iii-browser-sdk 0.25.0 → 0.25.1-alpha.1

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.
package/dist/index.cjs CHANGED
@@ -1,5 +1,5 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
- const require_utils = require('./utils-BUI0XQTZ.cjs');
2
+ const require_utils = require('./utils-Cy-Lu8WQ.cjs');
3
3
 
4
4
  //#region src/errors.ts
5
5
  /**
@@ -20,14 +20,13 @@ var RegistrationRejectedError = class extends Error {
20
20
  };
21
21
  /**
22
22
  * An error the SDK raises itself for an invocation, with a machine-readable
23
- * `code`: observe delivery errors (`NOT_OWNER_DELIVERED`,
24
- * `OBSERVER_NOT_ACTIVE`, `FILTERS_NOT_MATCHED`) and an invalid observe
25
- * descriptor (`INVALID_OBSERVE_DESCRIPTOR`). Mirrors the Node SDK.
23
+ * `code`: `LOCAL_DEPTH_EXCEEDED` (a local call nested too deep while the
24
+ * socket is closed) and `payload_too_large`. Mirrors the Node SDK.
26
25
  *
27
- * A call the engine answers with an error still rejects with the engine's
28
- * error body (`{ code, message, stacktrace? }`), as in earlier releases, and
29
- * so does a locally dispatched call whose handler throws: both paths reject
30
- * with the same value.
26
+ * A call the engine answers with an error rejects with the engine's error
27
+ * body (`{ code, message, stacktrace? }`), and so does a locally dispatched
28
+ * call whose handler or deliver hook throws: both paths reject with the same
29
+ * value.
31
30
  */
32
31
  var InvocationError = class extends Error {
33
32
  constructor(init) {
@@ -39,6 +38,110 @@ var InvocationError = class extends Error {
39
38
  }
40
39
  };
41
40
  /**
41
+ * The error a call that timed out rejects with, on the remote and the local
42
+ * path: an `Error` (its message unchanged from earlier releases) that also
43
+ * carries `code: 'TIMEOUT'` and the `function_id`, like the Node SDK's.
44
+ */
45
+ var InvocationTimeoutError = class extends Error {
46
+ constructor(ms, functionId) {
47
+ super(`Invocation timeout after ${ms}ms: ${functionId}`);
48
+ this.code = "TIMEOUT";
49
+ this.function_id = functionId;
50
+ }
51
+ };
52
+ /** What a failure reports when the thrown value cannot even be read (a getter or `toString` that throws). */
53
+ const UNREADABLE_FAILURE = "the handler failed with a value that cannot be read";
54
+ function safeString(value) {
55
+ try {
56
+ return String(value);
57
+ } catch {
58
+ return UNREADABLE_FAILURE;
59
+ }
60
+ }
61
+ /**
62
+ * An error body as the engine sends it, and as this SDK's own calls reject
63
+ * with: a plain (JSON-parsed) object with a string `code`, a string `message`
64
+ * and, optionally, a string `stacktrace`. A class instance or anything else
65
+ * with such fields is not one: it is reported through `String()`.
66
+ */
67
+ function isEngineErrorBody(value) {
68
+ if (value === null || typeof value !== "object") return false;
69
+ const proto = Object.getPrototypeOf(value);
70
+ if (proto !== Object.prototype && proto !== null) return false;
71
+ const body = value;
72
+ return typeof body.code === "string" && typeof body.message === "string" && (body.stacktrace === void 0 || typeof body.stacktrace === "string");
73
+ }
74
+ /**
75
+ * The error a handler's failure becomes, the same on the local and the remote
76
+ * path (code `invocation_failed`):
77
+ * - an `Error`, from any realm (an iframe's too): its message and stack;
78
+ * - an engine error body (a failed call's rejection, rethrown): its message and stacktrace;
79
+ * - anything else: `String(value)`.
80
+ * Never throws: when reading the value throws, a fixed message is reported, so
81
+ * the caller always gets its answer.
82
+ */
83
+ function handlerErrorBody(error) {
84
+ try {
85
+ if (error instanceof Error || Object.prototype.toString.call(error) === "[object Error]") {
86
+ const { message, stack } = error;
87
+ return {
88
+ code: "invocation_failed",
89
+ message: typeof message === "string" ? message : safeString(message),
90
+ stacktrace: typeof stack === "string" ? stack : void 0
91
+ };
92
+ }
93
+ if (isEngineErrorBody(error)) return {
94
+ code: "invocation_failed",
95
+ message: error.message,
96
+ stacktrace: error.stacktrace
97
+ };
98
+ return {
99
+ code: "invocation_failed",
100
+ message: String(error),
101
+ stacktrace: void 0
102
+ };
103
+ } catch {
104
+ return {
105
+ code: "invocation_failed",
106
+ message: safeString(error),
107
+ stacktrace: void 0
108
+ };
109
+ }
110
+ }
111
+ /**
112
+ * The error a deliver hook's failure becomes: an {@link ObserveRejection}, an
113
+ * {@link InvocationError}, a call that timed out ({@link InvocationTimeoutError})
114
+ * or an engine error body (a failed call's rejection, rethrown) keeps its code
115
+ * and message; anything else is a handler failure ({@link handlerErrorBody}).
116
+ * Never throws.
117
+ */
118
+ function deliverErrorBody(error) {
119
+ try {
120
+ if (error instanceof ObserveRejection) return {
121
+ code: error.code,
122
+ message: error.message
123
+ };
124
+ if (error instanceof InvocationError) {
125
+ const prefix = `${error.code}: `;
126
+ return {
127
+ code: error.code,
128
+ message: error.message.startsWith(prefix) ? error.message.slice(prefix.length) : error.message,
129
+ stacktrace: error.stacktrace
130
+ };
131
+ }
132
+ if (error instanceof InvocationTimeoutError) return {
133
+ code: error.code,
134
+ message: error.message
135
+ };
136
+ if (isEngineErrorBody(error)) return {
137
+ code: error.code,
138
+ message: error.message,
139
+ stacktrace: error.stacktrace
140
+ };
141
+ } catch {}
142
+ return handlerErrorBody(error);
143
+ }
144
+ /**
42
145
  * Thrown by an `onObserverAdded` hook to reject an observer with a code of
43
146
  * its own (`HTTP_ROUTE_CONFLICT`, `INVALID_CRON_EXPRESSION`, ...); any other
44
147
  * error rejects it with `OBSERVE_REJECTED`. Also the error `ObserverHandle.ready()`
@@ -46,11 +149,11 @@ var InvocationError = class extends Error {
46
149
  *
47
150
  * @example
48
151
  * ```typescript
49
- * onObserverAdded(obs) {
152
+ * iii.onObserverAdded('cron::on-tick', (obs) => {
50
153
  * if (!isValidCron(obs.args.expression)) {
51
154
  * throw new ObserveRejection('INVALID_CRON_EXPRESSION', 'invalid day-of-week field')
52
155
  * }
53
- * }
156
+ * })
54
157
  * ```
55
158
  */
56
159
  var ObserveRejection = class extends Error {
@@ -61,44 +164,6 @@ var ObserveRejection = class extends Error {
61
164
  }
62
165
  };
63
166
 
64
- //#endregion
65
- //#region src/iii-constants.ts
66
- /**
67
- * Constants for the III module.
68
- */
69
- /**
70
- * Engine function paths for internal operations.
71
- *
72
- * Naming note: `LIST_TRIGGERS` / `INFO_TRIGGERS` cover trigger TYPES
73
- * (templates). `LIST_REGISTERED_TRIGGERS` / `INFO_REGISTERED_TRIGGERS`
74
- * cover trigger INSTANCES (subscriber rows). The old
75
- * `engine::trigger-types::list` builtin has been removed and is now
76
- * served by `engine::triggers::list`.
77
- */
78
- const EngineFunctions = {
79
- LIST_FUNCTIONS: "engine::functions::list",
80
- INFO_FUNCTIONS: "engine::functions::info",
81
- LIST_WORKERS: "engine::workers::list",
82
- INFO_WORKERS: "engine::workers::info",
83
- LIST_TRIGGERS: "engine::triggers::list",
84
- INFO_TRIGGERS: "engine::triggers::info",
85
- LIST_REGISTERED_TRIGGERS: "engine::registered-triggers::list",
86
- INFO_REGISTERED_TRIGGERS: "engine::registered-triggers::info",
87
- REGISTER_WORKER: "engine::workers::register"
88
- };
89
- /** Engine trigger types */
90
- const EngineTriggers = { FUNCTIONS_AVAILABLE: "engine::functions-available" };
91
- /** Default reconnection configuration */
92
- const DEFAULT_BRIDGE_RECONNECTION_CONFIG = {
93
- initialDelayMs: 1e3,
94
- maxDelayMs: 3e4,
95
- backoffMultiplier: 2,
96
- jitterFactor: .3,
97
- maxRetries: -1
98
- };
99
- /** Default invocation timeout in milliseconds */
100
- const DEFAULT_INVOCATION_TIMEOUT_MS = 3e4;
101
-
102
167
  //#endregion
103
168
  //#region ../iii/src/filter/errors.ts
104
169
  const MAX_ENCODED_BYTES = 8192;
@@ -145,7 +210,7 @@ function checkString(s, at, what) {
145
210
  }
146
211
  }
147
212
  /** An object JSON writes member by member: a prototype-less object or one whose prototype is a realm's `Object.prototype`. */
148
- function isPlainObject(v) {
213
+ function isPlainObject$1(v) {
149
214
  const proto = Object.getPrototypeOf(v);
150
215
  return proto === null || Object.getPrototypeOf(proto) === null;
151
216
  }
@@ -209,7 +274,7 @@ function checkJson(src) {
209
274
  }
210
275
  continue;
211
276
  }
212
- if (!isPlainObject(value)) throw FilterError.invalid(`${where(at)}: ${describe(value)} is not a JSON object (use a plain object)`);
277
+ if (!isPlainObject$1(value)) throw FilterError.invalid(`${where(at)}: ${describe(value)} is not a JSON object (use a plain object)`);
213
278
  if (Object.getOwnPropertySymbols(value).length > 0) throw FilterError.invalid(`${where(at)}: symbol keys are not JSON`);
214
279
  for (const key of Object.getOwnPropertyNames(value)) {
215
280
  const member = at === "" ? key : `${at}.${key}`;
@@ -760,6 +825,221 @@ function checkLiteralDepth(path, name, literal) {
760
825
  }
761
826
  }
762
827
 
828
+ //#endregion
829
+ //#region ../iii/src/filter/filter-index.ts
830
+ function isScalar(value) {
831
+ return value === null || typeof value === "boolean" || typeof value === "number" || typeof value === "string";
832
+ }
833
+ /**
834
+ * The equality conditions of `source`, a filter that compiled: for each
835
+ * clause of its top-level `$and` (its keys and those of the filters its
836
+ * `$and`s hold, never inside `$or`, `$not` or `$any`), its `$eq` operand or
837
+ * its `$in` operands, when they are scalars. `path` is the parsed path,
838
+ * spelled one way whatever escapes the filter used.
839
+ */
840
+ function conditionsOf(source) {
841
+ const out = [];
842
+ const pending = [source];
843
+ while (pending.length > 0) {
844
+ const current = pending.pop();
845
+ for (const key of Object.keys(current)) {
846
+ const value = current[key];
847
+ if (key === "$and") {
848
+ for (const item of value) pending.push(item);
849
+ continue;
850
+ }
851
+ if (key.startsWith("$")) continue;
852
+ const ops = value;
853
+ const eq = ops.$eq;
854
+ const inItems = ops.$in;
855
+ const hasEq = Object.prototype.hasOwnProperty.call(ops, "$eq");
856
+ if (!hasEq && !Array.isArray(inItems)) continue;
857
+ const parsed = parsePath(key, false);
858
+ const path = JSON.stringify([parsed.root, ...parsed.segments.map((s) => s.key)]);
859
+ if (hasEq && isScalar(eq)) out.push({
860
+ path,
861
+ raw: key,
862
+ values: [eq]
863
+ });
864
+ if (Array.isArray(inItems) && inItems.length > 0 && inItems.every(isScalar)) out.push({
865
+ path,
866
+ raw: key,
867
+ values: [...new Set(inItems)]
868
+ });
869
+ }
870
+ }
871
+ return out;
872
+ }
873
+ /**
874
+ * Filters, each with a value and an order, matched against a document by an
875
+ * index of their equality conditions (see the module docs).
876
+ * {@link FilterIndex.matches} returns exactly the values whose filter
877
+ * matches the document (and that `accept` accepts), by ascending `order`.
878
+ */
879
+ var FilterIndex = class {
880
+ constructor() {
881
+ this.filed = /* @__PURE__ */ new Map();
882
+ this.scanned = /* @__PURE__ */ new Set();
883
+ this.paths = /* @__PURE__ */ new Map();
884
+ this.indexed = 0;
885
+ }
886
+ /** Entries held. */
887
+ get size() {
888
+ return this.filed.size;
889
+ }
890
+ /**
891
+ * Whether {@link FilterIndex.matches} can evaluate fewer filters than
892
+ * evaluating each entry's would. Looking a document's value up at an
893
+ * indexed path costs about one evaluation, and rules out the entries filed
894
+ * there under other values, so it can only when some indexed path files
895
+ * more than one entry. Otherwise evaluating each filter in order costs less
896
+ * and yields the same matches.
897
+ */
898
+ get narrows() {
899
+ return this.indexed > this.paths.size;
900
+ }
901
+ has(value) {
902
+ return this.filed.has(value);
903
+ }
904
+ /**
905
+ * Files `value` with `filter`, in place of the entry `value` had. `order`
906
+ * sorts the matches. The condition it is filed under is the one of the
907
+ * filter's top-level `$and` that the fewest entries share now (an `$eq`
908
+ * before an `$in` of several values).
909
+ */
910
+ insert(value, filter, order) {
911
+ this.remove(value);
912
+ const entry = {
913
+ value,
914
+ filter,
915
+ order
916
+ };
917
+ const condition = this.conditionFor(filter);
918
+ if (!condition) {
919
+ this.scanned.add(entry);
920
+ this.filed.set(value, { entry });
921
+ return;
922
+ }
923
+ let index = this.paths.get(condition.path);
924
+ if (!index) {
925
+ index = {
926
+ resolve: compilePath(parsePath(condition.raw, false)),
927
+ buckets: /* @__PURE__ */ new Map(),
928
+ entries: 0
929
+ };
930
+ this.paths.set(condition.path, index);
931
+ }
932
+ for (const scalar of condition.values) {
933
+ const bucket = index.buckets.get(scalar);
934
+ if (bucket) bucket.add(entry);
935
+ else index.buckets.set(scalar, new Set([entry]));
936
+ }
937
+ index.entries++;
938
+ this.indexed++;
939
+ this.filed.set(value, {
940
+ entry,
941
+ path: condition.path,
942
+ values: condition.values
943
+ });
944
+ }
945
+ /** Takes the entry of `value` out. */
946
+ remove(value) {
947
+ const filed = this.filed.get(value);
948
+ if (!filed) return;
949
+ this.filed.delete(value);
950
+ if (filed.path === void 0 || filed.values === void 0) {
951
+ this.scanned.delete(filed.entry);
952
+ return;
953
+ }
954
+ const index = this.paths.get(filed.path);
955
+ if (!index) return;
956
+ this.indexed--;
957
+ for (const scalar of filed.values) {
958
+ const bucket = index.buckets.get(scalar);
959
+ if (!bucket) continue;
960
+ bucket.delete(filed.entry);
961
+ if (bucket.size === 0) index.buckets.delete(scalar);
962
+ }
963
+ if (--index.entries === 0) this.paths.delete(filed.path);
964
+ }
965
+ /**
966
+ * The values whose filter matches `doc`, by ascending order. Resolves each
967
+ * indexed path of `doc` once, and evaluates the filters of the entries
968
+ * filed under the value found there and of the scanned entries
969
+ * ({@link FilterIndex.candidates} counts them); every other entry has a
970
+ * condition `doc` fails. `accept` is asked first, for each candidate.
971
+ */
972
+ matches(doc, accept) {
973
+ const found = [];
974
+ let sorted = true;
975
+ let last = -Infinity;
976
+ if (this.paths.size > 0) for (const index of this.paths.values()) {
977
+ const bucket = this.bucket(index, doc);
978
+ if (bucket === void 0) continue;
979
+ for (const entry of bucket) if ((accept === void 0 || accept(entry.value)) && entry.filter.matches(doc)) {
980
+ if (entry.order < last) sorted = false;
981
+ last = entry.order;
982
+ found.push(entry);
983
+ }
984
+ }
985
+ if (this.scanned.size > 0) {
986
+ for (const entry of this.scanned) if ((accept === void 0 || accept(entry.value)) && entry.filter.matches(doc)) {
987
+ if (entry.order < last) sorted = false;
988
+ last = entry.order;
989
+ found.push(entry);
990
+ }
991
+ }
992
+ if (!sorted) found.sort((a, b) => a.order - b.order);
993
+ const values = new Array(found.length);
994
+ for (let i = 0; i < found.length; i++) values[i] = found[i].value;
995
+ return values;
996
+ }
997
+ /** How many filters a match of `doc` evaluates: the entries filed under its values, and the scanned ones. */
998
+ candidates(doc) {
999
+ let n = this.scanned.size;
1000
+ for (const index of this.paths.values()) n += this.bucket(index, doc)?.size ?? 0;
1001
+ return n;
1002
+ }
1003
+ /**
1004
+ * The entries filed under `doc`'s value at the path. A value an index
1005
+ * cannot hold (absent, an array, an object) matches no condition, and
1006
+ * neither does a path whose reading throws: each filter filed under it
1007
+ * holds a clause on that path, and a filter whose reading throws does not
1008
+ * match.
1009
+ */
1010
+ bucket(index, doc) {
1011
+ let value;
1012
+ try {
1013
+ value = index.resolve(doc !== null && typeof doc === "object" ? doc : {}, void 0);
1014
+ } catch {
1015
+ return;
1016
+ }
1017
+ return isScalar(value) ? index.buckets.get(value) : void 0;
1018
+ }
1019
+ conditionFor(filter) {
1020
+ let best;
1021
+ for (const condition of conditionsOf(filter.source)) {
1022
+ const held = this.paths.get(condition.path);
1023
+ let sharing = 0;
1024
+ if (held) for (const scalar of condition.values) sharing += held.buckets.get(scalar)?.size ?? 0;
1025
+ const score = [
1026
+ condition.values.length > 1 ? 1 : 0,
1027
+ sharing,
1028
+ condition.values.length
1029
+ ];
1030
+ if (best === void 0 || lessThan(score, best.score)) best = {
1031
+ condition,
1032
+ score
1033
+ };
1034
+ }
1035
+ return best?.condition;
1036
+ }
1037
+ };
1038
+ function lessThan(a, b) {
1039
+ for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) return a[i] < b[i];
1040
+ return false;
1041
+ }
1042
+
763
1043
  //#endregion
764
1044
  //#region ../iii/src/filter/index.ts
765
1045
  /**
@@ -797,6 +1077,49 @@ function compileFilter(src, options) {
797
1077
  /** The filter that matches every document (`{}`). */
798
1078
  const MATCH_ALL = compileFilter({});
799
1079
 
1080
+ //#endregion
1081
+ //#region src/iii-constants.ts
1082
+ /**
1083
+ * Constants for the III module.
1084
+ */
1085
+ /** Engine function paths for internal operations. */
1086
+ const EngineFunctions = {
1087
+ LIST_FUNCTIONS: "engine::functions::list",
1088
+ INFO_FUNCTIONS: "engine::functions::info",
1089
+ LIST_WORKERS: "engine::workers::list",
1090
+ INFO_WORKERS: "engine::workers::info",
1091
+ REGISTER_WORKER: "engine::workers::register"
1092
+ };
1093
+ /**
1094
+ * The event sources the engine hosts: private functions whose handler
1095
+ * returns the event, observed with `iii.observe(EngineSources.X, target)`.
1096
+ * None takes args; filter on the event (`input`) instead.
1097
+ */
1098
+ const EngineSources = {
1099
+ /** A function was registered or unregistered; each row carries `observer_count`. */
1100
+ FUNCTIONS_CHANGED: "engine::on-functions-changed",
1101
+ /** A worker connected or left. */
1102
+ WORKERS_CHANGED: "engine::on-workers-changed",
1103
+ /** An observer changed state: `{ observer_id, function_id, target, state, reason? }`. */
1104
+ OBSERVERS_CHANGED: "engine::on-observers-changed",
1105
+ /** A log record. */
1106
+ LOG: "observability::on-log",
1107
+ /** A finished span. */
1108
+ SPAN: "observability::on-span",
1109
+ /** The engine's configuration was reloaded. */
1110
+ CONFIGURATION_UPDATED: "configuration::on-updated"
1111
+ };
1112
+ /** Default reconnection configuration */
1113
+ const DEFAULT_BRIDGE_RECONNECTION_CONFIG = {
1114
+ initialDelayMs: 1e3,
1115
+ maxDelayMs: 3e4,
1116
+ backoffMultiplier: 2,
1117
+ jitterFactor: .3,
1118
+ maxRetries: -1
1119
+ };
1120
+ /** Default invocation timeout in milliseconds */
1121
+ const DEFAULT_INVOCATION_TIMEOUT_MS = 3e4;
1122
+
800
1123
  //#endregion
801
1124
  //#region src/iii-types.ts
802
1125
  /**
@@ -804,13 +1127,23 @@ const MATCH_ALL = compileFilter({});
804
1127
  * `engine::workers::register` `features` from the SDK).
805
1128
  */
806
1129
  const FEATURE_OBSERVE_V1 = "observe.v1";
1130
+ /**
1131
+ * The host delivers the calls of its functions (routed ones included), and
1132
+ * functions may set `args_format`, `private`, `observable: false` and
1133
+ * `onObservationDeliver`. Includes `observe.v1`.
1134
+ */
1135
+ const FEATURE_OBSERVE_V2 = "observe.v2";
807
1136
  const FEATURE_LOCAL_DISPATCH_V1 = "local-dispatch.v1";
808
1137
  /**
809
1138
  * What this SDK declares in `engine::workers::register`. Not
810
1139
  * `large-messages.v1`, unlike the other SDKs: a browser receives one 16 MiB
811
1140
  * WebSocket frame at most.
812
1141
  */
813
- const SDK_FEATURES = [FEATURE_OBSERVE_V1, FEATURE_LOCAL_DISPATCH_V1];
1142
+ const SDK_FEATURES = [
1143
+ FEATURE_OBSERVE_V1,
1144
+ FEATURE_OBSERVE_V2,
1145
+ FEATURE_LOCAL_DISPATCH_V1
1146
+ ];
814
1147
 
815
1148
  //#endregion
816
1149
  //#region src/invocation-context.ts
@@ -833,10 +1166,10 @@ const MAX_RUNNING_INVOCATION_MS = 600 * 1e3;
833
1166
  *
834
1167
  * One scope for the whole page, like the Node SDK's one `AsyncLocalStorage`
835
1168
  * per process: a handler of one worker that calls another worker's
836
- * `trigger()` is that call's caller.
1169
+ * `call()` is that call's caller.
837
1170
  */
838
1171
  let current;
839
- /** The public views handed out, so `withInvocation(view, fn)` restores everything (metadata included). */
1172
+ /** The public views handed out, so `withInvocation(view, fn)` restores the invocation they were taken from. */
840
1173
  const views = /* @__PURE__ */ new WeakMap();
841
1174
  function currentContext() {
842
1175
  return current;
@@ -880,33 +1213,37 @@ function live() {
880
1213
  }
881
1214
  return out;
882
1215
  }
883
- /** What a fallback attribution lends: the invocation without its metadata sidecar (one object per invocation). */
884
- const lent = /* @__PURE__ */ new WeakMap();
885
- function lend(ctx) {
886
- let view = lent.get(ctx);
887
- if (!view) {
888
- const { metadata: _, ...rest } = ctx;
889
- view = rest;
890
- lent.set(ctx, view);
891
- }
892
- return view;
1216
+ /**
1217
+ * The invocations whose function's deliver hook is running: code after the
1218
+ * hook's `await`s falls back to them (see {@link callContext}).
1219
+ */
1220
+ const delivering = /* @__PURE__ */ new WeakSet();
1221
+ /**
1222
+ * Marks `ctx` as delivering (its function's deliver hook is running); call
1223
+ * the returned function when the hook settles.
1224
+ */
1225
+ function trackDelivering(ctx) {
1226
+ delivering.add(ctx);
1227
+ return () => {
1228
+ delivering.delete(ctx);
1229
+ };
893
1230
  }
894
1231
  /**
895
- * The invocation a call, an emit or a report made now belongs to. Inside a
896
- * scope, the scope's. Outside any scope (code after an `await`), the running
897
- * invocation when that is unambiguous: it is the only one running and it is
898
- * an observe activation. It lends its ids, caller and trace context, never its
899
- * metadata: filters on `metadata.*` see only what a real scope carries.
900
- * Otherwise none, and the call carries no `caller`: the SDK cannot tell which
901
- * handler, if any, made it.
1232
+ * The invocation a call or a report made now belongs to. Inside a scope, the
1233
+ * scope's. Outside any scope (code after an `await`), the running invocation
1234
+ * when that is unambiguous: it is the only one running, and it is an observe
1235
+ * activation or its function's deliver hook is running (the calls the hook
1236
+ * makes after an `await`, through its observers or not). It lends its ids,
1237
+ * caller and trace context. Otherwise none, and the call carries no
1238
+ * `caller`: the SDK cannot tell which handler, if any, made it.
902
1239
  */
903
1240
  function callContext() {
904
1241
  if (current) return current;
905
1242
  const all = live();
906
- return all.length === 1 && all[0].activation ? lend(all[0]) : void 0;
1243
+ return all.length === 1 && (all[0].activation || delivering.has(all[0])) ? all[0] : void 0;
907
1244
  }
908
1245
  /**
909
- * The `observe_depth` a call, an emit or a report made now carries. Inside a
1246
+ * The `observe_depth` a call or a report made now carries. Inside a
910
1247
  * scope, the scope's. Outside any scope, the deepest running invocation's:
911
1248
  * the engine's loop guard counts on this depth, so code after an `await`
912
1249
  * over-counts (a chain may stop earlier than `max_observe_depth`) rather than
@@ -973,7 +1310,7 @@ function runInContext(ctx, fn) {
973
1310
  current = previous;
974
1311
  }
975
1312
  }
976
- /** The public view of the current invocation (without the metadata sidecar). */
1313
+ /** The public view of the current invocation. */
977
1314
  function publicContext(ctx) {
978
1315
  if (!ctx) return void 0;
979
1316
  const view = {
@@ -1018,278 +1355,123 @@ function contextFromView(view) {
1018
1355
  }
1019
1356
 
1020
1357
  //#endregion
1021
- //#region src/observe-wire.ts
1022
- /** CONTRACT D1: what an absent `capture` means. */
1023
- const DEFAULT_CAPTURE = [
1024
- "input",
1025
- "output",
1026
- "caller"
1027
- ];
1028
- function isRecord(v) {
1029
- return v !== null && typeof v === "object" && !Array.isArray(v);
1358
+ //#region src/observable.ts
1359
+ /**
1360
+ * The host side of observe (v2 §4): per-function observer state, the
1361
+ * observer hooks of the worker and of the function, the `Observer` object
1362
+ * handed to them, matching (the key index, and the index of the filters'
1363
+ * equality conditions), and the delivery of each call of a hosted function.
1364
+ */
1365
+ /** CONTRACT D11: an observer hook still running after this is `OWNER_TIMEOUT`. */
1366
+ const OBSERVE_HOOK_TIMEOUT_MS = 3e4;
1367
+ function sameJson(a, b) {
1368
+ return JSON.stringify(a) === JSON.stringify(b);
1030
1369
  }
1031
- function str(v) {
1032
- return typeof v === "string" ? v : void 0;
1370
+ /** Whether `obs` is served with the view `info` announces: its filters, target, capture and `on`. */
1371
+ function sameView(obs, info) {
1372
+ return obs.target === info.target && obs.on === info.on && sameJson(obs.capture, info.capture) && sameJson(obs.filters, info.filters);
1033
1373
  }
1034
- function num(v) {
1035
- return typeof v === "number" ? v : void 0;
1374
+ function rejectionBody(error) {
1375
+ if (error instanceof ObserveRejection) return {
1376
+ code: error.code,
1377
+ message: error.message
1378
+ };
1379
+ return {
1380
+ code: "OBSERVE_REJECTED",
1381
+ message: error instanceof Error ? error.message : String(error)
1382
+ };
1036
1383
  }
1037
- function errorBody(v) {
1038
- if (!isRecord(v)) return void 0;
1039
- const body = {
1040
- code: String(v.code ?? ""),
1041
- message: String(v.message ?? "")
1384
+ function onAccepts(on, ok) {
1385
+ return on === "complete" || (on === "success" ? ok : on === "error" ? !ok : false);
1386
+ }
1387
+ /**
1388
+ * Whether two copies of a value hold the same JSON data: primitives, arrays
1389
+ * and plain objects, compared member by member in one walk. Any other object
1390
+ * (a `Date`, a class instance, a channel reader) is the same only as itself,
1391
+ * and so is an object the walk reaches twice (a shared member or a cycle).
1392
+ * A local call compares the handler's copy of its input with the copy the
1393
+ * delivery took when the call started.
1394
+ */
1395
+ function sameData(a, b) {
1396
+ const left = [a];
1397
+ const right = [b];
1398
+ const seen = /* @__PURE__ */ new Set();
1399
+ while (left.length > 0) {
1400
+ const x = left.pop();
1401
+ const y = right.pop();
1402
+ if (x === y || Number.isNaN(x) && Number.isNaN(y)) continue;
1403
+ if (x === null || y === null || typeof x !== "object" || typeof y !== "object" || seen.has(x)) return false;
1404
+ seen.add(x);
1405
+ if (Array.isArray(x)) {
1406
+ if (!Array.isArray(y) || x.length !== y.length) return false;
1407
+ for (let i = 0; i < x.length; i++) {
1408
+ left.push(x[i]);
1409
+ right.push(y[i]);
1410
+ }
1411
+ continue;
1412
+ }
1413
+ if (Array.isArray(y) || !isPlainObject(x) || !isPlainObject(y)) return false;
1414
+ const keys = Object.keys(x);
1415
+ if (keys.length !== Object.keys(y).length) return false;
1416
+ for (const key of keys) {
1417
+ if (!Object.prototype.hasOwnProperty.call(y, key)) return false;
1418
+ left.push(x[key]);
1419
+ right.push(y[key]);
1420
+ }
1421
+ }
1422
+ return true;
1423
+ }
1424
+ function isPlainObject(value) {
1425
+ const proto = Object.getPrototypeOf(value);
1426
+ return proto === Object.prototype || proto === null;
1427
+ }
1428
+ /** What filters read from a call; a call without `status` reads as a successful one. */
1429
+ function filterDoc(call) {
1430
+ const doc = {
1431
+ input: call.input,
1432
+ caller: call.caller,
1433
+ metadata: call.metadata
1042
1434
  };
1043
- if (typeof v.stacktrace === "string") body.stacktrace = v.stacktrace;
1044
- return body;
1435
+ if (call.status === "error") doc.error = call.error;
1436
+ else doc.output = call.output;
1437
+ return doc;
1045
1438
  }
1046
- /** Copies the wire caller, dropping `null`s and a `parent` inside `parent`. */
1047
- function decodeCaller(v, depth = 0) {
1048
- if (!isRecord(v)) return void 0;
1049
- const caller = {};
1050
- for (const key of [
1051
- "worker_id",
1052
- "worker_name",
1053
- "function_id",
1054
- "invocation_id"
1055
- ]) {
1056
- const value = str(v[key]);
1057
- if (value !== void 0) caller[key] = value;
1058
- }
1059
- if (depth === 0) {
1060
- const parent = decodeCaller(v.parent, 1);
1061
- if (parent) caller.parent = parent;
1062
- }
1063
- return caller;
1064
- }
1065
- function decodeActivation(v) {
1066
- if (!isRecord(v) || typeof v.observer_id !== "string") return void 0;
1067
- const activation = { observer_id: v.observer_id };
1068
- if (typeof v.activation_id === "string") activation.activation_id = v.activation_id;
1069
- return activation;
1070
- }
1071
- /** An observer as the owner sees it (`observeradded.observer`, `functionregistered.observers[]`). */
1072
- function decodeObserverInfo(v) {
1073
- const raw = isRecord(v) ? v : {};
1074
- const info = {
1075
- id: String(raw.id ?? ""),
1076
- args: isRecord(raw.args) ? raw.args : {},
1077
- filters: raw.filters === void 0 ? {} : raw.filters,
1078
- target: String(raw.target ?? ""),
1079
- capture: Array.isArray(raw.capture) ? raw.capture.filter((c) => typeof c === "string") : [...DEFAULT_CAPTURE],
1080
- on: str(raw.on) ?? "success"
1081
- };
1082
- if (isRecord(raw.legacy) && typeof raw.legacy.trigger_type === "string") info.legacy = {
1083
- trigger_type: raw.legacy.trigger_type,
1084
- config: raw.legacy.config ?? null
1085
- };
1086
- return info;
1087
- }
1088
- function decodeFunctionRegistered(v) {
1089
- return {
1090
- id: String(v.id ?? ""),
1091
- namespace: String(v.namespace ?? ""),
1092
- revision: num(v.revision) ?? 0,
1093
- local_dispatch: v.local_dispatch === true,
1094
- observers: Array.isArray(v.observers) ? v.observers.map(decodeObserverInfo) : []
1095
- };
1096
- }
1097
- function decodeObserverAdded(v) {
1098
- return {
1099
- function_id: String(v.function_id ?? ""),
1100
- namespace: String(v.namespace ?? ""),
1101
- revision: num(v.revision) ?? 0,
1102
- observer: decodeObserverInfo(v.observer)
1103
- };
1104
- }
1105
- function decodeObserverRemoved(v) {
1106
- return {
1107
- function_id: String(v.function_id ?? ""),
1108
- namespace: String(v.namespace ?? ""),
1109
- revision: num(v.revision) ?? 0,
1110
- id: String(v.id ?? "")
1111
- };
1112
- }
1113
- function decodeObserveResult(v) {
1114
- const msg = {
1115
- id: String(v.id ?? ""),
1116
- state: String(v.state ?? "")
1117
- };
1118
- const error = errorBody(v.error);
1119
- if (error) msg.error = error;
1120
- if (Array.isArray(v.warnings)) msg.warnings = v.warnings.filter((w) => typeof w === "string");
1121
- return msg;
1122
- }
1123
- function decodeObserverStateChanged(v) {
1124
- const msg = {
1125
- id: String(v.id ?? ""),
1126
- state: String(v.state ?? ""),
1127
- fires: num(v.fires) ?? 0
1128
- };
1129
- const reason = errorBody(v.reason);
1130
- if (reason) msg.reason = reason;
1131
- return msg;
1132
- }
1133
- function decodeWorkerRegistered(v) {
1134
- const msg = { worker_id: String(v.worker_id ?? "") };
1135
- if (typeof v.reattach_token === "string") msg.reattach_token = v.reattach_token;
1136
- if (Array.isArray(v.features)) msg.features = v.features.filter((f) => typeof f === "string");
1137
- return msg;
1138
- }
1139
- /** The observe fields of an inbound `invokefunction` (`caller`, `observe_depth`, `activation`). */
1140
- function decodeInvokeFunction(v) {
1141
- const msg = {
1142
- function_id: String(v.function_id ?? ""),
1143
- data: v.data
1144
- };
1145
- if (typeof v.invocation_id === "string") msg.invocation_id = v.invocation_id;
1146
- if (typeof v.traceparent === "string") msg.traceparent = v.traceparent;
1147
- if (typeof v.baggage === "string") msg.baggage = v.baggage;
1148
- if (isRecord(v.action)) msg.action = v.action;
1149
- if (v.metadata !== void 0 && v.metadata !== null) msg.metadata = v.metadata;
1150
- if (typeof v.namespace === "string") msg.namespace = v.namespace;
1151
- const caller = decodeCaller(v.caller);
1152
- if (caller) msg.caller = caller;
1153
- const depth = num(v.observe_depth);
1154
- if (depth !== void 0 && depth > 0) msg.observe_depth = depth;
1155
- const activation = decodeActivation(v.activation);
1156
- if (activation) msg.activation = activation;
1157
- return msg;
1158
- }
1159
- /** Drops `parent` (one level only). */
1160
- function stripCaller(caller) {
1161
- if (!caller) return void 0;
1162
- const { parent: _, ...rest } = caller;
1163
- return rest;
1164
- }
1165
- /** JSON's view of a message: `undefined` fields left out, no caller-owned objects retained. */
1166
- function snapshot(value) {
1167
- return JSON.parse(JSON.stringify(value));
1168
- }
1169
- /**
1170
- * `observe { id, source, target, ... }` from the three arguments of
1171
- * `iii.observe`. Only what the caller set is sent; the engine applies the
1172
- * defaults. `resolveNamespace` gives the namespace of an unqualified id (this
1173
- * worker's, `default` for `engine::*`).
1174
- */
1175
- function buildObserveMessage(id, source, target, options, resolveNamespace) {
1176
- const targetRef = typeof target === "string" ? { function_id: target } : target;
1177
- const sourceNamespace = resolveNamespace(source.namespace, source.function_id, "ObserveSource.namespace");
1178
- const targetNamespace = resolveNamespace(targetRef.namespace, targetRef.function_id, "Target.namespace");
1179
- return snapshot({
1180
- id,
1181
- source: {
1182
- function_id: source.function_id,
1183
- namespace: sourceNamespace,
1184
- args: source.args,
1185
- filters: source.filters,
1186
- capture: source.capture,
1187
- on: source.on,
1188
- deliver: source.deliver
1189
- },
1190
- target: {
1191
- function_id: targetRef.function_id,
1192
- namespace: targetNamespace
1193
- },
1194
- metadata: options?.metadata,
1195
- max_fires: options?.max_fires,
1196
- expires_in_ms: options?.expires_in_ms,
1197
- max_in_flight: options?.max_in_flight
1198
- });
1199
- }
1200
- /** `registerfunction.observe`: the four fields that travel, or `undefined` when none is set. */
1201
- function observeDescriptor(hooks) {
1202
- if (!hooks) return void 0;
1203
- const descriptor = snapshot({
1204
- delivery: hooks.delivery,
1205
- args_format: hooks.args_format,
1206
- legacy_trigger_type: hooks.legacy_trigger_type,
1207
- allow: hooks.allow
1208
- });
1209
- return Object.keys(descriptor).length > 0 ? descriptor : void 0;
1210
- }
1211
- function buildObserverAck(ack) {
1212
- const msg = {
1213
- function_id: ack.function_id,
1214
- id: ack.id,
1215
- revision: ack.revision
1216
- };
1217
- if (ack.namespace !== void 0) msg.namespace = ack.namespace;
1218
- if (ack.error) msg.error = {
1219
- code: ack.error.code,
1220
- message: ack.error.message
1221
- };
1222
- return msg;
1223
- }
1224
- /**
1225
- * An outbound `invokefunction`. `observe_depth` is left out when 0, and every
1226
- * optional field when unset.
1227
- */
1228
- function buildInvokeFunction(init) {
1229
- const msg = {};
1230
- if (init.invocation_id !== void 0) msg.invocation_id = init.invocation_id;
1231
- msg.function_id = init.function_id;
1232
- msg.data = init.data;
1233
- if (init.traceparent !== void 0) msg.traceparent = init.traceparent;
1234
- if (init.baggage !== void 0) msg.baggage = init.baggage;
1235
- if (init.action !== void 0) msg.action = init.action;
1236
- if (init.metadata !== void 0) msg.metadata = init.metadata;
1237
- if (init.namespace !== void 0) msg.namespace = init.namespace;
1238
- if (init.caller !== void 0) msg.caller = init.caller;
1239
- if (init.observe_depth !== void 0 && init.observe_depth > 0) msg.observe_depth = init.observe_depth;
1240
- if (init.activation !== void 0) msg.activation = init.activation;
1241
- return msg;
1242
- }
1243
- /** The caller an outbound call asserts from inside a handler: that handler, and its own caller one level up. */
1244
- function callerFor(ctx) {
1245
- const caller = {
1246
- function_id: ctx.function_id,
1247
- invocation_id: ctx.invocation_id
1248
- };
1249
- const parent = stripCaller(ctx.caller);
1250
- if (parent && Object.keys(parent).length > 0) caller.parent = parent;
1251
- return caller;
1252
- }
1253
-
1254
- //#endregion
1255
- //#region src/observable.ts
1256
1439
  /**
1257
- * The owner side of observe (sdk.md §1, §4.1–§4.3): per-function observer
1258
- * state, the observe hooks, the `Observer` object handed to them, and the
1259
- * reports of local invocations and `obs.emit` events.
1440
+ * The caller a report item carries: the engine sets `worker_id` and
1441
+ * `worker_name` itself, so they are left out (a `parent` keeps its own).
1442
+ * Nothing for a call made outside any handler.
1260
1443
  */
1261
- /** CONTRACT D11: `onObserverAdded` (and `onObserverRemoved`) still running after this is `OWNER_TIMEOUT`. */
1262
- const OBSERVE_HOOK_TIMEOUT_MS = 3e4;
1263
- function sameJson(a, b) {
1264
- return JSON.stringify(a) === JSON.stringify(b);
1444
+ function reportCaller(caller) {
1445
+ if (!caller) return void 0;
1446
+ const { worker_id: _, worker_name: __, ...rest } = caller;
1447
+ return Object.keys(rest).length > 0 ? rest : void 0;
1265
1448
  }
1266
- function rejectionBody(error) {
1267
- if (error instanceof ObserveRejection) return {
1268
- code: error.code,
1269
- message: error.message
1270
- };
1271
- return {
1272
- code: "OBSERVE_REJECTED",
1273
- message: error instanceof Error ? error.message : String(error)
1274
- };
1449
+ /** The key functions of a match hook given as keys, if it is one. */
1450
+ function matchKeysOf(hook) {
1451
+ return hook !== void 0 && typeof hook !== "function" ? hook : void 0;
1275
1452
  }
1276
- function onAccepts(on, ok) {
1277
- return on === "complete" || (on === "success" ? ok : on === "error" ? !ok : false);
1453
+ function keyList(keys) {
1454
+ return typeof keys === "string" ? [keys] : keys;
1278
1455
  }
1279
- /** The `Observer` an owner receives. Its identity is stable while the observer lives. */
1456
+ /** The `Observer` a host receives. Its identity is stable while the observer lives. */
1280
1457
  var ObserverImpl = class {
1281
1458
  constructor(owner, info, filter, revision) {
1282
1459
  this.owner = owner;
1283
1460
  this.active = false;
1461
+ this.activatedSeq = 0;
1284
1462
  this.adding = false;
1463
+ this.levels = {
1464
+ worker: "none",
1465
+ fn: "none"
1466
+ };
1467
+ this.acceptance = "pending";
1285
1468
  this.id = info.id;
1286
1469
  this.function_id = owner.functionId;
1287
1470
  this.args = info.args;
1288
1471
  this.filters = info.filters;
1289
1472
  this.target = info.target;
1290
- this.capture = info.capture;
1291
1473
  this.on = info.on;
1292
- if (info.legacy) this.legacy = info.legacy;
1474
+ this.capture = info.capture;
1293
1475
  this.filter = filter;
1294
1476
  this.revision = revision;
1295
1477
  }
@@ -1298,21 +1480,36 @@ var ObserverImpl = class {
1298
1480
  this.filters = info.filters;
1299
1481
  this.filter = filter;
1300
1482
  this.target = info.target;
1301
- this.capture = info.capture;
1302
1483
  this.on = info.on;
1484
+ this.capture = info.capture;
1303
1485
  }
1304
- matches(doc) {
1305
- return this.filter.matches(doc);
1306
- }
1307
- emit(event) {
1308
- return this.owner.emit(this, event);
1486
+ matches(call) {
1487
+ return onAccepts(this.on, call.status !== "error") && this.filter.matches(filterDoc(call));
1309
1488
  }
1310
- call(payload, opts) {
1311
- return this.owner.call(this, payload, opts?.timeoutMs);
1489
+ accepted() {
1490
+ const state = this.acceptance;
1491
+ if (state === "accepted") return Promise.resolve();
1492
+ if (state !== "pending") return Promise.reject(new ObserveRejection(state.code, state.message));
1493
+ return new Promise((resolve, reject) => {
1494
+ this.waiters ?? (this.waiters = []);
1495
+ this.waiters.push({
1496
+ resolve,
1497
+ reject
1498
+ });
1499
+ });
1312
1500
  }
1313
1501
  reject(code, message) {
1314
1502
  this.owner.reject(this, code, message);
1315
1503
  }
1504
+ /** @internal Acked (`accepted`) or never to be: settles `accepted()`, once. */
1505
+ settleAcceptance(outcome) {
1506
+ if (this.acceptance !== "pending") return;
1507
+ this.acceptance = outcome;
1508
+ const waiters = this.waiters ?? [];
1509
+ this.waiters = void 0;
1510
+ for (const waiter of waiters) if (outcome === "accepted") waiter.resolve();
1511
+ else waiter.reject(new ObserveRejection(outcome.code, outcome.message));
1512
+ }
1316
1513
  toJSON() {
1317
1514
  return {
1318
1515
  id: this.id,
@@ -1320,21 +1517,19 @@ var ObserverImpl = class {
1320
1517
  args: this.args,
1321
1518
  filters: this.filters,
1322
1519
  target: this.target,
1323
- capture: this.capture,
1324
1520
  on: this.on,
1325
- ...this.legacy ? { legacy: this.legacy } : {}
1521
+ capture: this.capture
1326
1522
  };
1327
1523
  }
1328
1524
  };
1329
1525
  /**
1330
1526
  * One registered function's observers, as the engine pushed them
1331
1527
  * (`functionregistered`, `observeradded`, `observerremoved`). Hooks run one
1332
- * at a time, in revision order.
1528
+ * at a time, in the order the engine announced the observers.
1333
1529
  */
1334
1530
  var FunctionObservers = class {
1335
- constructor(functionId, hooks, localDispatchOption, hasHandler, host) {
1531
+ constructor(functionId, localDispatchOption, hasHandler, host) {
1336
1532
  this.functionId = functionId;
1337
- this.hooks = hooks;
1338
1533
  this.localDispatchOption = localDispatchOption;
1339
1534
  this.hasHandler = hasHandler;
1340
1535
  this.host = host;
@@ -1344,17 +1539,79 @@ var FunctionObservers = class {
1344
1539
  this.revision = -1;
1345
1540
  this.known = /* @__PURE__ */ new Map();
1346
1541
  this.compiled = [];
1542
+ this.activations = 0;
1347
1543
  this.queue = Promise.resolve();
1348
1544
  this.disposed = false;
1349
1545
  this.releases = 0;
1350
- this.delivery = hooks?.delivery === "owner" ? "owner" : "auto";
1546
+ this.filterIndex = new FilterIndex();
1547
+ this.matchFailureLogged = false;
1548
+ this.matchChanged();
1549
+ }
1550
+ get reporter() {
1551
+ return this.host.reporter;
1552
+ }
1553
+ /** @internal */
1554
+ observeV2() {
1555
+ return this.host.observeV2();
1556
+ }
1557
+ /**
1558
+ * Whether a call would reach anyone. Without a call: any active observer
1559
+ * (one load). With a call, on a function matched by keys: an observer filed
1560
+ * under one of its keys (one lookup per key). Otherwise the call is not read.
1561
+ */
1562
+ isObserved(call) {
1563
+ if (this.compiled.length === 0) return false;
1564
+ const keys = this.matchKeys;
1565
+ const index = this.index;
1566
+ if (call === void 0 || !keys || !index) return true;
1567
+ for (const key of this.callKeys(keys, call)) if (index.has(key)) return true;
1568
+ return false;
1569
+ }
1570
+ /**
1571
+ * The observers of the call's snapshot that want `call` (`onObservationMatch`):
1572
+ * all of `snapshot` without a match hook, those of it the predicate accepts,
1573
+ * or those filed under one of the call's keys that joined the active set no
1574
+ * later than `activations` (the count when the call started), each once. A
1575
+ * match hook that throws matches nothing.
1576
+ */
1577
+ matching(call, snapshot, activations) {
1578
+ const hook = this.host.hooks(this.functionId).match;
1579
+ if (hook === void 0) return snapshot;
1580
+ if (typeof hook === "function") return snapshot.filter((obs) => {
1581
+ try {
1582
+ return hook(obs, call) === true;
1583
+ } catch (error) {
1584
+ this.matchFailed(error);
1585
+ return false;
1586
+ }
1587
+ });
1588
+ const index = this.index;
1589
+ if (this.matchKeys !== hook || !index) return [];
1590
+ const found = /* @__PURE__ */ new Set();
1591
+ for (const key of this.callKeys(hook, call)) {
1592
+ const filed = index.get(key);
1593
+ if (!filed) continue;
1594
+ for (const obs of filed) if (obs.activatedSeq <= activations) found.add(obs);
1595
+ }
1596
+ return [...found];
1351
1597
  }
1352
- /** Callbacks or owner delivery: what needs `observe.v1` on both sides. */
1353
- get needsObserve() {
1354
- return this.delivery === "owner" || !!this.hooks?.onObserverAdded || !!this.hooks?.onObserverRemoved;
1598
+ /** The function has a match hook (`onObservationMatch`) now. */
1599
+ hasMatchHook() {
1600
+ return this.host.hooks(this.functionId).match !== void 0;
1355
1601
  }
1356
- isObserved() {
1357
- return this.compiled.length > 0;
1602
+ /**
1603
+ * The active observers whose `on` accepts a call that succeeded (`ok`) or
1604
+ * failed and whose filters match `doc`, in the order of `compiled`. Matched
1605
+ * through the index of their filters' equality conditions when it narrows
1606
+ * them (`FilterIndex.narrows`): the call evaluates the filters of the
1607
+ * observers the index does not rule out. Otherwise each observer of
1608
+ * `compiled` is evaluated in order, which costs less and yields the same
1609
+ * observers in the same order.
1610
+ */
1611
+ selectActive(doc, ok) {
1612
+ const index = this.filterIndex;
1613
+ if (!index.narrows) return this.compiled.filter((obs) => onAccepts(obs.on, ok) && obs.filter.matches(doc));
1614
+ return index.matches(doc, (obs) => onAccepts(obs.on, ok));
1358
1615
  }
1359
1616
  observers() {
1360
1617
  return [...this.compiled];
@@ -1367,9 +1624,10 @@ var FunctionObservers = class {
1367
1624
  this.localDispatch = msg.local_dispatch && this.localDispatchOption && this.hasHandler;
1368
1625
  this.namespace = msg.namespace;
1369
1626
  this.revision = msg.revision;
1627
+ const releases = this.releases;
1370
1628
  this.enqueue(async () => {
1371
1629
  try {
1372
- await this.applySet(msg.observers, msg.revision, msg.namespace);
1630
+ if (this.releases === releases) await this.applySet(msg.observers, msg.revision, msg.namespace);
1373
1631
  } finally {
1374
1632
  this.confirmedEpoch = epoch;
1375
1633
  this.host.reporter.flush();
@@ -1379,8 +1637,12 @@ var FunctionObservers = class {
1379
1637
  onObserverAdded(msg) {
1380
1638
  if (this.disposed || msg.revision <= this.revision) return;
1381
1639
  this.revision = msg.revision;
1640
+ const releases = this.releases;
1382
1641
  this.enqueue(async () => {
1383
- if (this.known.get(msg.observer.id)?.rejection) await this.remove(msg.observer.id);
1642
+ if (this.disposed || this.releases !== releases || this.releasedEpoch !== void 0) return;
1643
+ const held = this.known.get(msg.observer.id);
1644
+ if (held && this.reack(held, msg.observer, msg.revision, msg.namespace, false)) return;
1645
+ if (held) await this.remove(held.id);
1384
1646
  await this.add(msg.observer, msg.revision, msg.namespace);
1385
1647
  });
1386
1648
  }
@@ -1390,9 +1652,10 @@ var FunctionObservers = class {
1390
1652
  this.enqueue(() => this.remove(msg.id));
1391
1653
  }
1392
1654
  /**
1393
- * `RegistrationRejected{FUNCTION_NAMESPACE_CONFLICT}`: no local dispatch, no
1394
- * observers, and its held reports are discarded (they could never be
1395
- * confirmed, and would starve other functions of buffer).
1655
+ * The engine refused the function (`registrationrejected`), or it no
1656
+ * longer holds it here: no local dispatch, no observers, and its held
1657
+ * reports are discarded (they could never be confirmed, and would starve
1658
+ * other functions of buffer).
1396
1659
  */
1397
1660
  onRegistrationRejected(epoch) {
1398
1661
  this.confirmed = false;
@@ -1409,30 +1672,134 @@ var FunctionObservers = class {
1409
1672
  this.onRegistrationRejected(-1);
1410
1673
  }
1411
1674
  /**
1675
+ * An `onObserverAdded` was set at `level` (the worker's, or this
1676
+ * function's): the active observers that were set up without one there are
1677
+ * caught up. It runs for each of them, in the hook queue; a throw
1678
+ * late-rejects that observer. One warning names the function and how many
1679
+ * observers were active without the hook.
1680
+ */
1681
+ catchUp(level) {
1682
+ if (this.disposed) return;
1683
+ this.enqueue(async () => {
1684
+ const behind = this.compiled.filter((obs) => obs.levels[level] === "bare");
1685
+ if (behind.length === 0) return;
1686
+ this.host.logWarn(`onObserverAdded was set for ${this.functionId} while ${behind.length} observer(s) were active without it; it runs for each of them now`);
1687
+ for (const obs of behind) {
1688
+ const hook = this.addedHook(level);
1689
+ if (!hook) return;
1690
+ if (!obs.active || obs.levels[level] !== "bare") continue;
1691
+ const outcome = await this.runHook(() => hook(obs));
1692
+ if (outcome.ok) {
1693
+ obs.levels[level] = "hooked";
1694
+ continue;
1695
+ }
1696
+ obs.levels[level] = "none";
1697
+ if (outcome.timedOut) this.undoLate(outcome.late, obs, level);
1698
+ this.reject(obs, outcome.code, outcome.message);
1699
+ }
1700
+ });
1701
+ }
1702
+ /**
1703
+ * The function's match hook was set or removed (decision 45). Matching by
1704
+ * keys rebuilds the index from the active observers; an observer whose keys
1705
+ * cannot be computed is late-rejected.
1706
+ */
1707
+ matchChanged() {
1708
+ const keys = matchKeysOf(this.host.hooks(this.functionId).match);
1709
+ if (keys === this.matchKeys) return;
1710
+ this.matchKeys = keys;
1711
+ this.index = keys ? /* @__PURE__ */ new Map() : void 0;
1712
+ for (const obs of this.known.values()) obs.keys = void 0;
1713
+ for (const obs of this.compiled) {
1714
+ const failure = this.prepareKeys(obs);
1715
+ if (failure) this.reject(obs, failure.code, failure.message);
1716
+ else this.file(obs);
1717
+ }
1718
+ }
1719
+ /** The keys of a call; a key function that throws gives none. */
1720
+ callKeys(keys, call) {
1721
+ try {
1722
+ return keyList(keys.call(call));
1723
+ } catch (error) {
1724
+ this.matchFailed(error);
1725
+ return [];
1726
+ }
1727
+ }
1728
+ matchFailed(error) {
1729
+ if (this.matchFailureLogged) return;
1730
+ this.matchFailureLogged = true;
1731
+ this.host.logError(`onObservationMatch of ${this.functionId} threw; the call matches no observer`, error);
1732
+ }
1733
+ /**
1412
1734
  * Stops delivery at once, then removes every observer through the hook
1413
1735
  * queue, after the adds queued before it (which undo themselves: `add`).
1414
1736
  */
1415
1737
  dropAll() {
1416
- for (const obs of this.compiled) obs.active = false;
1417
- this.compiled = [];
1738
+ for (const obs of this.compiled) this.deactivate(obs);
1418
1739
  this.enqueue(async () => {
1419
1740
  for (const id of [...this.known.keys()]) await this.remove(id);
1420
1741
  });
1421
1742
  }
1422
1743
  enqueue(task) {
1423
1744
  this.queue = this.queue.then(task).catch((error) => {
1424
- this.host.logError(`Observe hook failed for ${this.functionId}`, error);
1745
+ this.host.logError(`Observer hook failed for ${this.functionId}`, error);
1425
1746
  });
1426
1747
  }
1427
- activate(obs) {
1748
+ addedHook(level) {
1749
+ const hooks = this.host.hooks(this.functionId);
1750
+ return level === "worker" ? hooks.workerAdded : hooks.added;
1751
+ }
1752
+ removedHook(level) {
1753
+ const hooks = this.host.hooks(this.functionId);
1754
+ return level === "worker" ? hooks.workerRemoved : hooks.removed;
1755
+ }
1756
+ activate(obs) {
1428
1757
  if (obs.active) return;
1429
1758
  obs.active = true;
1759
+ obs.activatedSeq = ++this.activations;
1430
1760
  this.compiled = [...this.compiled, obs];
1761
+ this.filterIndex.insert(obs, obs.filter, obs.activatedSeq);
1762
+ this.file(obs);
1431
1763
  }
1432
1764
  deactivate(obs) {
1433
1765
  if (!obs.active) return;
1434
1766
  obs.active = false;
1435
1767
  this.compiled = this.compiled.filter((o) => o !== obs);
1768
+ this.filterIndex.remove(obs);
1769
+ this.unfile(obs);
1770
+ }
1771
+ /** Computes the keys `obs` is filed under, once, when the function is matched by keys. */
1772
+ prepareKeys(obs) {
1773
+ const keys = this.matchKeys;
1774
+ if (!keys || obs.keys) return void 0;
1775
+ try {
1776
+ obs.keys = [...new Set(keyList(keys.observer(obs)))];
1777
+ return;
1778
+ } catch (error) {
1779
+ return {
1780
+ code: "OBSERVE_REJECTED",
1781
+ message: `the keys of observer ${obs.id} of ${this.functionId} could not be computed: ${error instanceof Error ? error.message : String(error)}`
1782
+ };
1783
+ }
1784
+ }
1785
+ file(obs) {
1786
+ const index = this.index;
1787
+ if (!index || !obs.keys) return;
1788
+ for (const key of obs.keys) {
1789
+ const filed = index.get(key);
1790
+ if (filed) filed.add(obs);
1791
+ else index.set(key, new Set([obs]));
1792
+ }
1793
+ }
1794
+ unfile(obs) {
1795
+ const index = this.index;
1796
+ if (!index || !obs.keys) return;
1797
+ for (const key of obs.keys) {
1798
+ const filed = index.get(key);
1799
+ if (!filed) continue;
1800
+ filed.delete(obs);
1801
+ if (filed.size === 0) index.delete(key);
1802
+ }
1436
1803
  }
1437
1804
  ack(info, revision, namespace, error) {
1438
1805
  this.host.sendAck({
@@ -1443,55 +1810,82 @@ var FunctionObservers = class {
1443
1810
  ...error ? { error } : {}
1444
1811
  });
1445
1812
  }
1446
- /** Diffs the engine's full set against what this SDK holds. */
1813
+ /**
1814
+ * Diffs the engine's full set against what this SDK holds: the ones it no
1815
+ * longer lists are removed, the ones it holds are acked again
1816
+ * ({@link FunctionObservers.reack}), and the others are added.
1817
+ */
1447
1818
  async applySet(list, revision, namespace) {
1448
1819
  const incoming = new Set(list.map((o) => o.id));
1449
1820
  for (const id of [...this.known.keys()]) if (!incoming.has(id)) await this.remove(id);
1450
1821
  for (const info of list) {
1451
- const existing = this.known.get(info.id);
1452
- if (existing && sameJson(existing.args, info.args) && sameJson(existing.legacy, info.legacy)) this.keep(existing, info, revision, namespace);
1453
- else {
1454
- if (existing) await this.remove(info.id);
1455
- await this.add(info, revision, namespace);
1456
- }
1822
+ const held = this.known.get(info.id);
1823
+ if (held && this.reack(held, info, revision, namespace, true)) continue;
1824
+ if (held) await this.remove(info.id);
1825
+ await this.add(info, revision, namespace);
1457
1826
  }
1458
1827
  }
1459
1828
  /**
1460
- * A kept observer: the hook already ran for it; take the engine's filters
1461
- * and ack it again, or repeat the owner's late rejection of it.
1829
+ * Acks again, at `revision` and without running any hook, an observer this
1830
+ * SDK holds that the engine announced again (decision 44): one with the
1831
+ * same args, served from now on with the filters, target, capture and `on`
1832
+ * it was announced with (its keys computed again when they changed), or,
1833
+ * when `listed` by `functionregistered`, one rejected late, whose rejection
1834
+ * is sent again. `false` for an observer to add as a new one after removing
1835
+ * the one held: other args, a late rejection announced by `observeradded`,
1836
+ * or a view this SDK cannot serve (filters that do not compile, keys that
1837
+ * throw).
1462
1838
  */
1463
- keep(obs, info, revision, namespace) {
1464
- if (obs.rejection) {
1465
- obs.revision = revision;
1466
- this.ack(info, revision, namespace, obs.rejection);
1467
- return;
1839
+ reack(held, info, revision, namespace, listed) {
1840
+ if (held.rejection) {
1841
+ if (!listed) return false;
1842
+ held.revision = revision;
1843
+ this.ack(info, revision, namespace, held.rejection);
1844
+ return true;
1468
1845
  }
1469
- let filter = obs.filter;
1470
- if (!sameJson(obs.filters, info.filters)) try {
1471
- filter = compileFilter(info.filters, { trusted: true });
1472
- } catch (error) {
1473
- obs.revision = revision;
1474
- this.deactivate(obs);
1475
- this.ack(info, revision, namespace, {
1476
- code: "INVALID_FILTER",
1477
- message: error.message
1478
- });
1479
- return;
1846
+ if (!sameJson(held.args, info.args)) return false;
1847
+ if (!sameView(held, info)) {
1848
+ let filter = held.filter;
1849
+ if (!sameJson(held.filters, info.filters)) try {
1850
+ filter = compileFilter(info.filters, { trusted: true });
1851
+ } catch {
1852
+ return false;
1853
+ }
1854
+ const keys = this.viewKeys(held, info, filter);
1855
+ if (keys === null) return false;
1856
+ if (held.active) this.unfile(held);
1857
+ held.update(info, filter);
1858
+ if (keys !== void 0) held.keys = keys;
1859
+ if (held.active) {
1860
+ this.file(held);
1861
+ this.filterIndex.insert(held, held.filter, held.activatedSeq);
1862
+ }
1480
1863
  }
1481
- obs.update(info, filter);
1482
- obs.revision = revision;
1483
- this.activate(obs);
1864
+ held.revision = revision;
1484
1865
  this.ack(info, revision, namespace);
1866
+ return true;
1867
+ }
1868
+ /**
1869
+ * The keys `held` is filed under once it takes the view `info` (with
1870
+ * `filter`), on a function matched by keys: computed on a copy, so a key
1871
+ * function that throws (`null`) leaves `held` as it was. `undefined` when
1872
+ * the function is not matched by keys.
1873
+ */
1874
+ viewKeys(held, info, filter) {
1875
+ const keys = this.matchKeys;
1876
+ if (!keys) return void 0;
1877
+ const view = Object.assign(Object.create(Object.getPrototypeOf(held)), held);
1878
+ view.update(info, filter);
1879
+ try {
1880
+ return [...new Set(keyList(keys.observer(view)))];
1881
+ } catch {
1882
+ return null;
1883
+ }
1485
1884
  }
1486
- /** handleAdded (§4.2): hook, then the compiled set, then the ack. */
1885
+ /** handleAdded (§4.3): the hooks of both levels, then the active set, then the ack. */
1487
1886
  async add(info, revision, namespace) {
1488
1887
  if (this.disposed || this.releasedEpoch !== void 0) return;
1489
1888
  const releases = this.releases;
1490
- const existing = this.known.get(info.id);
1491
- if (existing) {
1492
- this.keep(existing, info, revision, namespace);
1493
- return;
1494
- }
1495
1889
  let filter;
1496
1890
  try {
1497
1891
  filter = compileFilter(info.filters, { trusted: true });
@@ -1503,43 +1897,91 @@ var FunctionObservers = class {
1503
1897
  return;
1504
1898
  }
1505
1899
  const obs = new ObserverImpl(this, info, filter, revision);
1506
- const onAdded = this.hooks?.onObserverAdded;
1507
- if (onAdded) {
1508
- obs.adding = true;
1509
- const outcome = await this.runHook(() => onAdded.call(this.hooks, obs));
1510
- obs.adding = false;
1511
- if (!outcome.ok) {
1512
- this.ack(info, revision, namespace, {
1513
- code: outcome.code,
1514
- message: outcome.message
1515
- });
1516
- if (outcome.timedOut) outcome.late.then(() => this.enqueue(() => this.callRemoved(obs)), () => void 0);
1517
- return;
1518
- }
1900
+ obs.adding = true;
1901
+ const failure = await this.setUp(obs);
1902
+ obs.adding = false;
1903
+ if (failure) {
1904
+ this.ack(info, revision, namespace, failure);
1905
+ obs.settleAcceptance(failure);
1906
+ return;
1519
1907
  }
1520
1908
  if (this.disposed || this.releases !== releases) {
1521
- await this.callRemoved(obs);
1909
+ await this.unwind(obs);
1910
+ obs.settleAcceptance({
1911
+ code: "OBSERVER_NOT_ACTIVE",
1912
+ message: `${this.functionId} was released before observer ${obs.id} was accepted`
1913
+ });
1522
1914
  return;
1523
1915
  }
1524
1916
  this.known.set(obs.id, obs);
1525
- if (obs.rejection) {
1526
- this.ack(info, revision, namespace, obs.rejection);
1917
+ const rejection = obs.rejection ?? this.prepareKeys(obs);
1918
+ if (rejection) {
1919
+ obs.rejection = rejection;
1920
+ this.ack(info, revision, namespace, rejection);
1921
+ obs.settleAcceptance(rejection);
1922
+ await this.unwind(obs);
1527
1923
  return;
1528
1924
  }
1529
1925
  this.activate(obs);
1530
1926
  this.ack(info, revision, namespace);
1927
+ obs.settleAcceptance("accepted");
1928
+ }
1929
+ /**
1930
+ * Runs `onObserverAdded` of the worker, then of the function. When one
1931
+ * fails, the levels whose `onObserverAdded` resolved are torn down, and the
1932
+ * rejection is returned.
1933
+ */
1934
+ async setUp(obs) {
1935
+ for (const level of ["worker", "fn"]) {
1936
+ const hook = this.addedHook(level);
1937
+ if (!hook) {
1938
+ obs.levels[level] = "bare";
1939
+ continue;
1940
+ }
1941
+ const outcome = await this.runHook(() => hook(obs));
1942
+ if (!outcome.ok) {
1943
+ if (outcome.timedOut) this.undoLate(outcome.late, obs, level);
1944
+ await this.unwind(obs);
1945
+ return {
1946
+ code: outcome.code,
1947
+ message: outcome.message
1948
+ };
1949
+ }
1950
+ obs.levels[level] = "hooked";
1951
+ }
1952
+ }
1953
+ /**
1954
+ * Undoes the setup of an observer that is not accepted: `onObserverRemoved`
1955
+ * runs only at the levels whose `onObserverAdded` resolved (§4.3), never at
1956
+ * a level set up without one.
1957
+ */
1958
+ async unwind(obs) {
1959
+ for (const level of ["worker", "fn"]) if (obs.levels[level] === "bare") obs.levels[level] = "none";
1960
+ await this.tearDown(obs);
1961
+ }
1962
+ /** Runs `onObserverRemoved` of the function, then of the worker, for each level set up, once. */
1963
+ async tearDown(obs) {
1964
+ for (const level of ["fn", "worker"]) {
1965
+ if (obs.levels[level] === "none") continue;
1966
+ obs.levels[level] = "none";
1967
+ await this.runRemoved(obs, level);
1968
+ }
1969
+ }
1970
+ /** A timed-out `onObserverAdded` that resolves later is undone by its level's `onObserverRemoved`. */
1971
+ undoLate(late, obs, level) {
1972
+ late.then(() => this.enqueue(() => this.runRemoved(obs, level)), () => void 0);
1531
1973
  }
1532
1974
  async remove(id) {
1533
1975
  const obs = this.known.get(id);
1534
1976
  if (!obs) return;
1535
1977
  this.known.delete(id);
1536
1978
  this.deactivate(obs);
1537
- await this.callRemoved(obs);
1979
+ await this.tearDown(obs);
1538
1980
  }
1539
- async callRemoved(obs) {
1540
- const onRemoved = this.hooks?.onObserverRemoved;
1541
- if (!onRemoved) return;
1542
- const outcome = await this.runHook(() => onRemoved.call(this.hooks, obs));
1981
+ async runRemoved(obs, level) {
1982
+ const hook = this.removedHook(level);
1983
+ if (!hook) return;
1984
+ const outcome = await this.runHook(() => hook(obs));
1543
1985
  if (!outcome.ok) this.host.logError(`onObserverRemoved failed for observer ${obs.id} of ${this.functionId}: ${outcome.message}`);
1544
1986
  }
1545
1987
  async runHook(fn) {
@@ -1554,7 +1996,7 @@ var FunctionObservers = class {
1554
1996
  if (await Promise.race([run.then(() => "done"), timeout]) === "timeout") return {
1555
1997
  ok: false,
1556
1998
  code: "OWNER_TIMEOUT",
1557
- message: `observe hook of ${this.functionId} still running after ${timeoutMs}ms`,
1999
+ message: `observer hook of ${this.functionId} still running after ${timeoutMs}ms`,
1558
2000
  timedOut: true,
1559
2001
  late: run
1560
2002
  };
@@ -1570,103 +2012,7 @@ var FunctionObservers = class {
1570
2012
  if (timer) clearTimeout(timer);
1571
2013
  }
1572
2014
  }
1573
- requireOwnerDelivery(what) {
1574
- if (this.delivery !== "owner") throw new InvocationError({
1575
- code: "NOT_OWNER_DELIVERED",
1576
- message: `obs.${what}() needs an owner-delivered function; ${this.functionId} is auto-delivered (observe.delivery)`,
1577
- function_id: this.functionId
1578
- });
1579
- }
1580
- isActive(obs) {
1581
- return obs.active && this.known.get(obs.id) === obs;
1582
- }
1583
- /**
1584
- * The caller an event carries (sdk.md §1): inside the function's own
1585
- * handler, that invocation's caller; inside another handler, that handler;
1586
- * outside any handler, this worker only.
1587
- */
1588
- eventCaller(cur) {
1589
- if (cur && cur.function_id === this.functionId) return {
1590
- caller: cur.caller,
1591
- own: true
1592
- };
1593
- const { worker_id, worker_name } = this.host.identity();
1594
- const caller = worker_id !== void 0 ? {
1595
- worker_id,
1596
- worker_name
1597
- } : { worker_name };
1598
- if (cur) {
1599
- caller.function_id = cur.function_id;
1600
- caller.invocation_id = cur.invocation_id;
1601
- const parent = stripCaller(cur.caller);
1602
- if (parent && Object.keys(parent).length > 0) caller.parent = parent;
1603
- }
1604
- return {
1605
- caller,
1606
- own: false
1607
- };
1608
- }
1609
- /**
1610
- * Hands `event` to one observer. `false`, and nothing sent, when its
1611
- * filters reject the event or it is no longer active (removed or rejected
1612
- * meanwhile): an owner's fan-out loop must not stop for one observer.
1613
- */
1614
- emit(obs, event) {
1615
- this.requireOwnerDelivery("emit");
1616
- if (!this.isActive(obs)) return false;
1617
- const cur = callContext();
1618
- const { caller, own } = this.eventCaller(cur);
1619
- const metadata = cur?.metadata;
1620
- if (!obs.filter.matches({
1621
- input: event,
1622
- caller,
1623
- metadata
1624
- })) return false;
1625
- const values = { input: event };
1626
- if (caller !== void 0) values.caller = caller;
1627
- if (metadata !== void 0) values.metadata = metadata;
1628
- const trace = cur ? {
1629
- traceparent: cur.traceparent,
1630
- baggage: cur.baggage
1631
- } : this.host.traceContext();
1632
- this.host.reporter.pushEmit({
1633
- function_id: this.functionId,
1634
- namespace: this.namespace,
1635
- invocation_id: own && cur ? cur.invocation_id : require_utils.randomUUID(),
1636
- status: "success",
1637
- values,
1638
- captures: obs.capture,
1639
- started_at_ms: Date.now(),
1640
- duration_ms: 0,
1641
- observe_depth: cur ? cur.observe_depth : callDepth(),
1642
- traceparent: trace.traceparent,
1643
- baggage: trace.baggage,
1644
- observer_id: obs.id,
1645
- event,
1646
- context: cur
1647
- });
1648
- return true;
1649
- }
1650
- async call(obs, payload, timeoutMs) {
1651
- this.requireOwnerDelivery("call");
1652
- if (!this.isActive(obs)) throw new InvocationError({
1653
- code: "OBSERVER_NOT_ACTIVE",
1654
- message: `observer ${obs.id} of ${this.functionId} is not active`,
1655
- function_id: this.functionId
1656
- });
1657
- const cur = callContext();
1658
- const { caller } = this.eventCaller(cur);
1659
- if (!obs.filter.matches({
1660
- input: payload,
1661
- caller,
1662
- metadata: cur?.metadata
1663
- })) throw new InvocationError({
1664
- code: "FILTERS_NOT_MATCHED",
1665
- message: `the filters of observer ${obs.id} reject this payload`,
1666
- function_id: this.functionId
1667
- });
1668
- return this.host.callTarget(obs.target, obs.id, payload, timeoutMs);
1669
- }
2015
+ /** @internal Late rejection (`obs.reject`, a failed catch-up): inactive at once, then torn down. */
1670
2016
  reject(obs, code, message) {
1671
2017
  if (obs.adding) {
1672
2018
  obs.rejection = {
@@ -1675,7 +2021,7 @@ var FunctionObservers = class {
1675
2021
  };
1676
2022
  return;
1677
2023
  }
1678
- if (this.known.get(obs.id) !== obs) return;
2024
+ if (this.known.get(obs.id) !== obs || obs.rejection) return;
1679
2025
  obs.rejection = {
1680
2026
  code,
1681
2027
  message
@@ -1691,52 +2037,343 @@ var FunctionObservers = class {
1691
2037
  message
1692
2038
  }
1693
2039
  });
2040
+ this.enqueue(() => this.tearDown(obs));
2041
+ }
2042
+ };
2043
+ /**
2044
+ * The delivery of one call (v2 §4.4–§4.6, decisions 20, 36, 38, 45, 55): the
2045
+ * observers are matched (`onObservationMatch`), then the function's
2046
+ * `onObservationDeliver` delivers the call itself, or iii delivers it to the
2047
+ * matched observers whose `on` and filters accept it. For a local call the
2048
+ * host evaluates `on` and filters and reports the observers delivered in
2049
+ * one report item. For a routed call the engine evaluates them: the answer
2050
+ * carries the observers the match hook matched (`matched`), or says that
2051
+ * the deliver hook delivered the call (`delivered`), or neither for a
2052
+ * function with no match hook and no deliver hook.
2053
+ */
2054
+ var Delivery = class {
2055
+ constructor(owner, init) {
2056
+ this.owner = owner;
2057
+ this.init = init;
2058
+ this.delivered = false;
2059
+ }
2060
+ /** Resolves to what the caller gets back, or rejects with what it gets thrown. */
2061
+ async run(deliver) {
2062
+ const { call, snapshot, activations, thrown, routed } = this.init;
2063
+ const matched = this.owner.matching(call, snapshot, activations);
2064
+ if (deliver !== void 0) {
2065
+ if (routed) this.delivered = true;
2066
+ return deliver(call, matched);
2067
+ }
2068
+ if (routed) {
2069
+ if (this.owner.hasMatchHook()) this.matched = matched.map((obs) => obs.id);
2070
+ } else {
2071
+ const selected = this.select(call, matched);
2072
+ if (selected.length > 0) this.owner.reporter.push(this.item(call, selected));
2073
+ }
2074
+ if (call.status === "error") throw thrown;
2075
+ return call.output;
1694
2076
  }
1695
2077
  /**
1696
- * Evaluates `set` (the compiled set captured when the call started) on a
1697
- * finished local invocation of an auto function, and reports it when an
1698
- * observer matches. Never throws.
2078
+ * The error body a call answers with for `error`: the handler's own, or
2079
+ * what the deliver hook threw ({@link deliverErrorBody}).
1699
2080
  */
1700
- reportLocal(set, init) {
1701
- if (this.delivery !== "auto" || set.length === 0) return;
1702
- const doc = {
1703
- input: init.input,
1704
- caller: init.caller,
1705
- metadata: init.metadata
1706
- };
1707
- if (init.ok) doc.output = init.output;
1708
- else doc.error = init.error;
1709
- const matched = [];
2081
+ errorBody(error) {
2082
+ const { call, thrown } = this.init;
2083
+ return error === thrown && call.error ? call.error : deliverErrorBody(error);
2084
+ }
2085
+ /**
2086
+ * The matched observers whose `on` and filters accept `call`, in the order
2087
+ * of `matched`. Without a match hook `matched` is the call's snapshot; while
2088
+ * it is also the active set (no observer joined or left since the call
2089
+ * started), {@link FunctionObservers.selectActive} selects them, through
2090
+ * the index of the filters' equality conditions when it narrows them.
2091
+ * Otherwise each matched observer's filters are evaluated.
2092
+ */
2093
+ select(call, matched) {
2094
+ const ok = call.status !== "error";
2095
+ const doc = filterDoc(call);
2096
+ if (matched === this.init.snapshot && matched === this.owner.compiled) return this.owner.selectActive(doc, ok);
2097
+ return matched.filter((obs) => onAccepts(obs.on, ok) && obs.filter.matches(doc));
2098
+ }
2099
+ /** The report item of a local call delivered to `selected`. */
2100
+ item(call, selected) {
2101
+ const init = this.init;
1710
2102
  const captures = /* @__PURE__ */ new Set();
1711
- for (const obs of set) {
1712
- if (!onAccepts(obs.on, init.ok)) continue;
1713
- if (!obs.filter.matches(doc)) continue;
1714
- matched.push(obs.id);
1715
- for (const c of obs.capture) captures.add(c);
1716
- }
1717
- if (matched.length === 0) return;
1718
- const values = { input: init.input };
1719
- if (init.ok) values.output = init.output;
1720
- else values.error = init.error;
1721
- if (init.caller !== void 0) values.caller = init.caller;
1722
- if (init.metadata !== void 0) values.metadata = init.metadata;
1723
- this.host.reporter.push({
1724
- function_id: this.functionId,
1725
- namespace: this.namespace,
1726
- invocation_id: init.invocation_id,
1727
- matched,
1728
- status: init.ok ? "success" : "error",
2103
+ for (const obs of selected) for (const c of obs.capture) captures.add(c);
2104
+ const ok = call.status !== "error";
2105
+ const values = { input: call.input };
2106
+ if (ok) values.output = call.output;
2107
+ else values.error = call.error;
2108
+ const caller = reportCaller(call.caller);
2109
+ if (caller !== void 0) values.caller = caller;
2110
+ if (call.metadata !== void 0) values.metadata = call.metadata;
2111
+ return {
2112
+ function_id: this.owner.functionId,
2113
+ namespace: this.owner.namespace,
2114
+ invocation_id: call.invocation_id,
2115
+ matched: selected.map((obs) => obs.id),
2116
+ status: ok ? "success" : "error",
1729
2117
  values,
1730
2118
  captures,
2119
+ output_is_input: ok && call.output === call.input && this.owner.observeV2(),
1731
2120
  started_at_ms: init.started_at_ms,
1732
2121
  duration_ms: init.duration_ms,
1733
2122
  observe_depth: init.observe_depth,
1734
2123
  traceparent: init.traceparent,
1735
2124
  baggage: init.baggage
1736
- });
2125
+ };
1737
2126
  }
1738
2127
  };
1739
2128
 
2129
+ //#endregion
2130
+ //#region src/observe-wire.ts
2131
+ /** CONTRACT D1: what an absent `capture` means. */
2132
+ const DEFAULT_CAPTURE = [
2133
+ "input",
2134
+ "output",
2135
+ "caller"
2136
+ ];
2137
+ function isRecord(v) {
2138
+ return v !== null && typeof v === "object" && !Array.isArray(v);
2139
+ }
2140
+ function str(v) {
2141
+ return typeof v === "string" ? v : void 0;
2142
+ }
2143
+ function num(v) {
2144
+ return typeof v === "number" ? v : void 0;
2145
+ }
2146
+ function errorBody(v) {
2147
+ if (!isRecord(v)) return void 0;
2148
+ const body = {
2149
+ code: String(v.code ?? ""),
2150
+ message: String(v.message ?? "")
2151
+ };
2152
+ if (typeof v.stacktrace === "string") body.stacktrace = v.stacktrace;
2153
+ return body;
2154
+ }
2155
+ /** Copies the wire caller, dropping `null`s and a `parent` inside `parent`. */
2156
+ function decodeCaller(v, depth = 0) {
2157
+ if (!isRecord(v)) return void 0;
2158
+ const caller = {};
2159
+ for (const key of [
2160
+ "worker_id",
2161
+ "worker_name",
2162
+ "function_id",
2163
+ "invocation_id"
2164
+ ]) {
2165
+ const value = str(v[key]);
2166
+ if (value !== void 0) caller[key] = value;
2167
+ }
2168
+ if (depth === 0) {
2169
+ const parent = decodeCaller(v.parent, 1);
2170
+ if (parent) caller.parent = parent;
2171
+ }
2172
+ return caller;
2173
+ }
2174
+ function decodeActivation(v) {
2175
+ if (!isRecord(v) || typeof v.observer_id !== "string") return void 0;
2176
+ const activation = { observer_id: v.observer_id };
2177
+ if (typeof v.activation_id === "string") activation.activation_id = v.activation_id;
2178
+ return activation;
2179
+ }
2180
+ /** An observer as its host sees it (`observeradded.observer`, `functionregistered.observers[]`). */
2181
+ function decodeObserverInfo(v) {
2182
+ const raw = isRecord(v) ? v : {};
2183
+ return {
2184
+ id: String(raw.id ?? ""),
2185
+ args: isRecord(raw.args) ? raw.args : {},
2186
+ filters: raw.filters === void 0 ? {} : raw.filters,
2187
+ target: String(raw.target ?? ""),
2188
+ capture: Array.isArray(raw.capture) ? raw.capture.filter((c) => typeof c === "string") : [...DEFAULT_CAPTURE],
2189
+ on: str(raw.on) ?? "success"
2190
+ };
2191
+ }
2192
+ function decodeFunctionRegistered(v) {
2193
+ return {
2194
+ id: String(v.id ?? ""),
2195
+ namespace: String(v.namespace ?? ""),
2196
+ revision: num(v.revision) ?? 0,
2197
+ local_dispatch: v.local_dispatch === true,
2198
+ observers: Array.isArray(v.observers) ? v.observers.map(decodeObserverInfo) : []
2199
+ };
2200
+ }
2201
+ function decodeObserverAdded(v) {
2202
+ return {
2203
+ function_id: String(v.function_id ?? ""),
2204
+ namespace: String(v.namespace ?? ""),
2205
+ revision: num(v.revision) ?? 0,
2206
+ observer: decodeObserverInfo(v.observer)
2207
+ };
2208
+ }
2209
+ function decodeObserverRemoved(v) {
2210
+ return {
2211
+ function_id: String(v.function_id ?? ""),
2212
+ namespace: String(v.namespace ?? ""),
2213
+ revision: num(v.revision) ?? 0,
2214
+ id: String(v.id ?? "")
2215
+ };
2216
+ }
2217
+ function decodeObserveResult(v) {
2218
+ const msg = {
2219
+ id: String(v.id ?? ""),
2220
+ state: String(v.state ?? "")
2221
+ };
2222
+ const error = errorBody(v.error);
2223
+ if (error) msg.error = error;
2224
+ if (Array.isArray(v.warnings)) msg.warnings = v.warnings.filter((w) => typeof w === "string");
2225
+ return msg;
2226
+ }
2227
+ function decodeObserverStateChanged(v) {
2228
+ const msg = {
2229
+ id: String(v.id ?? ""),
2230
+ state: String(v.state ?? ""),
2231
+ fires: num(v.fires) ?? 0
2232
+ };
2233
+ const reason = errorBody(v.reason);
2234
+ if (reason) msg.reason = reason;
2235
+ return msg;
2236
+ }
2237
+ function decodeWorkerRegistered(v) {
2238
+ const msg = { worker_id: String(v.worker_id ?? "") };
2239
+ if (typeof v.reattach_token === "string") msg.reattach_token = v.reattach_token;
2240
+ if (Array.isArray(v.features)) msg.features = v.features.filter((f) => typeof f === "string");
2241
+ return msg;
2242
+ }
2243
+ /** The observe fields of an inbound `invokefunction` (`caller`, `observe_depth`, `activation`). */
2244
+ function decodeInvokeFunction(v) {
2245
+ const msg = {
2246
+ function_id: String(v.function_id ?? ""),
2247
+ data: v.data
2248
+ };
2249
+ if (typeof v.invocation_id === "string") msg.invocation_id = v.invocation_id;
2250
+ if (typeof v.traceparent === "string") msg.traceparent = v.traceparent;
2251
+ if (typeof v.baggage === "string") msg.baggage = v.baggage;
2252
+ if (isRecord(v.action)) msg.action = v.action;
2253
+ if (v.metadata !== void 0 && v.metadata !== null) msg.metadata = v.metadata;
2254
+ if (typeof v.namespace === "string") msg.namespace = v.namespace;
2255
+ const caller = decodeCaller(v.caller);
2256
+ if (caller) msg.caller = caller;
2257
+ const depth = num(v.observe_depth);
2258
+ if (depth !== void 0 && depth > 0) msg.observe_depth = depth;
2259
+ const activation = decodeActivation(v.activation);
2260
+ if (activation) msg.activation = activation;
2261
+ return msg;
2262
+ }
2263
+ function decodeRegistrationRejected(v) {
2264
+ const msg = {
2265
+ code: String(v.code ?? ""),
2266
+ namespace: String(v.namespace ?? ""),
2267
+ owner_worker_id: String(v.owner_worker_id ?? "")
2268
+ };
2269
+ if (typeof v.worker_name === "string") msg.worker_name = v.worker_name;
2270
+ if (typeof v.function_id === "string") msg.function_id = v.function_id;
2271
+ return msg;
2272
+ }
2273
+ /** Drops `parent` (one level only). */
2274
+ function stripCaller(caller) {
2275
+ if (!caller) return void 0;
2276
+ const { parent: _, ...rest } = caller;
2277
+ return rest;
2278
+ }
2279
+ /** JSON's view of a message: `undefined` fields left out, no caller-owned objects retained. */
2280
+ function snapshot(value) {
2281
+ return JSON.parse(JSON.stringify(value));
2282
+ }
2283
+ /**
2284
+ * `observe { id, source, target, ... }` from the three arguments of
2285
+ * `iii.observe`. Only what the caller set is sent; the engine applies the
2286
+ * defaults. `resolveNamespace` gives the namespace of an unqualified id (this
2287
+ * worker's, `default` for `engine::*`).
2288
+ */
2289
+ function buildObserveMessage(id, source, target, options, resolveNamespace) {
2290
+ const targetRef = typeof target === "string" ? { function_id: target } : target;
2291
+ const sourceNamespace = resolveNamespace(source.namespace, source.function_id, "ObserveSource.namespace");
2292
+ const targetNamespace = resolveNamespace(targetRef.namespace, targetRef.function_id, "Target.namespace");
2293
+ return snapshot({
2294
+ id,
2295
+ source: {
2296
+ function_id: source.function_id,
2297
+ namespace: sourceNamespace,
2298
+ args: source.args,
2299
+ filters: source.filters,
2300
+ capture: source.capture,
2301
+ on: source.on,
2302
+ deliver: source.deliver
2303
+ },
2304
+ target: {
2305
+ function_id: targetRef.function_id,
2306
+ namespace: targetNamespace
2307
+ },
2308
+ metadata: options?.metadata,
2309
+ max_fires: options?.max_fires,
2310
+ expires_in_ms: options?.expires_in_ms,
2311
+ max_in_flight: options?.max_in_flight
2312
+ });
2313
+ }
2314
+ function buildObserverAck(ack) {
2315
+ const msg = {
2316
+ function_id: ack.function_id,
2317
+ id: ack.id,
2318
+ revision: ack.revision
2319
+ };
2320
+ if (ack.namespace !== void 0) msg.namespace = ack.namespace;
2321
+ if (ack.error) msg.error = {
2322
+ code: ack.error.code,
2323
+ message: ack.error.message
2324
+ };
2325
+ return msg;
2326
+ }
2327
+ /**
2328
+ * An outbound `invokefunction`. `observe_depth` is left out when 0, and every
2329
+ * optional field when unset.
2330
+ */
2331
+ function buildInvokeFunction(init) {
2332
+ const msg = {};
2333
+ if (init.invocation_id !== void 0) msg.invocation_id = init.invocation_id;
2334
+ msg.function_id = init.function_id;
2335
+ msg.data = init.data;
2336
+ if (init.traceparent !== void 0) msg.traceparent = init.traceparent;
2337
+ if (init.baggage !== void 0) msg.baggage = init.baggage;
2338
+ if (init.action !== void 0) msg.action = init.action;
2339
+ if (init.metadata !== void 0) msg.metadata = init.metadata;
2340
+ if (init.namespace !== void 0) msg.namespace = init.namespace;
2341
+ if (init.caller !== void 0) msg.caller = init.caller;
2342
+ if (init.observe_depth !== void 0 && init.observe_depth > 0) msg.observe_depth = init.observe_depth;
2343
+ if (init.activation !== void 0) msg.activation = init.activation;
2344
+ return msg;
2345
+ }
2346
+ /**
2347
+ * An outbound `invocationresult`: `result` is left out when the function
2348
+ * returned nothing (`undefined`). A routed call's answer says how the call
2349
+ * is delivered (decision 55): `delivered: true` (its deliver hook delivered
2350
+ * it), or `matched` (the observers its match hook matched, `[]` when none),
2351
+ * or neither; `delivered` outweighs `matched`, and only one is sent.
2352
+ */
2353
+ function buildInvocationResult(init) {
2354
+ const msg = {
2355
+ invocation_id: init.invocation_id,
2356
+ function_id: init.function_id
2357
+ };
2358
+ if (init.result !== void 0) msg.result = init.result;
2359
+ if (init.error !== void 0) msg.error = init.error;
2360
+ if (init.traceparent !== void 0) msg.traceparent = init.traceparent;
2361
+ if (init.baggage !== void 0) msg.baggage = init.baggage;
2362
+ if (init.delivered === true) msg.delivered = true;
2363
+ else if (init.matched !== void 0) msg.matched = [...init.matched];
2364
+ return msg;
2365
+ }
2366
+ /** The caller an outbound call asserts from inside a handler: that handler, and its own caller one level up. */
2367
+ function callerFor(ctx) {
2368
+ const caller = {
2369
+ function_id: ctx.function_id,
2370
+ invocation_id: ctx.invocation_id
2371
+ };
2372
+ const parent = stripCaller(ctx.caller);
2373
+ if (parent && Object.keys(parent).length > 0) caller.parent = parent;
2374
+ return caller;
2375
+ }
2376
+
1740
2377
  //#endregion
1741
2378
  //#region src/observer-handle.ts
1742
2379
  /**
@@ -1765,6 +2402,8 @@ var ObserverHandleImpl = class {
1765
2402
  this.undelivered = [];
1766
2403
  this.delivering = false;
1767
2404
  this.sent = false;
2405
+ this.answered = false;
2406
+ this.refused = false;
1768
2407
  }
1769
2408
  get state() {
1770
2409
  return this.currentState;
@@ -1852,47 +2491,27 @@ const DEFAULT_REPORTER_LIMITS = {
1852
2491
  statsIntervalMs: 1e4
1853
2492
  };
1854
2493
  var ReportItem = class {
1855
- constructor(init, emit, coalesceKey, context) {
2494
+ constructor(init) {
1856
2495
  this.init = init;
1857
- this.emit = emit;
1858
- this.coalesceKey = coalesceKey;
1859
- this.context = context;
1860
2496
  this.parts = /* @__PURE__ */ new Map();
1861
- this.captured = /* @__PURE__ */ new Set();
2497
+ this.outputIsInput = false;
1862
2498
  this.json = "";
1863
2499
  this.bytes = 0;
1864
2500
  }
1865
- /** Adds the parts `captures` asks for that are not in the item yet. */
2501
+ /** Encodes the parts `captures` asks for. */
1866
2502
  capture(captures) {
1867
- for (const c of captures) {
1868
- if (this.captured.has(c)) continue;
1869
- this.captured.add(c);
1870
- if (!PART_ORDER.includes(c)) continue;
1871
- const part = c;
1872
- if (!(part in this.init.values)) continue;
1873
- const encoded = encodeJson(this.init.values[part]);
2503
+ const wanted = new Set(captures);
2504
+ const values = this.init.values;
2505
+ for (const part of PART_ORDER) {
2506
+ if (!wanted.has(part) || !(part in values)) continue;
2507
+ if (part === "output" && this.init.output_is_input && this.parts.has("input")) {
2508
+ this.outputIsInput = true;
2509
+ continue;
2510
+ }
2511
+ const encoded = encodeJson(values[part]);
1874
2512
  if (encoded !== void 0) this.parts.set(part, encoded);
1875
2513
  }
1876
2514
  }
1877
- /** What a merge can change, to undo it. */
1878
- save() {
1879
- return {
1880
- matched: this.init.matched.length,
1881
- captured: [...this.captured],
1882
- parts: [...this.parts],
1883
- json: this.json,
1884
- bytes: this.bytes
1885
- };
1886
- }
1887
- restore(state) {
1888
- this.init.matched.length = state.matched;
1889
- this.captured.clear();
1890
- for (const c of state.captured) this.captured.add(c);
1891
- this.parts.clear();
1892
- for (const [part, encoded] of state.parts) this.parts.set(part, encoded);
1893
- this.json = state.json;
1894
- this.bytes = state.bytes;
1895
- }
1896
2515
  /** Assembles the wire JSON from the pre-encoded parts. */
1897
2516
  render() {
1898
2517
  const i = this.init;
@@ -1903,6 +2522,7 @@ var ReportItem = class {
1903
2522
  for (const part of PART_ORDER) {
1904
2523
  const encoded = this.parts.get(part);
1905
2524
  if (encoded !== void 0) s += `,"${part}":${encoded}`;
2525
+ if (part === "input" && this.outputIsInput) s += ",\"output_is_input\":true";
1906
2526
  }
1907
2527
  s += `,"started_at_ms":${finite(i.started_at_ms)},"duration_ms":${finite(i.duration_ms)}`;
1908
2528
  s += `,"observe_depth":${finite(i.observe_depth)}`;
@@ -1947,7 +2567,6 @@ var Reporter = class {
1947
2567
  this.items = [];
1948
2568
  this.bytes = 0;
1949
2569
  this.perFunction = /* @__PURE__ */ new Map();
1950
- this.openEmits = /* @__PURE__ */ new Map();
1951
2570
  this.stats = /* @__PURE__ */ new Map();
1952
2571
  this.drops = /* @__PURE__ */ new Map();
1953
2572
  this.windowStart = Date.now();
@@ -1974,59 +2593,13 @@ var Reporter = class {
1974
2593
  get size() {
1975
2594
  return this.items.length;
1976
2595
  }
1977
- /** A matched local invocation of an auto function. */
2596
+ /** A local call that observers matched. */
1978
2597
  push(init) {
1979
2598
  const { captures, ...rest } = init;
1980
- const item = new ReportItem(rest, false, void 0, void 0);
1981
- if (!this.build(item, captures)) return false;
1982
- return this.enqueue(item);
1983
- }
1984
- /**
1985
- * An `obs.emit` event. The same event value emitted to several observers
1986
- * from the same invocation context, before the buffer is flushed, becomes
1987
- * one item whose `matched` lists them all.
1988
- */
1989
- pushEmit(init) {
1990
- const { observer_id, event, context, captures, ...rest } = init;
1991
- const merge = this.openEmits.get(event)?.find((it) => it.init.function_id === rest.function_id && it.context === context && !it.init.matched.includes(observer_id));
1992
- if (merge) return this.merge(merge, observer_id, captures);
1993
- const item = new ReportItem({
1994
- ...rest,
1995
- matched: [observer_id]
1996
- }, true, event, context);
2599
+ const item = new ReportItem(rest);
1997
2600
  if (!this.build(item, captures)) return false;
1998
2601
  return this.enqueue(item);
1999
2602
  }
2000
- /** Makes a buffered emit item a merge target. Only items in the buffer are: a flush re-indexes. */
2001
- index(item) {
2002
- if (!item.emit) return;
2003
- const list = this.openEmits.get(item.coalesceKey);
2004
- if (list) list.push(item);
2005
- else this.openEmits.set(item.coalesceKey, [item]);
2006
- }
2007
- /** Adds an observer (and its captures) to a buffered emit item, within the same bounds as a new item. */
2008
- merge(item, observerId, captures) {
2009
- const fn = item.init.function_id;
2010
- const before = item.save();
2011
- try {
2012
- item.init.matched.push(observerId);
2013
- item.capture(captures);
2014
- item.render();
2015
- } catch (error) {
2016
- item.restore(before);
2017
- this.logUnencodable(fn, error);
2018
- return false;
2019
- }
2020
- const growth = item.bytes - before.bytes;
2021
- const reason = this.tooLarge(item) ? "TOO_LARGE" : growth > 0 && this.bytes + this.host.pendingBytes() + growth > this.limits.maxBytes ? "BUFFER_FULL" : void 0;
2022
- if (reason) {
2023
- item.restore(before);
2024
- this.drop(fn, reason);
2025
- return false;
2026
- }
2027
- this.bytes += growth;
2028
- return true;
2029
- }
2030
2603
  build(item, captures) {
2031
2604
  try {
2032
2605
  item.capture(captures);
@@ -2062,7 +2635,6 @@ var Reporter = class {
2062
2635
  this.items.push(item);
2063
2636
  this.bytes += item.bytes;
2064
2637
  this.perFunction.set(fn, (this.perFunction.get(fn) ?? 0) + 1);
2065
- this.index(item);
2066
2638
  if (this.items.length >= this.limits.batchItems) this.flush();
2067
2639
  else this.arm(this.limits.lingerMs);
2068
2640
  return true;
@@ -2164,17 +2736,15 @@ var Reporter = class {
2164
2736
  if (this.host.online()) this.arm(this.limits.lingerMs * 20);
2165
2737
  }
2166
2738
  }
2167
- /** Replaces the buffer, keeping the per-function counts and the emit coalescing index in step. */
2739
+ /** Replaces the buffer, keeping the per-function counts in step. */
2168
2740
  setItems(items) {
2169
2741
  this.items = items;
2170
2742
  this.bytes = 0;
2171
2743
  this.perFunction.clear();
2172
- this.openEmits.clear();
2173
2744
  for (const item of items) {
2174
2745
  this.bytes += item.bytes;
2175
2746
  const fn = item.init.function_id;
2176
2747
  this.perFunction.set(fn, (this.perFunction.get(fn) ?? 0) + 1);
2177
- this.index(item);
2178
2748
  }
2179
2749
  }
2180
2750
  /** Puts items back at the front of the buffer, within its bounds. */
@@ -2251,6 +2821,26 @@ function createPayloadTooLargeError(size, functionId) {
2251
2821
  function isPayloadTooLargeError(error) {
2252
2822
  return error instanceof Error && "code" in error && error.code === "payload_too_large";
2253
2823
  }
2824
+ /**
2825
+ * `registrationrejected` code (engine `protocol.rs`): another live worker
2826
+ * already holds this `(namespace, worker_name)`. The engine closes the
2827
+ * connection -- fatal.
2828
+ */
2829
+ const WORKER_NAMESPACE_CONFLICT = "WORKER_NAMESPACE_CONFLICT";
2830
+ /**
2831
+ * `registrationrejected` code (engine `protocol.rs`): another live worker in
2832
+ * this namespace already exports this one function id. The connection stays
2833
+ * open -- non-fatal.
2834
+ */
2835
+ const FUNCTION_NAMESPACE_CONFLICT = "FUNCTION_NAMESPACE_CONFLICT";
2836
+ /**
2837
+ * `registrationrejected` codes that refuse one function only (decisions 1,
2838
+ * 11): its `args_format` is not a valid JSON Schema, or the engine does not
2839
+ * support what it declares. The connection stays open -- non-fatal.
2840
+ */
2841
+ const FUNCTION_REJECTIONS = new Set(["INVALID_ARGS_FORMAT", "UNSUPPORTED"]);
2842
+ /** Why `call` refuses a call through an observer that names metadata (v2 §4.6, decision 53); the same in every SDK. */
2843
+ const OBSERVER_CALL_METADATA = "a call through an observer takes no metadata; its target receives the observer's metadata";
2254
2844
  /** Short random suffix; `crypto.randomUUID` is unavailable on insecure origins. */
2255
2845
  function randomId() {
2256
2846
  const c = globalThis.crypto;
@@ -2259,20 +2849,6 @@ function randomId() {
2259
2849
  return Math.random().toString(16).slice(2, 10);
2260
2850
  }
2261
2851
  /**
2262
- * The worker's namespace, refusing one that was named and left blank.
2263
- *
2264
- * Absent and blank mean opposite things. Absent asks for the engine's
2265
- * `default`; blank names a namespace and gives nothing to name it with. Read as
2266
- * absent, the worker registers in `default`, and since a worker's calls and
2267
- * triggers follow its namespace, the whole project quietly serves from a place
2268
- * its declaration never named -- the one thing an operator cannot see by
2269
- * reading the declaration.
2270
- *
2271
- * The browser has no `III_NAMESPACE` to fall back to, so unlike the other SDKs
2272
- * there is only the option here, and an option that was written and left empty
2273
- * is never what someone meant.
2274
- */
2275
- /**
2276
2852
  * The namespace one call or one binding resolves in.
2277
2853
  *
2278
2854
  * `undefined` inherits the worker's. A blank one is refused: named and left
@@ -2285,17 +2861,20 @@ function callNamespace(explicit, worker, source) {
2285
2861
  return explicit ?? worker;
2286
2862
  }
2287
2863
  /** Resolve one function invocation without leaking engine and configuration builtins into a worker namespace. */
2288
- function invocationNamespace(explicit, worker, functionId, source = "TriggerRequest.namespace") {
2864
+ function invocationNamespace(explicit, worker, functionId, source = "CallRequest.namespace") {
2289
2865
  const namespace = callNamespace(explicit, worker, source);
2290
2866
  return explicit === void 0 && (functionId.startsWith("engine::") || functionId.startsWith("configuration::")) ? "default" : namespace;
2291
2867
  }
2292
- const MIGRATION_GUIDE = "https://iii.dev/docs/upgrading/from-0-24-x";
2293
- /** CONTRACT §5: one warning per page per deprecated API. */
2294
- const DEPRECATIONS = {
2295
- registerTrigger: `registerTrigger is deprecated and will be removed in a future release. Use iii.observe(source, target) instead. Migration guide: ${MIGRATION_GUIDE}`,
2296
- registerTriggerType: `registerTriggerType is deprecated and will be removed in a future release. Register a function with an observe descriptor (registerFunction(id, handler, { observe: { ... } })) instead. Migration guide: ${MIGRATION_GUIDE}`
2297
- };
2298
- const deprecationsWarned = /* @__PURE__ */ new Set();
2868
+ /** Whether an observer of the snapshot captures the input or filters on it; computed once per snapshot. */
2869
+ const inputReaders = /* @__PURE__ */ new WeakMap();
2870
+ function readsInput(snapshot) {
2871
+ let reads = inputReaders.get(snapshot);
2872
+ if (reads === void 0) {
2873
+ reads = snapshot.some((obs) => obs.capture.includes("input") || obs.filter.roots.has("input"));
2874
+ inputReaders.set(snapshot, reads);
2875
+ }
2876
+ return reads;
2877
+ }
2299
2878
  /**
2300
2879
  * Local dispatch hands the handler a copy of the caller's payload and the
2301
2880
  * caller a copy of the result (value semantics, as over the wire):
@@ -2314,222 +2893,115 @@ const UNSUPPORTED_REASON = {
2314
2893
  code: "UNSUPPORTED",
2315
2894
  message: "the engine does not support observe (no observe.v1 in its features); upgrade it to 0.25 or later"
2316
2895
  };
2317
- /** `args_format` needs `delivery: 'owner'`: an auto function's events are its invocations, offered to every observer. */
2318
- function validateObserveHooks(functionId, hooks) {
2319
- if (!hooks) return;
2320
- const delivery = hooks.delivery;
2321
- if (delivery !== void 0 && delivery !== "auto" && delivery !== "owner") throw new InvocationError({
2322
- code: "INVALID_OBSERVE_DESCRIPTOR",
2323
- message: `observe.delivery must be 'auto' or 'owner', got ${JSON.stringify(delivery)}`,
2324
- function_id: functionId
2325
- });
2326
- if (hooks.args_format !== void 0 && delivery !== "owner") throw new InvocationError({
2327
- code: "INVALID_OBSERVE_DESCRIPTOR",
2328
- message: "observe.args_format requires delivery: 'owner' (an auto function takes no args)",
2329
- function_id: functionId
2330
- });
2331
- }
2332
- /**
2333
- * The error a call that timed out rejects with, on the remote and the local
2334
- * path: an `Error` (its message unchanged from earlier releases) that also
2335
- * carries `code: 'TIMEOUT'` and the `function_id`, like the Node SDK's.
2336
- */
2337
- function timeoutError(ms, functionId) {
2338
- return Object.assign(/* @__PURE__ */ new Error(`Invocation timeout after ${ms}ms: ${functionId}`), {
2339
- code: "TIMEOUT",
2340
- function_id: functionId
2341
- });
2342
- }
2343
- /** What a handler failure reports when the thrown value cannot even be read (a getter or `toString` that throws). */
2344
- const UNREADABLE_FAILURE = "the handler failed with a value that cannot be read";
2345
- function safeString(value) {
2346
- try {
2347
- return String(value);
2348
- } catch {
2349
- return UNREADABLE_FAILURE;
2350
- }
2351
- }
2352
- /**
2353
- * An error body as the engine sends it, and as this SDK's own calls reject
2354
- * with: a plain (JSON-parsed) object with a string `code`, a string `message`
2355
- * and, optionally, a string `stacktrace`. A class instance or anything else
2356
- * with such fields is not one: it is reported through `String()`.
2357
- */
2358
- function isEngineErrorBody(value) {
2359
- if (value === null || typeof value !== "object") return false;
2360
- const proto = Object.getPrototypeOf(value);
2361
- if (proto !== Object.prototype && proto !== null) return false;
2362
- const body = value;
2363
- return typeof body.code === "string" && typeof body.message === "string" && (body.stacktrace === void 0 || typeof body.stacktrace === "string");
2364
- }
2365
- /**
2366
- * The error a handler's failure becomes, the same on the local and the remote
2367
- * path (code `invocation_failed`):
2368
- * - an `Error`, from any realm (an iframe's too): its message and stack;
2369
- * - an engine error body (a failed call's rejection, rethrown): its message and stacktrace;
2370
- * - anything else: `String(value)`.
2371
- * Never throws: when reading the value throws, a fixed message is reported, so
2372
- * the caller always gets its answer.
2373
- */
2374
- function handlerErrorBody(error) {
2375
- try {
2376
- if (error instanceof Error || Object.prototype.toString.call(error) === "[object Error]") {
2377
- const { message, stack } = error;
2378
- return {
2379
- code: "invocation_failed",
2380
- message: typeof message === "string" ? message : safeString(message),
2381
- stacktrace: typeof stack === "string" ? stack : void 0
2382
- };
2383
- }
2384
- if (isEngineErrorBody(error)) return {
2385
- code: "invocation_failed",
2386
- message: error.message,
2387
- stacktrace: error.stacktrace
2388
- };
2389
- return {
2390
- code: "invocation_failed",
2391
- message: String(error),
2392
- stacktrace: void 0
2393
- };
2394
- } catch {
2395
- return {
2396
- code: "invocation_failed",
2397
- message: safeString(error),
2398
- stacktrace: void 0
2399
- };
2400
- }
2401
- }
2402
2896
  function resolveNamespace(optionNamespace) {
2403
2897
  if (optionNamespace !== void 0 && optionNamespace.trim() === "") throw new Error(`namespace is empty: options.namespace was set to ${JSON.stringify(optionNamespace)}. Give it a name, or leave it unset to register in \`default\`.`);
2404
2898
  return optionNamespace;
2405
2899
  }
2900
+ /** The upgrade guide the removed 0.25 trigger APIs point to. */
2901
+ const UPGRADE_GUIDE = "https://iii.dev/docs/upgrading/from-0-25-x";
2406
2902
  var Sdk = class {
2407
2903
  constructor(address, options) {
2408
2904
  this.address = address;
2409
- this.options = options;
2410
2905
  this.functions = /* @__PURE__ */ new Map();
2411
2906
  this.invocations = /* @__PURE__ */ new Map();
2412
- this.triggers = /* @__PURE__ */ new Map();
2413
- this.triggerTypes = /* @__PURE__ */ new Map();
2414
2907
  this.messagesToSend = [];
2415
2908
  this.reconnectAttempt = 0;
2416
2909
  this.connectionState = "disconnected";
2417
2910
  this.connectionListeners = /* @__PURE__ */ new Set();
2418
2911
  this.isShuttingDown = false;
2419
- this.observers = /* @__PURE__ */ new Map();
2912
+ this.observerHandles = /* @__PURE__ */ new Map();
2913
+ this.observesSent = /* @__PURE__ */ new Map();
2420
2914
  this.engineFeatures = /* @__PURE__ */ new Set();
2421
2915
  this.registeredOnConnection = false;
2422
2916
  this.connectionEpoch = 0;
2917
+ this.workerHooks = {};
2918
+ this.functionHooks = /* @__PURE__ */ new Map();
2423
2919
  this.hooksInactiveWarned = /* @__PURE__ */ new Set();
2920
+ this.unsupportedWarned = /* @__PURE__ */ new Set();
2921
+ this.unregisteredHooksWarned = /* @__PURE__ */ new Set();
2424
2922
  this.observeQueue = [];
2425
- this.registerTriggerType = (triggerType, handler) => {
2426
- this.warnDeprecated("registerTriggerType");
2427
- const message = this.snapshotRegistration({
2428
- ...triggerType,
2429
- message_type: "registertriggertype"
2430
- });
2431
- this.sendMessage("registertriggertype", message, true);
2432
- this.triggerTypes.set(message.id, {
2433
- message,
2434
- handler
2435
- });
2436
- return {
2437
- id: message.id,
2438
- registerTrigger: (functionId, config) => {
2439
- return this.registerTrigger({
2440
- type: message.id,
2441
- function_id: functionId,
2442
- config,
2443
- namespace: this.namespace
2444
- });
2445
- },
2446
- registerFunction: (functionId, handler, config) => {
2447
- const ref = this.registerFunction(functionId, handler);
2448
- this.registerTrigger({
2449
- type: message.id,
2450
- function_id: functionId,
2451
- config,
2452
- namespace: this.namespace
2453
- });
2454
- return ref;
2455
- },
2456
- unregister: () => {
2457
- this.unregisterTriggerType(message);
2458
- }
2459
- };
2460
- };
2461
- this.unregisterTriggerType = (triggerType) => {
2462
- const { id, namespace } = triggerType;
2463
- this.sendMessage("unregistertriggertype", namespace !== void 0 ? {
2464
- id,
2465
- namespace
2466
- } : { id }, true);
2467
- this.triggerTypes.delete(id);
2468
- };
2469
- this.registerTrigger = (trigger) => {
2470
- this.warnDeprecated("registerTrigger");
2471
- const id = require_utils.randomUUID();
2472
- const fullTrigger = this.snapshotRegistration({
2473
- ...trigger,
2474
- id,
2475
- message_type: "registertrigger",
2476
- ...(() => {
2477
- const namespace = callNamespace(trigger.namespace, this.namespace, "RegisterTriggerInput.namespace");
2478
- return namespace !== void 0 ? { namespace } : {};
2479
- })()
2480
- });
2481
- this.sendMessage("registertrigger", fullTrigger, true);
2482
- this.triggers.set(id, fullTrigger);
2483
- return { unregister: () => {
2484
- this.sendMessage("unregistertrigger", {
2485
- id,
2486
- message_type: "unregistertrigger",
2487
- type: fullTrigger.type
2488
- });
2489
- this.triggers.delete(id);
2490
- } };
2491
- };
2492
- this.registerFunction = (functionId, handlerOrInvocation, options) => {
2923
+ this.registerFunction = (functionId, handler, options) => {
2493
2924
  if (!functionId || functionId.trim() === "") throw new Error("id is required");
2494
2925
  if (this.functions.has(functionId)) throw new Error(`function id already registered: ${functionId}`);
2495
- const { observe: hooks, localDispatch, ...wireOptions } = options ?? {};
2496
- validateObserveHooks(functionId, hooks);
2497
- const descriptor = observeDescriptor(hooks);
2926
+ const { localDispatch, private: isPrivate, observable, ...wireOptions } = options ?? {};
2498
2927
  const fullMessage = this.snapshotRegistration({
2499
2928
  ...wireOptions,
2500
- ...descriptor ? { observe: descriptor } : {},
2929
+ ...isPrivate === true ? { private: true } : {},
2930
+ ...observable === false ? { observable: false } : {},
2501
2931
  id: functionId,
2502
2932
  message_type: "registerfunction"
2503
2933
  });
2504
- this.sendMessage("registerfunction", fullMessage, true);
2505
- const observe = new FunctionObservers(functionId, hooks, localDispatch !== false, true, this.observeHost);
2506
- if (observe.needsObserve && this.registeredOnConnection && !this.engineFeatures.has("observe.v1")) this.warnHooksInactive(functionId);
2507
- const handler = handlerOrInvocation;
2508
- this.functions.set(functionId, {
2934
+ const frame = this.prepareJson(this.toWireFormat("registerfunction", fullMessage));
2935
+ const observe = new FunctionObservers(functionId, localDispatch !== false, true, this.observeHost);
2936
+ const fn = {
2509
2937
  message: fullMessage,
2510
2938
  observe,
2511
2939
  handler: async (input, metadata) => {
2512
2940
  return await handler(input, metadata);
2513
2941
  }
2514
- });
2515
- return {
2942
+ };
2943
+ this.functions.set(functionId, fn);
2944
+ if (this.mayRegister(functionId, fn)) {
2945
+ this.sendMessageRaw(frame);
2946
+ fn.sentEpoch = this.connectionEpoch;
2947
+ }
2948
+ if (this.registeredOnConnection && !this.engineFeatures.has("observe.v1") && this.hasObserverHooks(functionId)) this.warnHooksInactive(functionId);
2949
+ const ref = {
2516
2950
  id: functionId,
2951
+ onObserverAdded: (hook) => {
2952
+ this.onObserverAdded(functionId, hook);
2953
+ return ref;
2954
+ },
2955
+ onObserverRemoved: (hook) => {
2956
+ this.onObserverRemoved(functionId, hook);
2957
+ return ref;
2958
+ },
2959
+ onObservationMatch: (hook) => {
2960
+ this.onObservationMatch(functionId, hook);
2961
+ return ref;
2962
+ },
2963
+ onObservationDeliver: (hook) => {
2964
+ this.onObservationDeliver(functionId, hook);
2965
+ return ref;
2966
+ },
2967
+ observers: () => observe.observers(),
2968
+ isObserved: (call) => observe.isObserved(call),
2517
2969
  unregister: () => {
2518
- if (this.functions.get(functionId)?.observe !== observe) return;
2970
+ if (this.functions.get(functionId) !== fn) return;
2519
2971
  this.sendMessage("unregisterfunction", { id: functionId }, true);
2520
2972
  this.functions.delete(functionId);
2521
2973
  observe.dispose();
2522
- },
2523
- isObserved: () => observe.isObserved(),
2524
- observers: () => observe.observers()
2974
+ }
2525
2975
  };
2976
+ return ref;
2977
+ };
2978
+ this.onObserverAdded = (a, b) => {
2979
+ if (typeof a === "string") this.setFunctionHook(a, "added", b);
2980
+ else this.setWorkerHook("added", a);
2981
+ return this;
2982
+ };
2983
+ this.onObserverRemoved = (a, b) => {
2984
+ if (typeof a === "string") this.setFunctionHook(a, "removed", b);
2985
+ else this.setWorkerHook("removed", a);
2986
+ return this;
2987
+ };
2988
+ this.onObservationMatch = (functionId, hook) => {
2989
+ this.setFunctionHook(functionId, "match", hook);
2990
+ return this;
2526
2991
  };
2527
- this.observe = (source, target, options) => {
2992
+ this.onObservationDeliver = (functionId, hook) => {
2993
+ this.setFunctionHook(functionId, "deliver", hook);
2994
+ return this;
2995
+ };
2996
+ this.observers = (functionId) => this.functions.get(functionId)?.observe.observers() ?? [];
2997
+ this.isObserved = (functionId, call) => this.functions.get(functionId)?.observe.isObserved(call) ?? false;
2998
+ this.observe = (sourceOrId, target, options) => {
2999
+ const source = typeof sourceOrId === "string" ? { function_id: sourceOrId } : sourceOrId;
2528
3000
  if (!source || typeof source.function_id !== "string" || source.function_id.trim() === "") throw new Error("observe: source.function_id is required");
2529
3001
  const targetId = typeof target === "string" ? target : target?.function_id;
2530
3002
  if (typeof targetId !== "string" || targetId.trim() === "") throw new Error("observe: target is required (the id of a registered function)");
2531
3003
  const id = options?.id ?? require_utils.randomUUID();
2532
- if (this.observers.has(id)) throw new Error(`observe: observer id already in use: ${id}`);
3004
+ if (this.observerHandles.has(id)) throw new ObserveRejection("OBSERVER_ID_CONFLICT", `observe: observer id already in use: ${id}`);
2533
3005
  const onDispose = (h) => this.disposeObserver(h);
2534
3006
  const logError = (msg, error) => this.logError(msg, error);
2535
3007
  const refused = (reason) => {
@@ -2561,7 +3033,7 @@ var Sdk = class {
2561
3033
  });
2562
3034
  }
2563
3035
  const handle = new ObserverHandleImpl(id, message, onDispose, logError);
2564
- this.observers.set(id, handle);
3036
+ this.observerHandles.set(id, handle);
2565
3037
  if (this.registeredOnConnection && this.isOpen()) if (this.engineFeatures.has("observe.v1")) this.sendObserve(handle);
2566
3038
  else handle.setState("error", UNSUPPORTED_REASON);
2567
3039
  return handle;
@@ -2569,7 +3041,7 @@ var Sdk = class {
2569
3041
  this.currentInvocation = () => publicContext(currentContext());
2570
3042
  this.withInvocation = (invocation, fn) => enterInvocation(contextFromView(invocation), fn, MAX_RUNNING_INVOCATION_MS);
2571
3043
  this.__helpers_create_channel = async (bufferSize) => {
2572
- const result = await this.trigger({
3044
+ const result = await this.call({
2573
3045
  function_id: "engine::channels::create",
2574
3046
  payload: { buffer_size: bufferSize }
2575
3047
  });
@@ -2580,17 +3052,31 @@ var Sdk = class {
2580
3052
  readerRef: result.reader
2581
3053
  };
2582
3054
  };
2583
- this.trigger = async (request) => {
2584
- const { function_id, action } = request;
2585
- const namespace = invocationNamespace(request.namespace, this.namespace, function_id);
2586
- if (request.dispatch !== "remote" && action?.type !== "enqueue") {
3055
+ this.call = async (request) => {
3056
+ if (request.observer !== void 0) {
3057
+ const { observer, payload, action, timeoutMs } = request;
3058
+ if (request.metadata != null) throw new Error(OBSERVER_CALL_METADATA);
3059
+ return this.invokeRemote({
3060
+ function_id: observer.target,
3061
+ payload,
3062
+ action,
3063
+ timeoutMs
3064
+ }, void 0, { observer_id: observer.id });
3065
+ }
3066
+ const req = request.metadata === null ? {
3067
+ ...request,
3068
+ metadata: void 0
3069
+ } : request;
3070
+ const { function_id, action } = req;
3071
+ const namespace = invocationNamespace(req.namespace, this.namespace, function_id);
3072
+ if (req.dispatch !== "remote" && action?.type !== "enqueue") {
2587
3073
  const fn = this.functions.get(function_id);
2588
3074
  const observe = fn?.observe;
2589
3075
  if (fn?.handler && observe?.localDispatch && (namespace === void 0 || namespace === observe.namespace)) {
2590
3076
  const depth = callLocalDepth();
2591
- if (depth < 64) return this.invokeLocal(function_id, fn.handler, observe, request);
3077
+ if (depth < 64) return this.invokeLocal(function_id, fn, req);
2592
3078
  if (!this.isOpen()) {
2593
- if (depth < 256) return this.invokeLocal(function_id, fn.handler, observe, request);
3079
+ if (depth < 256) return this.invokeLocal(function_id, fn, req);
2594
3080
  throw new InvocationError({
2595
3081
  code: "LOCAL_DEPTH_EXCEEDED",
2596
3082
  message: `${function_id} is called ${depth} local calls deep: past ${64} the call needs the engine, and the socket is closed`,
@@ -2599,7 +3085,17 @@ var Sdk = class {
2599
3085
  }
2600
3086
  }
2601
3087
  }
2602
- return this.invokeRemote(request, namespace);
3088
+ return this.invokeRemote(req, namespace);
3089
+ };
3090
+ this.trigger = this.call;
3091
+ this.registerTrigger = () => {
3092
+ throw new Error(`registerTrigger was removed in iii 0.26.0: bind functions with iii.observe(source, target). registerTrigger({ type: 'cron', function_id, config }) becomes iii.observe({ function_id: 'cron::on-tick', args: config }, function_id). Every trigger type's function is in the migration guide: ${UPGRADE_GUIDE}`);
3093
+ };
3094
+ this.registerTriggerType = () => {
3095
+ throw new Error(`registerTriggerType was removed in iii 0.26.0: a trigger type is now a function that consumers observe. Register it with registerFunction('<worker>::on-<event>', (event) => event, { args_format, private: true }), move the TriggerHandler to onObserverAdded and onObserverRemoved, and call the function once per event. Migration guide: ${UPGRADE_GUIDE}#move-a-trigger-type-to-an-observable-function`);
3096
+ };
3097
+ this.unregisterTriggerType = () => {
3098
+ throw new Error(`unregisterTriggerType was removed in iii 0.26.0: a trigger type is now a function. Unregister it with the FunctionRef that registerFunction returns: functionRef.unregister(). Migration guide: ${UPGRADE_GUIDE}#move-a-trigger-type-to-an-observable-function`);
2603
3099
  };
2604
3100
  this.__helpers_create_stream = (streamName, stream) => {
2605
3101
  this.registerFunction(`stream::get(${streamName})`, stream.get.bind(stream));
@@ -2670,39 +3166,146 @@ var Sdk = class {
2670
3166
  logError: (message, error) => this.logError(message, error)
2671
3167
  }, options?.observe?.reporter);
2672
3168
  this.observeHost = {
2673
- identity: () => this.workerId !== void 0 ? {
2674
- worker_id: this.workerId,
2675
- worker_name: this.workerName
2676
- } : { worker_name: this.workerName },
2677
3169
  sendAck: (ack) => this.sendMessage("observerack", buildObserverAck(ack), true),
2678
3170
  reporter: this.reporter,
2679
- callTarget: (target, observerId, payload, timeoutMs) => this.invokeRemote({
2680
- function_id: target,
2681
- payload,
2682
- timeoutMs
2683
- }, void 0, { observer_id: observerId }),
3171
+ hooks: (functionId) => this.hooksOf(functionId),
2684
3172
  logError: (message, error) => this.logError(message, error),
3173
+ logWarn: (message) => this.logWarn(message),
2685
3174
  hookTimeoutMs: () => options?.observe?.hookTimeoutMs ?? 3e4,
2686
- traceContext: () => ({})
3175
+ observeV2: () => this.engineFeatures.has(FEATURE_OBSERVE_V2)
2687
3176
  };
2688
3177
  this.reporter.start();
2689
3178
  this.connect();
2690
3179
  }
2691
- warnDeprecated(api) {
2692
- if (deprecationsWarned.has(api)) return;
2693
- deprecationsWarned.add(api);
2694
- console.warn(`[iii] ${DEPRECATIONS[api]}`);
2695
- }
2696
3180
  logError(message, error) {
2697
3181
  if (error === void 0) console.error(`[iii] ${message}`);
2698
3182
  else console.error(`[iii] ${message}`, error);
2699
3183
  }
3184
+ logWarn(message) {
3185
+ console.warn(`[iii] ${message}`);
3186
+ }
3187
+ logInfo(message) {
3188
+ console.info(`[iii] ${message}`);
3189
+ }
3190
+ /**
3191
+ * What a function needs `observe.v2` for (decision 18): `args_format`,
3192
+ * `private`, `observable: false`, a match hook or a deliver hook.
3193
+ */
3194
+ needsObserveV2(functionId, fn) {
3195
+ const { message } = fn;
3196
+ const hooks = this.functionHooks.get(functionId);
3197
+ return message.args_format !== void 0 || message.private === true || message.observable === false || hooks?.match !== void 0 || hooks?.deliver !== void 0;
3198
+ }
3199
+ /**
3200
+ * Whether the function's `registerfunction` may go out on the current
3201
+ * connection now. One that needs `observe.v2` waits for this connection's
3202
+ * `WorkerRegistered`, and stays unregistered (`holdUnsupported`) when the
3203
+ * engine does not advertise it (decision 41).
3204
+ */
3205
+ mayRegister(functionId, fn) {
3206
+ if (!this.isOpen()) return false;
3207
+ if (!this.needsObserveV2(functionId, fn)) return true;
3208
+ if (!this.registeredOnConnection) return false;
3209
+ if (this.engineFeatures.has("observe.v2")) return true;
3210
+ this.holdUnsupported(functionId, fn);
3211
+ return false;
3212
+ }
3213
+ /**
3214
+ * A function that needs `observe.v2` on a connection whose engine does not
3215
+ * advertise it: the engine does not hold it here, so what it kept from an
3216
+ * earlier connection is released once per connection (local dispatch, its
3217
+ * observers through `onObserverRemoved`, held reports), and `UNSUPPORTED`
3218
+ * is logged once per function.
3219
+ */
3220
+ holdUnsupported(functionId, fn) {
3221
+ if (fn.observe.releasedEpoch !== this.connectionEpoch) fn.observe.onRegistrationRejected(this.connectionEpoch);
3222
+ this.warnUnsupported(functionId);
3223
+ }
3224
+ /** Sends the registrations that may go out now and have not on this connection. */
3225
+ sendRegistrations() {
3226
+ for (const [functionId, fn] of this.functions) {
3227
+ if (fn.sentEpoch === this.connectionEpoch || !this.mayRegister(functionId, fn)) continue;
3228
+ this.replayRegistration("registerfunction", fn.message);
3229
+ fn.sentEpoch = this.connectionEpoch;
3230
+ }
3231
+ }
3232
+ /**
3233
+ * Decides the registration again once a match or deliver hook may have
3234
+ * changed whether the function needs `observe.v2` (set or removed, or set
3235
+ * before `WorkerRegistered`): against an engine without it, a registered
3236
+ * function is unregistered (and one held back is registered once it no
3237
+ * longer needs it).
3238
+ */
3239
+ reconcileRegistration(functionId) {
3240
+ const fn = this.functions.get(functionId);
3241
+ if (!fn || !this.isOpen() || !this.registeredOnConnection) return;
3242
+ const sent = fn.sentEpoch === this.connectionEpoch;
3243
+ const allowed = this.engineFeatures.has("observe.v2") || !this.needsObserveV2(functionId, fn);
3244
+ if (sent && !allowed) {
3245
+ this.sendMessage("unregisterfunction", { id: functionId }, true);
3246
+ fn.sentEpoch = void 0;
3247
+ this.holdUnsupported(functionId, fn);
3248
+ } else if (!sent && allowed) {
3249
+ this.replayRegistration("registerfunction", fn.message);
3250
+ fn.sentEpoch = this.connectionEpoch;
3251
+ }
3252
+ }
3253
+ warnUnsupported(functionId) {
3254
+ if (this.unsupportedWarned.has(functionId)) return;
3255
+ this.unsupportedWarned.add(functionId);
3256
+ this.logWarn(`UNSUPPORTED: function "${functionId}" needs observe.v2 (args_format, private, observable: false, onObservationMatch or onObservationDeliver), which this engine does not advertise; it stays unregistered until the worker connects to an engine with observe.v2.`);
3257
+ }
3258
+ /** The hooks that apply to one function now: the worker's, and those set for its id. */
3259
+ hooksOf(functionId) {
3260
+ const own = this.functionHooks.get(functionId);
3261
+ return {
3262
+ workerAdded: this.workerHooks.added,
3263
+ workerRemoved: this.workerHooks.removed,
3264
+ added: own?.added,
3265
+ removed: own?.removed,
3266
+ match: own?.match,
3267
+ deliver: own?.deliver
3268
+ };
3269
+ }
3270
+ hasObserverHooks(functionId) {
3271
+ const own = this.functionHooks.get(functionId);
3272
+ return !!(this.workerHooks.added || this.workerHooks.removed || own?.added || own?.removed || own?.match || own?.deliver);
3273
+ }
3274
+ setFunctionHook(functionId, kind, hook) {
3275
+ if (typeof functionId !== "string" || functionId.trim() === "") throw new TypeError("the function id of an observer hook is required");
3276
+ const keys = kind === "match" && hook !== null && typeof hook === "object" && typeof hook.observer === "function" && typeof hook.call === "function";
3277
+ if (hook !== null && typeof hook !== "function" && !keys) throw new TypeError(kind === "match" ? `the match hook of ${functionId} must be a predicate, { observer, call } key functions, or null to remove it` : `the ${kind} hook of ${functionId} must be a function, or null to remove it`);
3278
+ const hooks = {
3279
+ ...this.functionHooks.get(functionId),
3280
+ [kind]: hook ?? void 0
3281
+ };
3282
+ if (hooks.added || hooks.removed || hooks.match || hooks.deliver) this.functionHooks.set(functionId, hooks);
3283
+ else this.functionHooks.delete(functionId);
3284
+ const fn = this.functions.get(functionId);
3285
+ if (!fn) return;
3286
+ if (kind === "added" && hook) fn.observe.catchUp("fn");
3287
+ if (kind === "match") fn.observe.matchChanged();
3288
+ if (kind === "match" || kind === "deliver") this.reconcileRegistration(functionId);
3289
+ }
3290
+ setWorkerHook(kind, hook) {
3291
+ if (hook !== null && typeof hook !== "function") throw new TypeError(`the worker's ${kind} hook must be a function, or null to remove it`);
3292
+ this.workerHooks = {
3293
+ ...this.workerHooks,
3294
+ [kind]: hook ?? void 0
3295
+ };
3296
+ if (kind === "added" && hook) for (const fn of this.functions.values()) fn.observe.catchUp("worker");
3297
+ }
2700
3298
  sendObserve(handle) {
2701
3299
  this.sendMessage("observe", handle.message, true);
2702
3300
  handle.sent = true;
3301
+ handle.answered = false;
3302
+ const sent = this.observesSent.get(handle.id);
3303
+ if (sent) sent.push(handle);
3304
+ else this.observesSent.set(handle.id, [handle]);
2703
3305
  }
2704
3306
  disposeObserver(handle) {
2705
- if (this.observers.get(handle.id) === handle) this.observers.delete(handle.id);
3307
+ if (this.observerHandles.get(handle.id) === handle) this.observerHandles.delete(handle.id);
3308
+ if (handle.answered) this.unlistObserve(handle);
2706
3309
  if (!handle.sent) return;
2707
3310
  this.sendObserveFamily("unobserve", { id: handle.id });
2708
3311
  }
@@ -2722,7 +3325,15 @@ var Sdk = class {
2722
3325
  warnHooksInactive(functionId) {
2723
3326
  if (this.hooksInactiveWarned.has(functionId)) return;
2724
3327
  this.hooksInactiveWarned.add(functionId);
2725
- console.warn(`[iii] Function "${functionId}" declares observe hooks or owner delivery, but the engine does not support observe (observe.v1): it is registered as a plain function and its observe hooks are inactive.`);
3328
+ this.logWarn(`Function "${functionId}" has observer hooks, but the engine does not support observe (observe.v1): it is registered as a plain function and its observer hooks are inactive.`);
3329
+ }
3330
+ /** Once the connection is registered: a hook set for an id this worker has not registered (a mistyped id?). */
3331
+ warnUnregisteredHookIds() {
3332
+ for (const functionId of this.functionHooks.keys()) {
3333
+ if (this.functions.has(functionId) || this.unregisteredHooksWarned.has(functionId)) continue;
3334
+ this.unregisteredHooksWarned.add(functionId);
3335
+ this.logWarn(`Observer hooks are set for "${functionId}", which this worker has not registered; check the function id.`);
3336
+ }
2726
3337
  }
2727
3338
  /** Connected to an engine that advertised `observe.v1`. */
2728
3339
  observeOnline() {
@@ -2750,6 +3361,7 @@ var Sdk = class {
2750
3361
  }
2751
3362
  /** The routed path: an `InvokeFunction` through the engine. */
2752
3363
  invokeRemote(request, namespace, activation) {
3364
+ if (this.fatalError) return Promise.reject(this.fatalError);
2753
3365
  const { function_id, payload, action, timeoutMs, metadata } = request;
2754
3366
  const effectiveTimeout = timeoutMs ?? this.invocationTimeoutMs;
2755
3367
  const outgoing = this.outgoingFields(request);
@@ -2770,7 +3382,7 @@ var Sdk = class {
2770
3382
  const timeout = setTimeout(() => {
2771
3383
  if (this.invocations.get(invocation_id)) {
2772
3384
  this.invocations.delete(invocation_id);
2773
- reject(timeoutError(effectiveTimeout, function_id));
3385
+ reject(new InvocationTimeoutError(effectiveTimeout, function_id));
2774
3386
  }
2775
3387
  }, effectiveTimeout);
2776
3388
  this.invocations.set(invocation_id, {
@@ -2797,13 +3409,30 @@ var Sdk = class {
2797
3409
  });
2798
3410
  }
2799
3411
  /**
2800
- * The local path (sdk.md §4.3): runs the handler in-process, with a copy of
2801
- * the payload, inside a new invocation context; the same timeout and the
2802
- * same rejection value as the remote path; reports the call when an
2803
- * observer matches. Puts nothing on the wire when nobody observes the
2804
- * function.
3412
+ * Runs a call's delivery inside `ctx`: the function's deliver hook, or
3413
+ * iii's delivery to its observers. The hook sees the invocation up to its
3414
+ * first `await`, and counts as delivering until it settles, so the calls it
3415
+ * makes after an `await` fall back to the invocation while it is the only
3416
+ * one running (`callContext`).
3417
+ */
3418
+ deliverIn(ctx, delivery, hook) {
3419
+ if (hook === void 0) return delivery.run(void 0);
3420
+ const untrack = trackDelivering(ctx);
3421
+ return runInContext(ctx, () => delivery.run(hook)).finally(untrack);
3422
+ }
3423
+ /**
3424
+ * The local path (sdk.md §4.3): runs the handler in-process inside a new
3425
+ * invocation context, then delivers the call (the function's deliver hook,
3426
+ * or iii's delivery to its observers); the same timeout and the same
3427
+ * rejection value as the remote path. A call of a function nobody observes
3428
+ * and without a deliver hook puts nothing on the wire.
3429
+ *
3430
+ * The handler gets a copy of the payload and the caller a copy of the
3431
+ * result; a private function's input and result pass by reference.
2805
3432
  */
2806
- invokeLocal(function_id, handler, observe, request) {
3433
+ invokeLocal(function_id, fn, request) {
3434
+ const { observe } = fn;
3435
+ const handler = fn.handler;
2807
3436
  const parent = callContext();
2808
3437
  const caller = this.workerId !== void 0 ? {
2809
3438
  worker_id: this.workerId,
@@ -2820,51 +3449,63 @@ var Sdk = class {
2820
3449
  invocation_id: require_utils.randomUUID(),
2821
3450
  caller,
2822
3451
  observe_depth: parent ? parent.observe_depth : callDepth(),
2823
- metadata: request.metadata,
2824
3452
  localDepth: callLocalDepth() + 1
2825
3453
  };
2826
3454
  const traceparent = request.traceparent ?? parent?.traceparent;
2827
3455
  const baggage = request.baggage ?? parent?.baggage;
2828
3456
  if (traceparent !== void 0) ctx.traceparent = traceparent;
2829
3457
  if (baggage !== void 0) ctx.baggage = baggage;
2830
- const set = observe.delivery === "auto" ? observe.compiled : [];
3458
+ const snapshot = observe.compiled;
3459
+ const activations = observe.activations;
3460
+ const hook = this.functionHooks.get(function_id)?.deliver;
3461
+ const delivering = hook !== void 0 || snapshot.length > 0;
3462
+ const copiesInput = delivering && (hook !== void 0 || this.functionHooks.get(function_id)?.match !== void 0 || readsInput(snapshot));
3463
+ const byReference = fn.message.private === true;
2831
3464
  let input;
2832
- let observedInput;
2833
- let observedMetadata;
2834
3465
  let metadata;
3466
+ let callInput;
3467
+ let callMetadata;
2835
3468
  try {
2836
- if (set.length > 0) {
2837
- observedInput = cloneValue(request.payload);
2838
- observedMetadata = request.metadata === void 0 ? void 0 : cloneValue(request.metadata);
3469
+ if (byReference) {
3470
+ callInput = request.payload;
3471
+ callMetadata = request.metadata;
3472
+ input = this.resolveChannelValue(request.payload);
3473
+ metadata = request.metadata;
3474
+ } else {
3475
+ if (copiesInput) {
3476
+ callInput = cloneValue(request.payload);
3477
+ callMetadata = request.metadata === void 0 ? void 0 : cloneValue(request.metadata);
3478
+ }
3479
+ input = this.resolveChannelValue(cloneValue(request.payload));
3480
+ metadata = request.metadata === void 0 ? void 0 : cloneValue(request.metadata);
2839
3481
  }
2840
- input = this.resolveChannelValue(cloneValue(request.payload));
2841
- metadata = request.metadata === void 0 ? void 0 : cloneValue(request.metadata);
2842
3482
  } catch (error) {
2843
3483
  return Promise.reject(error);
2844
3484
  }
2845
3485
  const startedAt = Date.now();
2846
3486
  const t0 = performance.now();
2847
- const finish = (ok, output, error) => {
2848
- try {
2849
- const duration = performance.now() - t0;
2850
- this.reporter.recordLocal(function_id, ok, duration);
2851
- observe.reportLocal(set, {
2852
- invocation_id: ctx.invocation_id,
2853
- ok,
2854
- input: observedInput,
2855
- output,
2856
- error,
2857
- caller: ctx.caller,
2858
- metadata: observedMetadata,
2859
- started_at_ms: startedAt,
2860
- duration_ms: duration,
2861
- observe_depth: ctx.observe_depth,
2862
- traceparent,
2863
- baggage
2864
- });
2865
- } catch (reportError) {
2866
- this.logError(`Failed to report a local invocation of ${function_id}`, reportError);
3487
+ let delivery;
3488
+ const settle = (handled) => {
3489
+ const duration = performance.now() - t0;
3490
+ this.reporter.recordLocal(function_id, handled.ok, duration);
3491
+ if (!delivering) {
3492
+ if (handled.ok) return handled.value;
3493
+ throw handled.error;
2867
3494
  }
3495
+ const outcome = byReference ? handled : this.deliveredOutcome(handled, input, callInput);
3496
+ delivery = new Delivery(observe, {
3497
+ call: this.callOf(function_id, ctx.invocation_id, outcome, callInput, ctx.caller, callMetadata),
3498
+ thrown: outcome.ok ? void 0 : outcome.error,
3499
+ snapshot,
3500
+ activations,
3501
+ started_at_ms: startedAt,
3502
+ duration_ms: duration,
3503
+ observe_depth: ctx.observe_depth,
3504
+ traceparent,
3505
+ baggage,
3506
+ routed: false
3507
+ });
3508
+ return this.deliverIn(ctx, delivery, hook);
2868
3509
  };
2869
3510
  const effectiveTimeout = request.timeoutMs ?? this.invocationTimeoutMs;
2870
3511
  const untrack = trackRunning(ctx, effectiveTimeout);
@@ -2874,15 +3515,18 @@ var Sdk = class {
2874
3515
  } catch (error) {
2875
3516
  started = Promise.reject(error);
2876
3517
  }
2877
- const done = started.then((output) => {
3518
+ const done = started.then((value) => settle({
3519
+ ok: true,
3520
+ value
3521
+ }), (error) => settle({
3522
+ ok: false,
3523
+ error
3524
+ })).then((output) => {
2878
3525
  untrack();
2879
- finish(true, output, void 0);
2880
3526
  return output;
2881
3527
  }, (error) => {
2882
3528
  untrack();
2883
- const body = handlerErrorBody(error);
2884
- finish(false, void 0, body);
2885
- throw body;
3529
+ throw delivery ? delivery.errorBody(error) : handlerErrorBody(error);
2886
3530
  });
2887
3531
  if (request.action?.type === "void") {
2888
3532
  done.catch((error) => this.logError(`Error invoking function ${function_id}`, error));
@@ -2893,7 +3537,7 @@ var Sdk = class {
2893
3537
  done.then((output) => {
2894
3538
  if (timeout !== void 0) clearTimeout(timeout);
2895
3539
  try {
2896
- resolve(cloneValue(output));
3540
+ resolve(byReference ? output : cloneValue(output));
2897
3541
  } catch (error) {
2898
3542
  reject(error);
2899
3543
  }
@@ -2902,10 +3546,37 @@ var Sdk = class {
2902
3546
  reject(error);
2903
3547
  });
2904
3548
  timeout = setTimeout(() => {
2905
- reject(timeoutError(effectiveTimeout, function_id));
3549
+ reject(new InvocationTimeoutError(effectiveTimeout, function_id));
2906
3550
  }, effectiveTimeout);
2907
3551
  });
2908
3552
  }
3553
+ /**
3554
+ * The outcome a local call of a function that is not private is delivered
3555
+ * with: a handler that returns its own input unchanged is delivered with
3556
+ * the input the call started with as its output, so the report carries the
3557
+ * value once (`output_is_input`, decision 4).
3558
+ */
3559
+ deliveredOutcome(outcome, input, callInput) {
3560
+ if (!outcome.ok) return outcome;
3561
+ return outcome.value === input && input !== null && typeof input === "object" && sameData(callInput, input) ? {
3562
+ ok: true,
3563
+ value: callInput
3564
+ } : outcome;
3565
+ }
3566
+ /** The {@link Call} a finished handler made: what it was called with, and what it returned or threw. */
3567
+ callOf(function_id, invocation_id, outcome, input, caller, metadata) {
3568
+ const call = {
3569
+ function_id,
3570
+ invocation_id,
3571
+ status: outcome.ok ? "success" : "error",
3572
+ input
3573
+ };
3574
+ if (outcome.ok) call.output = outcome.value;
3575
+ else call.error = handlerErrorBody(outcome.error);
3576
+ if (caller !== void 0) call.caller = caller;
3577
+ if (metadata !== void 0) call.metadata = metadata;
3578
+ return call;
3579
+ }
2909
3580
  setConnectionState(state) {
2910
3581
  if (this.connectionState !== state) {
2911
3582
  this.connectionState = state;
@@ -2963,6 +3634,7 @@ var Sdk = class {
2963
3634
  }
2964
3635
  this.ws = void 0;
2965
3636
  this.registeredOnConnection = false;
3637
+ this.observesSent.clear();
2966
3638
  if (this.isShuttingDown) return;
2967
3639
  this.setConnectionState("disconnected");
2968
3640
  this.scheduleReconnect();
@@ -2973,6 +3645,7 @@ var Sdk = class {
2973
3645
  this.setConnectionState("connected");
2974
3646
  this.connectionEpoch++;
2975
3647
  this.registeredOnConnection = false;
3648
+ this.observesSent.clear();
2976
3649
  if (this.ws) this.ws.onmessage = this.onMessage.bind(this);
2977
3650
  if (this.workerId) try {
2978
3651
  this.sendMessageRaw(JSON.stringify({
@@ -2985,15 +3658,7 @@ var Sdk = class {
2985
3658
  console.error("[iii] Reattach JSON envelope rejected", error);
2986
3659
  }
2987
3660
  this.registerWorkerMetadata();
2988
- this.triggerTypes.forEach(({ message }) => {
2989
- this.replayRegistration("registertriggertype", message);
2990
- });
2991
- this.functions.forEach(({ message }) => {
2992
- this.replayRegistration("registerfunction", message);
2993
- });
2994
- this.triggers.forEach((trigger) => {
2995
- this.replayRegistration("registertrigger", trigger);
2996
- });
3661
+ this.sendRegistrations();
2997
3662
  const pending = this.messagesToSend;
2998
3663
  this.messagesToSend = [];
2999
3664
  for (const message of pending) {
@@ -3020,13 +3685,31 @@ var Sdk = class {
3020
3685
  console.error("[iii] Registration JSON envelope rejected", error);
3021
3686
  }
3022
3687
  }
3688
+ /**
3689
+ * The `payload_too_large` error that replaces an answer too large to send
3690
+ * is not the handler's outcome, so it activates no observer: to an engine
3691
+ * with `observe.v2` it says `delivered` when the deliver hook delivered the
3692
+ * call (`answer.delivered`), and `matched: []` otherwise, whatever the
3693
+ * function's hooks. An engine without `observe.v2` gets the bare error.
3694
+ */
3695
+ oversizedAnswer(answer, fallback) {
3696
+ if (!this.engineFeatures.has("observe.v2")) return fallback;
3697
+ if (answer.delivered === true) return {
3698
+ ...fallback,
3699
+ delivered: true
3700
+ };
3701
+ return {
3702
+ ...fallback,
3703
+ matched: []
3704
+ };
3705
+ }
3023
3706
  prepareJson(message) {
3024
3707
  const data = JSON.stringify(message);
3025
3708
  const size = JSON_ENCODER.encode(data).byteLength;
3026
3709
  if (size <= MAX_JSON_FRAME_BYTES) return data;
3027
3710
  const error = createPayloadTooLargeError(size, typeof message.function_id === "string" ? message.function_id : void 0);
3028
3711
  if (message.type === "invocationresult") {
3029
- const fallback = JSON.stringify({
3712
+ const fallback = JSON.stringify(this.oversizedAnswer(message, {
3030
3713
  type: "invocationresult",
3031
3714
  invocation_id: message.invocation_id,
3032
3715
  function_id: message.function_id,
@@ -3034,7 +3717,7 @@ var Sdk = class {
3034
3717
  code: error.code,
3035
3718
  message: payloadTooLargeMessage(size)
3036
3719
  }
3037
- });
3720
+ }));
3038
3721
  if (JSON_ENCODER.encode(fallback).byteLength <= MAX_JSON_FRAME_BYTES) return fallback;
3039
3722
  }
3040
3723
  if (typeof message.invocation_id === "string") {
@@ -3054,30 +3737,6 @@ var Sdk = class {
3054
3737
  }
3055
3738
  toWireFormat(messageType, message) {
3056
3739
  const { message_type: _, ...rest } = message;
3057
- if (messageType === "registertrigger" && "type" in message) {
3058
- const { type: triggerType, ...triggerRest } = message;
3059
- return {
3060
- type: messageType,
3061
- ...triggerRest,
3062
- trigger_type: triggerType
3063
- };
3064
- }
3065
- if (messageType === "unregistertrigger" && "type" in message) {
3066
- const { type: triggerType, ...triggerRest } = message;
3067
- return {
3068
- type: messageType,
3069
- ...triggerRest,
3070
- trigger_type: triggerType
3071
- };
3072
- }
3073
- if (messageType === "triggerregistrationresult" && "type" in message) {
3074
- const { type: triggerType, ...resultRest } = message;
3075
- return {
3076
- type: messageType,
3077
- ...resultRest,
3078
- trigger_type: triggerType
3079
- };
3080
- }
3081
3740
  return {
3082
3741
  type: messageType,
3083
3742
  ...rest
@@ -3151,23 +3810,60 @@ var Sdk = class {
3151
3810
  }
3152
3811
  async onInvokeFunction(invocation_id, function_id, input, metadata, traceparent, baggage, observeFields = {}) {
3153
3812
  const fn = this.functions.get(function_id);
3154
- const resolvedInput = this.resolveChannelValue(input);
3155
3813
  if (fn?.handler) {
3156
3814
  const handler = fn.handler;
3157
3815
  const ctx = {
3158
3816
  function_id,
3159
3817
  invocation_id: invocation_id ?? require_utils.randomUUID(),
3160
- observe_depth: observeFields.observe_depth ?? 0,
3161
- metadata
3818
+ observe_depth: observeFields.observe_depth ?? 0
3162
3819
  };
3163
3820
  if (observeFields.caller) ctx.caller = observeFields.caller;
3164
3821
  if (observeFields.activation) ctx.activation = observeFields.activation;
3165
3822
  if (traceparent !== void 0) ctx.traceparent = traceparent;
3166
3823
  if (baggage !== void 0) ctx.baggage = baggage;
3824
+ const snapshot = fn.observe.compiled;
3825
+ const activations = fn.observe.activations;
3826
+ const hook = this.functionHooks.get(function_id)?.deliver;
3827
+ const answering = this.engineFeatures.has(FEATURE_OBSERVE_V2);
3828
+ const startedAt = Date.now();
3829
+ const t0 = performance.now();
3830
+ let delivery;
3831
+ let matched;
3832
+ const resolvedInput = this.resolveChannelValue(input);
3167
3833
  const run = async () => {
3168
3834
  const untrack = trackRunning(ctx, MAX_RUNNING_INVOCATION_MS);
3169
3835
  try {
3170
- return await runInContext(ctx, () => handler(resolvedInput, metadata));
3836
+ let outcome;
3837
+ try {
3838
+ outcome = {
3839
+ ok: true,
3840
+ value: await runInContext(ctx, () => handler(resolvedInput, metadata))
3841
+ };
3842
+ } catch (error) {
3843
+ outcome = {
3844
+ ok: false,
3845
+ error
3846
+ };
3847
+ }
3848
+ const narrowed = answering && hook === void 0 && fn.observe.hasMatchHook();
3849
+ if (!answering || hook === void 0 && (!narrowed || snapshot.length === 0)) {
3850
+ if (narrowed) matched = [];
3851
+ if (outcome.ok) return outcome.value;
3852
+ throw outcome.error;
3853
+ }
3854
+ delivery = new Delivery(fn.observe, {
3855
+ call: this.callOf(function_id, ctx.invocation_id, outcome, input, ctx.caller, metadata),
3856
+ thrown: outcome.ok ? void 0 : outcome.error,
3857
+ snapshot,
3858
+ activations,
3859
+ started_at_ms: startedAt,
3860
+ duration_ms: performance.now() - t0,
3861
+ observe_depth: ctx.observe_depth,
3862
+ traceparent,
3863
+ baggage,
3864
+ routed: true
3865
+ });
3866
+ return await this.deliverIn(ctx, delivery, hook);
3171
3867
  } finally {
3172
3868
  untrack();
3173
3869
  }
@@ -3182,26 +3878,30 @@ var Sdk = class {
3182
3878
  }
3183
3879
  try {
3184
3880
  const result = await run();
3185
- this.sendMessage("invocationresult", {
3881
+ this.sendMessage("invocationresult", buildInvocationResult({
3186
3882
  invocation_id,
3187
3883
  function_id,
3188
3884
  result,
3189
3885
  traceparent,
3190
- baggage
3191
- });
3886
+ baggage,
3887
+ matched: delivery ? delivery.matched : matched,
3888
+ delivered: delivery?.delivered
3889
+ }));
3192
3890
  } catch (error) {
3193
- this.sendMessage("invocationresult", {
3891
+ this.sendMessage("invocationresult", buildInvocationResult({
3194
3892
  invocation_id,
3195
3893
  function_id,
3196
- error: handlerErrorBody(error),
3894
+ error: delivery ? delivery.errorBody(error) : handlerErrorBody(error),
3197
3895
  traceparent,
3198
- baggage
3199
- });
3896
+ baggage,
3897
+ matched: delivery ? delivery.matched : matched,
3898
+ delivered: delivery?.delivered
3899
+ }));
3200
3900
  }
3201
3901
  } else {
3202
3902
  const errorCode = fn ? "function_not_invokable" : "function_not_found";
3203
3903
  const errorMessage = fn ? "Function is HTTP-invoked and cannot be invoked locally" : "Function not found";
3204
- if (invocation_id) this.sendMessage("invocationresult", {
3904
+ if (invocation_id) this.sendMessage("invocationresult", buildInvocationResult({
3205
3905
  invocation_id,
3206
3906
  function_id,
3207
3907
  error: {
@@ -3210,62 +3910,7 @@ var Sdk = class {
3210
3910
  },
3211
3911
  traceparent,
3212
3912
  baggage
3213
- });
3214
- }
3215
- }
3216
- async onRegisterTrigger(message) {
3217
- const { trigger_type, id, function_id, config, namespace } = message;
3218
- const triggerTypeData = this.triggerTypes.get(trigger_type);
3219
- if (triggerTypeData) try {
3220
- await triggerTypeData.handler.registerTrigger({
3221
- id,
3222
- function_id,
3223
- config,
3224
- namespace
3225
- });
3226
- this.sendMessage("triggerregistrationresult", {
3227
- id,
3228
- message_type: "triggerregistrationresult",
3229
- type: trigger_type,
3230
- function_id
3231
- });
3232
- } catch (error) {
3233
- this.sendMessage("triggerregistrationresult", {
3234
- id,
3235
- message_type: "triggerregistrationresult",
3236
- type: trigger_type,
3237
- function_id,
3238
- error: {
3239
- code: "trigger_registration_failed",
3240
- message: error.message
3241
- }
3242
- });
3243
- }
3244
- else this.sendMessage("triggerregistrationresult", {
3245
- id,
3246
- message_type: "triggerregistrationresult",
3247
- type: trigger_type,
3248
- function_id,
3249
- error: {
3250
- code: "trigger_type_not_found",
3251
- message: "Trigger type not found"
3252
- }
3253
- });
3254
- }
3255
- async onUnregisterTrigger(message) {
3256
- const trigger_type = message.trigger_type;
3257
- if (!trigger_type) return;
3258
- const triggerTypeData = this.triggerTypes.get(trigger_type);
3259
- if (!triggerTypeData) return;
3260
- const { id, function_id = "", config } = message;
3261
- try {
3262
- await triggerTypeData.handler.unregisterTrigger({
3263
- id,
3264
- function_id,
3265
- config
3266
- });
3267
- } catch (error) {
3268
- console.error(`[iii] Error unregistering trigger ${id}`, error);
3913
+ }));
3269
3914
  }
3270
3915
  }
3271
3916
  onMessage(event) {
@@ -3292,23 +3937,23 @@ var Sdk = class {
3292
3937
  });
3293
3938
  } else if (msgType === "functionregistered") {
3294
3939
  const msg = decodeFunctionRegistered(message);
3295
- this.functions.get(msg.id)?.observe?.onFunctionRegistered(msg, this.connectionEpoch);
3940
+ const fn = this.functions.get(msg.id);
3941
+ if (fn && fn.sentEpoch === this.connectionEpoch) fn.observe.onFunctionRegistered(msg, this.connectionEpoch);
3296
3942
  } else if (msgType === "observeradded") {
3297
3943
  const msg = decodeObserverAdded(message);
3298
- this.functions.get(msg.function_id)?.observe?.onObserverAdded(msg);
3944
+ const fn = this.functions.get(msg.function_id);
3945
+ if (fn && fn.sentEpoch === this.connectionEpoch) fn.observe.onObserverAdded(msg);
3299
3946
  } else if (msgType === "observerremoved") {
3300
3947
  const msg = decodeObserverRemoved(message);
3301
- this.functions.get(msg.function_id)?.observe?.onObserverRemoved(msg);
3948
+ this.functions.get(msg.function_id)?.observe.onObserverRemoved(msg);
3302
3949
  } else if (msgType === "observeresult") {
3303
3950
  const msg = decodeObserveResult(message);
3304
- if (msg.warnings && msg.warnings.length > 0) console.warn(`[iii] Observer ${msg.id}: ${msg.warnings.join("; ")}`);
3305
- this.onObserverState(msg.id, msg.state, msg.error);
3951
+ if (msg.warnings && msg.warnings.length > 0) this.logWarn(`Observer ${msg.id}: ${msg.warnings.join("; ")}`);
3952
+ this.onObserveResult(msg.id, msg.state, msg.error);
3306
3953
  } else if (msgType === "observerstatechanged") {
3307
3954
  const msg = decodeObserverStateChanged(message);
3308
- this.onObserverState(msg.id, msg.state, msg.reason);
3309
- } else if (msgType === "registertrigger") this.onRegisterTrigger(message);
3310
- else if (msgType === "unregistertrigger") this.onUnregisterTrigger(message);
3311
- else if (msgType === "registrationrejected") this.onRegistrationRejected(message);
3955
+ this.onObserverStateChanged(msg.id, msg.state, msg.reason);
3956
+ } else if (msgType === "registrationrejected") this.onRegistrationRejected(decodeRegistrationRejected(message));
3312
3957
  else if (msgType === "workerregistered") {
3313
3958
  const { worker_id, reattach_token, features } = decodeWorkerRegistered(message);
3314
3959
  this.workerId = worker_id;
@@ -3317,51 +3962,112 @@ var Sdk = class {
3317
3962
  }
3318
3963
  }
3319
3964
  /**
3320
- * `WorkerRegistered` told this connection what the engine supports. With
3321
- * `observe.v1` the observers are replayed (after the functions, sent on
3322
- * open) and held reports flushed; without it `observe()` fails with
3323
- * `UNSUPPORTED` and observe hooks are inactive.
3965
+ * `WorkerRegistered` told this connection what the engine supports. The
3966
+ * functions that need `observe.v2` go out now, or stay unregistered without
3967
+ * it; without it, one sent earlier on this connection that has gained a
3968
+ * match or deliver hook since is unregistered. With `observe.v1` the observers the
3969
+ * engine has not refused are replayed (after the functions) and held reports flushed; without it
3970
+ * `observe()` fails with `UNSUPPORTED` and observer hooks are inactive.
3324
3971
  */
3325
3972
  onEngineFeatures(features) {
3326
3973
  this.engineFeatures = new Set(features);
3327
3974
  this.registeredOnConnection = true;
3975
+ this.sendRegistrations();
3976
+ for (const [functionId, fn] of this.functions) if (fn.sentEpoch === this.connectionEpoch) this.reconcileRegistration(functionId);
3977
+ this.warnUnregisteredHookIds();
3328
3978
  const queued = this.observeQueue;
3329
3979
  this.observeQueue = [];
3330
3980
  if (this.engineFeatures.has("observe.v1")) {
3331
3981
  for (const frame of queued) this.sendMessageRaw(JSON.stringify(frame));
3332
- for (const handle of this.observers.values()) this.sendObserve(handle);
3982
+ for (const handle of this.observerHandles.values()) if (!handle.refused) this.sendObserve(handle);
3333
3983
  this.reporter.flush();
3334
3984
  return;
3335
3985
  }
3336
- for (const handle of this.observers.values()) handle.setState("error", UNSUPPORTED_REASON);
3337
- for (const [functionId, fn] of this.functions) if (fn.observe?.needsObserve) this.warnHooksInactive(functionId);
3986
+ for (const handle of this.observerHandles.values()) if (!handle.refused) handle.setState("error", UNSUPPORTED_REASON);
3987
+ for (const functionId of this.functions.keys()) if (this.hasObserverHooks(functionId)) this.warnHooksInactive(functionId);
3338
3988
  this.reporter.clear();
3339
3989
  }
3340
- onObserverState(id, wireState, reason) {
3341
- const handle = this.observers.get(id);
3990
+ /**
3991
+ * An `observeresult`: the answer to the oldest `observe` of the id sent on
3992
+ * this connection that has none yet. The engine answers every `observe`
3993
+ * once, in the order it read them (decision 56).
3994
+ */
3995
+ onObserveResult(id, wireState, reason) {
3996
+ const handle = this.observesSent.get(id)?.find((h) => !h.answered);
3342
3997
  if (!handle) return;
3998
+ handle.answered = true;
3999
+ if (toObserverState(wireState) === "error") {
4000
+ handle.sent = false;
4001
+ handle.refused = true;
4002
+ this.unlistObserve(handle);
4003
+ handle.setState("error", reason ? {
4004
+ code: reason.code,
4005
+ message: reason.message
4006
+ } : void 0);
4007
+ return;
4008
+ }
4009
+ if (handle.state === "disposed") this.unlistObserve(handle);
4010
+ else this.applyObserverState(handle, wireState, reason);
4011
+ }
4012
+ /**
4013
+ * An `observerstatechanged`: about the newest observer of the id whose
4014
+ * `observeresult` arrived on this connection. One that arrives before any
4015
+ * did is dropped: a reattached connection hears its observers resume
4016
+ * before its replayed `observe`s are answered, and each answer carries the
4017
+ * current state (decision 56).
4018
+ */
4019
+ onObserverStateChanged(id, wireState, reason) {
4020
+ const sent = this.observesSent.get(id);
4021
+ if (!sent) return;
4022
+ for (let at = sent.length - 1; at >= 0; at--) if (sent[at].answered) {
4023
+ this.applyObserverState(sent[at], wireState, reason);
4024
+ return;
4025
+ }
4026
+ }
4027
+ /** A state from the engine for `handle`; `disposed` frees its id. */
4028
+ applyObserverState(handle, wireState, reason) {
3343
4029
  const state = toObserverState(wireState);
3344
4030
  handle.setState(state, reason ? {
3345
4031
  code: reason.code,
3346
4032
  message: reason.message
3347
4033
  } : void 0);
3348
- if (state === "disposed") this.observers.delete(id);
4034
+ if (state !== "disposed") return;
4035
+ this.unlistObserve(handle);
4036
+ if (this.observerHandles.get(handle.id) === handle) this.observerHandles.delete(handle.id);
4037
+ }
4038
+ unlistObserve(handle) {
4039
+ const sent = this.observesSent.get(handle.id);
4040
+ const at = sent ? sent.indexOf(handle) : -1;
4041
+ if (!sent || at < 0) return;
4042
+ sent.splice(at, 1);
4043
+ if (sent.length === 0) this.observesSent.delete(handle.id);
3349
4044
  }
3350
4045
  /**
3351
- * The engine rejected a registration. A `FUNCTION_NAMESPACE_CONFLICT` costs
3352
- * one function and leaves the connection open, so log and keep serving. A
3353
- * `WORKER_NAMESPACE_CONFLICT` means another live worker owns this name in the
3354
- * namespace: it is terminal — stop and do not reconnect (otherwise the engine
3355
- * would only reject the same name again, which with `maxRetries: -1` loops
3356
- * forever).
4046
+ * The engine rejected a registration. The `code` decides the severity:
4047
+ *
4048
+ * - {@link FUNCTION_NAMESPACE_CONFLICT}: another live worker in this
4049
+ * namespace already exports this one function id. Only that registration
4050
+ * is refused; the connection stays open and the worker keeps serving its
4051
+ * other functions.
4052
+ * - {@link FUNCTION_REJECTIONS} on one function: only that function is
4053
+ * refused. Logged; the worker keeps serving.
4054
+ * - {@link WORKER_NAMESPACE_CONFLICT}, or any other code: terminal — stop and
4055
+ * do not reconnect (otherwise the engine would only reject the same name
4056
+ * again, which with `maxRetries: -1` loops forever).
3357
4057
  */
3358
4058
  onRegistrationRejected(init) {
3359
- if (init.code === "FUNCTION_NAMESPACE_CONFLICT") {
3360
- if (init.function_id !== void 0) this.functions.get(init.function_id)?.observe?.onRegistrationRejected(this.connectionEpoch);
3361
- console.warn(`[iii] Function registration rejected: function "${init.function_id ?? "<unknown>"}" in namespace "${init.namespace}" is already exported by worker ${init.owner_worker_id}. Staying connected and serving the rest.`);
4059
+ if (init.code === FUNCTION_NAMESPACE_CONFLICT) {
4060
+ (init.function_id !== void 0 ? this.functions.get(init.function_id) : void 0)?.observe.onRegistrationRejected(this.connectionEpoch);
4061
+ this.logWarn(`Function registration rejected: function "${init.function_id ?? "<unknown>"}" in namespace "${init.namespace}" is already exported by worker ${init.owner_worker_id}. Staying connected and serving the rest.`);
4062
+ return;
4063
+ }
4064
+ if (FUNCTION_REJECTIONS.has(init.code) && init.function_id !== void 0) {
4065
+ this.functions.get(init.function_id)?.observe.onRegistrationRejected(this.connectionEpoch);
4066
+ this.logError(`Function registration rejected with ${init.code}: function "${init.function_id}" in namespace "${init.namespace}" is not registered. Staying connected and serving the rest.`);
3362
4067
  return;
3363
4068
  }
3364
- console.error(`[iii] Registration rejected (${init.code}): worker "${init.worker_name}" in namespace "${init.namespace}" is already owned by ${init.owner_worker_id}. Not reconnecting.`);
4069
+ if (init.code === WORKER_NAMESPACE_CONFLICT) this.logError(`Registration rejected (${init.code}): worker "${init.worker_name}" in namespace "${init.namespace}" is already owned by ${init.owner_worker_id}. Not reconnecting.`);
4070
+ else this.logError(`Registration rejected by engine with unknown code "${init.code}"; treating as fatal. Not reconnecting.`);
3365
4071
  this.isShuttingDown = true;
3366
4072
  this.clearReconnectTimeout();
3367
4073
  const error = new RegistrationRejectedError(init);
@@ -3376,28 +4082,28 @@ var Sdk = class {
3376
4082
  }
3377
4083
  };
3378
4084
  /**
3379
- * Factory object that constructs routing actions for {@link ISdk.trigger}.
4085
+ * Factory object that constructs routing actions for {@link ISdk.call}.
3380
4086
  *
3381
4087
  * @example
3382
4088
  * ```typescript
3383
- * import { TriggerAction } from 'iii-browser-sdk'
4089
+ * import { CallAction } from 'iii-browser-sdk'
3384
4090
  *
3385
4091
  * // Enqueue to a named queue
3386
- * worker.trigger({
4092
+ * worker.call({
3387
4093
  * function_id: 'process',
3388
4094
  * payload: { data: 'hello' },
3389
- * action: TriggerAction.Enqueue({ queue: 'jobs' }),
4095
+ * action: CallAction.Enqueue({ queue: 'jobs' }),
3390
4096
  * })
3391
4097
  *
3392
4098
  * // Fire-and-forget
3393
- * worker.trigger({
4099
+ * worker.call({
3394
4100
  * function_id: 'notify',
3395
4101
  * payload: {},
3396
- * action: TriggerAction.Void(),
4102
+ * action: CallAction.Void(),
3397
4103
  * })
3398
4104
  * ```
3399
4105
  */
3400
- const TriggerAction = {
4106
+ const CallAction = {
3401
4107
  /**
3402
4108
  * Routes the invocation through a named queue. The engine enqueues the job,
3403
4109
  * acknowledges the caller with `{ messageReceiptId }`, and processes it
@@ -3416,6 +4122,8 @@ const TriggerAction = {
3416
4122
  */
3417
4123
  Void: () => ({ type: "void" })
3418
4124
  };
4125
+ /** @deprecated Use {@link CallAction}, the same object. */
4126
+ const TriggerAction = CallAction;
3419
4127
  /**
3420
4128
  * Register the worker with a iii instance, returns a connected worker client.
3421
4129
  * The WebSocket connection is established automatically.
@@ -3434,10 +4142,11 @@ const TriggerAction = {
3434
4142
  const registerWorker = (address, options) => new Sdk(address, options);
3435
4143
 
3436
4144
  //#endregion
4145
+ exports.CallAction = CallAction;
3437
4146
  exports.ChannelReader = require_utils.ChannelReader;
3438
4147
  exports.ChannelWriter = require_utils.ChannelWriter;
3439
4148
  exports.EngineFunctions = EngineFunctions;
3440
- exports.EngineTriggers = EngineTriggers;
4149
+ exports.EngineSources = EngineSources;
3441
4150
  exports.InvocationError = InvocationError;
3442
4151
  exports.ObserveRejection = ObserveRejection;
3443
4152
  exports.RegistrationRejectedError = RegistrationRejectedError;