@milaboratories/pl-tree 1.6.8 → 1.6.10

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.mjs CHANGED
@@ -1,10 +1,10 @@
1
1
  var M = Object.defineProperty;
2
2
  var U = (n, e, t) => e in n ? M(n, e, { enumerable: !0, configurable: !0, writable: !0, value: t }) : n[e] = t;
3
3
  var d = (n, e, t) => U(n, typeof e != "symbol" ? e + "" : e, t);
4
- import { resourceIdToString as S, resourceTypesEqual as A, resourceTypeToString as J, isNotNullResourceId as g, NullResourceId as T, isNullResourceId as V, stringifyWithResourceId as D, isTimeoutOrCancelError as q } from "@milaboratories/pl-client";
4
+ import { resourceIdToString as S, resourceTypesEqual as A, resourceTypeToString as J, isNotNullResourceId as g, NullResourceId as F, isNullResourceId as V, stringifyWithResourceId as L, isTimeoutOrCancelError as q } from "@milaboratories/pl-client";
5
5
  import { ChangeSource as m, PollingComputableHooks as z } from "@milaboratories/computable";
6
6
  import { parsePlError as P } from "@milaboratories/pl-errors";
7
- import { notEmpty as p, cachedDeserialize as $, msToHumanReadable as H } from "@milaboratories/ts-helpers";
7
+ import { notEmpty as p, cachedDecode as $, cachedDeserialize as b, msToHumanReadable as H } from "@milaboratories/ts-helpers";
8
8
  import j from "denque";
9
9
  import * as Y from "node:timers/promises";
10
10
  function ne(n, e) {
@@ -47,29 +47,29 @@ class C {
47
47
  return `[ENTRY:${S(this.rid)}]`;
48
48
  }
49
49
  }
50
- function K(n, e, t, r, s) {
50
+ function K(n, e, t, r, a) {
51
51
  const o = new G(
52
52
  n,
53
53
  e,
54
54
  e.get(t.ctx.watcher, r),
55
55
  t
56
56
  );
57
- if (!s.ignoreError) {
58
- const a = o.getError();
59
- if (a !== void 0)
60
- throw P(p(a.getDataAsString()), o.id, o.resourceType);
57
+ if (!a.ignoreError) {
58
+ const s = o.getError();
59
+ if (s !== void 0)
60
+ throw P(p(s.getDataAsString()), o.id, o.resourceType);
61
61
  }
62
- if (s.assertResourceType !== void 0 && (Array.isArray(s.assertResourceType) ? s.assertResourceType.findIndex((a) => A(a, o.resourceType)) === -1 : !A(s.assertResourceType, o.resourceType)))
62
+ if (a.assertResourceType !== void 0 && (Array.isArray(a.assertResourceType) ? a.assertResourceType.findIndex((s) => A(s, o.resourceType)) === -1 : !A(a.assertResourceType, o.resourceType)))
63
63
  throw new Error(
64
64
  // eslint-disable-next-line @typescript-eslint/no-base-to-string
65
- `wrong resource type ${J(o.resourceType)} but expected ${s.assertResourceType}`
65
+ `wrong resource type ${J(o.resourceType)} but expected ${a.assertResourceType}`
66
66
  );
67
67
  return o;
68
68
  }
69
69
  class E {
70
- constructor(e, t, r, s) {
70
+ constructor(e, t, r, a) {
71
71
  d(this, "__pl_tree_type_marker__", "PlTreeEntryAccessor");
72
- this.accessorData = e, this.tree = t, this.rid = r, this.instanceData = s;
72
+ this.accessorData = e, this.tree = t, this.rid = r, this.instanceData = a;
73
73
  }
74
74
  node(e = {}) {
75
75
  return this.instanceData.guard(), this.accessorData.hooks !== void 0 && this.instanceData.ctx.attacheHooks(this.accessorData.hooks), K(this.accessorData, this.tree, this.instanceData, this.rid, e);
@@ -79,12 +79,12 @@ function he(n, e) {
79
79
  return n instanceof C ? e.accessor(n).node().resourceInfo : n;
80
80
  }
81
81
  class G {
82
- constructor(e, t, r, s) {
82
+ constructor(e, t, r, a) {
83
83
  d(this, "__pl_tree_type_marker__", "PlTreeNodeAccessor");
84
84
  d(this, "onUnstableLambda", (e) => {
85
85
  this.instanceData.ctx.markUnstable(e);
86
86
  });
87
- this.accessorData = e, this.tree = t, this.resource = r, this.instanceData = s;
87
+ this.accessorData = e, this.tree = t, this.resource = r, this.instanceData = a;
88
88
  }
89
89
  get id() {
90
90
  return this.instanceData.guard(), this.resource.id;
@@ -116,25 +116,25 @@ class G {
116
116
  }
117
117
  traverseOrErrorWithCommon(e, ...t) {
118
118
  let r = this;
119
- for (const s of t) {
120
- const o = typeof s == "string" ? {
119
+ for (const a of t) {
120
+ const o = typeof a == "string" ? {
121
121
  ...e,
122
- field: s
123
- } : { ...e, ...s }, a = r.getField(s);
124
- if (a === void 0 || o.pureFieldErrorToUndefined && a.value === void 0 && a.error !== void 0)
122
+ field: a
123
+ } : { ...e, ...a }, s = r.getField(a);
124
+ if (s === void 0 || o.pureFieldErrorToUndefined && s.value === void 0 && s.error !== void 0)
125
125
  return;
126
- if ((!o.ignoreError || a.value === void 0) && a.error !== void 0)
126
+ if ((!o.ignoreError || s.value === void 0) && s.error !== void 0)
127
127
  return {
128
128
  ok: !1,
129
129
  // FIXME: in next tickets we'll allow Errors to be thrown.
130
130
  error: P(
131
- p(a.error.getDataAsString()),
131
+ p(s.error.getDataAsString()),
132
132
  r.id,
133
133
  r.resourceType,
134
134
  o.field
135
135
  )
136
136
  };
137
- if (a.value === void 0) {
137
+ if (s.value === void 0) {
138
138
  if (o.errorIfFieldNotSet)
139
139
  return {
140
140
  ok: !1,
@@ -143,7 +143,7 @@ class G {
143
143
  this.onUnstableLambda("unpopulated_field:" + o.field);
144
144
  return;
145
145
  }
146
- r = a.value;
146
+ r = s.value;
147
147
  }
148
148
  return { ok: !0, value: r };
149
149
  }
@@ -151,7 +151,7 @@ class G {
151
151
  this.instanceData.guard();
152
152
  const t = typeof e == "string" ? { field: e } : e, r = this.resource.getField(this.instanceData.ctx.watcher, t, this.onUnstableLambda);
153
153
  if (r !== void 0)
154
- return N(r, (s) => this.getResourceFromTree(s, { ignoreError: !0 }));
154
+ return N(r, (a) => this.getResourceFromTree(a, { ignoreError: !0 }));
155
155
  }
156
156
  getInputsLocked() {
157
157
  this.instanceData.guard();
@@ -235,9 +235,9 @@ class R extends Error {
235
235
  }
236
236
  }
237
237
  class x {
238
- constructor(e, t, r, s, o, a, i) {
238
+ constructor(e, t, r, a, o, s, i) {
239
239
  d(this, "change", new m());
240
- this.name = e, this.type = t, this.value = r, this.error = s, this.status = o, this.valueIsFinal = a, this.resourceVersion = i;
240
+ this.name = e, this.type = t, this.value = r, this.error = a, this.status = o, this.valueIsFinal = s, this.resourceVersion = i;
241
241
  }
242
242
  get state() {
243
243
  return {
@@ -250,15 +250,15 @@ class x {
250
250
  };
251
251
  }
252
252
  }
253
- const L = 0, b = new TextDecoder();
253
+ const T = 0;
254
254
  class Q {
255
255
  constructor(e, t) {
256
256
  /** Tracks number of other resources referencing this resource. Used to perform garbage collection in tree patching procedure */
257
257
  d(this, "refCount", 0);
258
258
  /** Increments each time resource is checked for difference with new state */
259
- d(this, "version", L);
259
+ d(this, "version", T);
260
260
  /** Set to resource version when resource state, or it's fields have changed */
261
- d(this, "dataVersion", L);
261
+ d(this, "dataVersion", T);
262
262
  d(this, "fieldsMap", /* @__PURE__ */ new Map());
263
263
  d(this, "kv", /* @__PURE__ */ new Map());
264
264
  d(this, "resourceRemoved", new m());
@@ -305,34 +305,34 @@ class Q {
305
305
  }
306
306
  getField(e, t, r = () => {
307
307
  }) {
308
- var a, i, f;
309
- const s = typeof t == "string" ? { field: t } : t, o = this.fieldsMap.get(s.field);
308
+ var s, i, f;
309
+ const a = typeof t == "string" ? { field: t } : t, o = this.fieldsMap.get(a.field);
310
310
  if (o === void 0) {
311
- if (s.errorIfFieldNotFound || s.errorIfFieldNotSet)
311
+ if (a.errorIfFieldNotFound || a.errorIfFieldNotSet)
312
312
  throw new Error(
313
- `Field "${s.field}" not found in resource ${S(this.id)}`
313
+ `Field "${a.field}" not found in resource ${S(this.id)}`
314
314
  );
315
- if (!this.inputsLocked) (a = this.inputAndServiceFieldListChanged) == null || a.attachWatcher(e);
316
- else if (s.assertFieldType === "Service" || s.assertFieldType === "Input") {
317
- if (s.allowPermanentAbsence)
315
+ if (!this.inputsLocked) (s = this.inputAndServiceFieldListChanged) == null || s.attachWatcher(e);
316
+ else if (a.assertFieldType === "Service" || a.assertFieldType === "Input") {
317
+ if (a.allowPermanentAbsence)
318
318
  return;
319
- throw new Error(`Service or input field not found ${s.field}.`);
319
+ throw new Error(`Service or input field not found ${a.field}.`);
320
320
  }
321
321
  if (!this.outputsLocked) (i = this.outputFieldListChanged) == null || i.attachWatcher(e);
322
- else if (s.assertFieldType === "Output") {
323
- if (s.allowPermanentAbsence)
322
+ else if (a.assertFieldType === "Output") {
323
+ if (a.allowPermanentAbsence)
324
324
  return;
325
- throw new Error(`Output field not found ${s.field}.`);
325
+ throw new Error(`Output field not found ${a.field}.`);
326
326
  }
327
- (f = this.dynamicFieldListChanged) == null || f.attachWatcher(e), !this._finalState && !s.stableIfNotFound && r("field_not_found:" + s.field);
327
+ (f = this.dynamicFieldListChanged) == null || f.attachWatcher(e), !this._finalState && !a.stableIfNotFound && r("field_not_found:" + a.field);
328
328
  return;
329
329
  } else {
330
- if (s.assertFieldType !== void 0 && o.type !== s.assertFieldType)
330
+ if (a.assertFieldType !== void 0 && o.type !== a.assertFieldType)
331
331
  throw new Error(
332
- `Unexpected field type: expected ${s.assertFieldType} but got ${o.type} for the field name ${s.field}`
332
+ `Unexpected field type: expected ${a.assertFieldType} but got ${o.type} for the field name ${a.field}`
333
333
  );
334
334
  const l = {};
335
- return g(o.value) && (l.value = o.value), g(o.error) && (l.error = o.error), l.value === void 0 && l.error === void 0 && r("field_not_resolved:" + s.field), o.change.attachWatcher(e), l;
335
+ return g(o.value) && (l.value = o.value), g(o.error) && (l.error = o.error), l.value === void 0 && l.error === void 0 && r("field_not_resolved:" + a.field), o.change.attachWatcher(e), l;
336
336
  }
337
337
  }
338
338
  getInputsLocked(e) {
@@ -344,7 +344,7 @@ class Q {
344
344
  return this.outputsLocked || (t = this.resourceStateChange) == null || t.attachWatcher(e), this.outputsLocked;
345
345
  }
346
346
  get isReadyOrError() {
347
- return this.error !== T || this.resourceReady || this.originalResourceId !== T;
347
+ return this.error !== F || this.resourceReady || this.originalResourceId !== F;
348
348
  }
349
349
  getIsFinal(e) {
350
350
  var t;
@@ -365,22 +365,22 @@ class Q {
365
365
  listInputFields(e) {
366
366
  var r;
367
367
  const t = [];
368
- return this.fieldsMap.forEach((s, o) => {
369
- (s.type === "Input" || s.type === "Service") && t.push(o);
368
+ return this.fieldsMap.forEach((a, o) => {
369
+ (a.type === "Input" || a.type === "Service") && t.push(o);
370
370
  }), this.inputsLocked || (r = this.inputAndServiceFieldListChanged) == null || r.attachWatcher(e), t;
371
371
  }
372
372
  listOutputFields(e) {
373
373
  var r;
374
374
  const t = [];
375
- return this.fieldsMap.forEach((s, o) => {
376
- s.type === "Output" && t.push(o);
375
+ return this.fieldsMap.forEach((a, o) => {
376
+ a.type === "Output" && t.push(o);
377
377
  }), this.outputsLocked || (r = this.outputFieldListChanged) == null || r.attachWatcher(e), t;
378
378
  }
379
379
  listDynamicFields(e) {
380
380
  var r;
381
381
  const t = [];
382
- return this.fieldsMap.forEach((s, o) => {
383
- s.type !== "Input" && s.type !== "Output" && t.push(o);
382
+ return this.fieldsMap.forEach((a, o) => {
383
+ a.type !== "Input" && a.type !== "Output" && t.push(o);
384
384
  }), (r = this.dynamicFieldListChanged) == null || r.attachWatcher(e), t;
385
385
  }
386
386
  getKeyValue(e, t) {
@@ -390,24 +390,24 @@ class Q {
390
390
  getKeyValueString(e, t) {
391
391
  const r = this.getKeyValue(e, t);
392
392
  if (r !== void 0)
393
- return b.decode(r);
393
+ return $(r);
394
394
  }
395
395
  getKeyValueAsJson(e, t) {
396
396
  const r = this.getKeyValue(e, t);
397
397
  if (r !== void 0)
398
- return $(r);
398
+ return b(r);
399
399
  }
400
400
  getDataAsString() {
401
401
  if (this.data !== void 0)
402
- return this.dataAsString === void 0 && (this.dataAsString = b.decode(this.data)), this.dataAsString;
402
+ return this.dataAsString === void 0 && (this.dataAsString = $(this.data)), this.dataAsString;
403
403
  }
404
404
  getDataAsJson() {
405
405
  if (this.data !== void 0)
406
- return this.dataAsJson === void 0 && (this.dataAsJson = $(this.data)), this.dataAsJson;
406
+ return this.dataAsJson === void 0 && (this.dataAsJson = b(this.data)), this.dataAsJson;
407
407
  }
408
408
  verifyReadyState() {
409
409
  if (this.resourceReady && !this.inputsLocked)
410
- throw new Error(`ready without input or output lock: ${D(this.basicState)}`);
410
+ throw new Error(`ready without input or output lock: ${L(this.basicState)}`);
411
411
  }
412
412
  get basicState() {
413
413
  return {
@@ -436,8 +436,8 @@ class Q {
436
436
  }
437
437
  /** Used for invalidation */
438
438
  markAllChanged() {
439
- var e, t, r, s, o, a, i;
440
- this.fieldsMap.forEach((f) => f.change.markChanged()), (e = this.finalChanged) == null || e.markChanged(), (t = this.resourceStateChange) == null || t.markChanged(), (r = this.lockedChange) == null || r.markChanged(), (s = this.inputAndServiceFieldListChanged) == null || s.markChanged(), (o = this.outputFieldListChanged) == null || o.markChanged(), (a = this.dynamicFieldListChanged) == null || a.markChanged(), (i = this.kvChanged) == null || i.markChanged(), this.resourceRemoved.markChanged();
439
+ var e, t, r, a, o, s, i;
440
+ this.fieldsMap.forEach((f) => f.change.markChanged()), (e = this.finalChanged) == null || e.markChanged(), (t = this.resourceStateChange) == null || t.markChanged(), (r = this.lockedChange) == null || r.markChanged(), (a = this.inputAndServiceFieldListChanged) == null || a.markChanged(), (o = this.outputFieldListChanged) == null || o.markChanged(), (s = this.dynamicFieldListChanged) == null || s.markChanged(), (i = this.kvChanged) == null || i.markChanged(), this.resourceRemoved.markChanged();
441
441
  }
442
442
  }
443
443
  class O {
@@ -466,28 +466,28 @@ class O {
466
466
  }
467
467
  updateFromResourceData(e, t = !1) {
468
468
  this.checkValid();
469
- const r = [], s = [];
470
- for (const a of e) {
471
- let i = this.resources.get(a.id);
469
+ const r = [], a = [];
470
+ for (const s of e) {
471
+ let i = this.resources.get(s.id);
472
472
  const f = i == null ? void 0 : i.basicState, l = (h) => {
473
- const { fields: k, ...u } = a;
473
+ const { fields: k, ...u } = s;
474
474
  throw this.invalidateTree(), new R(
475
- `Unexpected resource state transition (${h}): ${D(
475
+ `Unexpected resource state transition (${h}): ${L(
476
476
  u
477
- )} -> ${D(f)}`
477
+ )} -> ${L(f)}`
478
478
  );
479
479
  };
480
480
  if (i !== void 0) {
481
481
  i.finalState && l("resource state can be updated after it is marked as final");
482
482
  let h = !1;
483
- i.version += 1, i.originalResourceId !== a.originalResourceId && (i.originalResourceId !== T && l("originalResourceId can't change after it is set"), i.originalResourceId = a.originalResourceId, p(i.resourceStateChange).markChanged(), h = !0), i.error !== a.error && (g(i.error) && l("resource can't change attached error after it is set"), i.error = a.error, r.push(i.error), p(i.resourceStateChange).markChanged(), h = !0);
484
- for (const u of a.fields) {
483
+ i.version += 1, i.originalResourceId !== s.originalResourceId && (i.originalResourceId !== F && l("originalResourceId can't change after it is set"), i.originalResourceId = s.originalResourceId, p(i.resourceStateChange).markChanged(), h = !0), i.error !== s.error && (g(i.error) && l("resource can't change attached error after it is set"), i.error = s.error, r.push(i.error), p(i.resourceStateChange).markChanged(), h = !0);
484
+ for (const u of s.fields) {
485
485
  let c = i.fieldsMap.get(u.name);
486
486
  c ? (c.type !== u.type && (c.type !== "Dynamic" && l(`field changed type ${c.type} -> ${u.type}`), p(i.dynamicFieldListChanged).markChanged(), (c.type === "Input" || c.type === "Service") && (i.inputsLocked && l(
487
487
  `adding input field "${u.name}", while corresponding list is locked`
488
488
  ), p(i.inputAndServiceFieldListChanged).markChanged()), c.type === "Output" && (i.outputsLocked && l(
489
489
  `adding output field "${u.name}", while corresponding list is locked`
490
- ), p(i.outputFieldListChanged).markChanged()), c.type = u.type, c.change.markChanged(), h = !0), c.value !== u.value && (g(c.value) && s.push(c.value), c.value = u.value, g(u.value) && r.push(u.value), c.change.markChanged(), h = !0), c.error !== u.error && (g(c.error) && s.push(c.error), c.error = u.error, g(u.error) && r.push(u.error), c.change.markChanged(), h = !0), c.status !== u.status && (c.status = u.status, c.change.markChanged(), h = !0), c.valueIsFinal !== u.valueIsFinal && (c.valueIsFinal = u.valueIsFinal, c.change.markChanged(), h = !0), c.resourceVersion = i.version) : (c = new x(
490
+ ), p(i.outputFieldListChanged).markChanged()), c.type = u.type, c.change.markChanged(), h = !0), c.value !== u.value && (g(c.value) && a.push(c.value), c.value = u.value, g(u.value) && r.push(u.value), c.change.markChanged(), h = !0), c.error !== u.error && (g(c.error) && a.push(c.error), c.error = u.error, g(u.error) && r.push(u.error), c.change.markChanged(), h = !0), c.status !== u.status && (c.status = u.status, c.change.markChanged(), h = !0), c.valueIsFinal !== u.valueIsFinal && (c.valueIsFinal = u.valueIsFinal, c.change.markChanged(), h = !0), c.resourceVersion = i.version) : (c = new x(
491
491
  u.name,
492
492
  u.type,
493
493
  u.value,
@@ -502,28 +502,28 @@ class O {
502
502
  ), p(i.outputFieldListChanged).markChanged()) : p(i.dynamicFieldListChanged).markChanged(), i.fieldsMap.set(u.name, c), h = !0);
503
503
  }
504
504
  if (i.fieldsMap.forEach((u, c, v) => {
505
- u.resourceVersion !== i.version && ((u.type === "Input" || u.type === "Service" || u.type === "Output") && l(`removal of ${u.type} field ${c}`), u.change.markChanged(), v.delete(c), g(u.value) && s.push(u.value), g(u.error) && s.push(u.error), p(i.dynamicFieldListChanged).markChanged());
506
- }), i.inputsLocked !== a.inputsLocked && (i.inputsLocked && l("inputs unlocking is not permitted"), i.inputsLocked = a.inputsLocked, p(i.lockedChange).markChanged(), h = !0), i.outputsLocked !== a.outputsLocked && (i.outputsLocked && l("outputs unlocking is not permitted"), i.outputsLocked = a.outputsLocked, p(i.lockedChange).markChanged(), h = !0), i.resourceReady !== a.resourceReady) {
505
+ u.resourceVersion !== i.version && ((u.type === "Input" || u.type === "Service" || u.type === "Output") && l(`removal of ${u.type} field ${c}`), u.change.markChanged(), v.delete(c), g(u.value) && a.push(u.value), g(u.error) && a.push(u.error), p(i.dynamicFieldListChanged).markChanged());
506
+ }), i.inputsLocked !== s.inputsLocked && (i.inputsLocked && l("inputs unlocking is not permitted"), i.inputsLocked = s.inputsLocked, p(i.lockedChange).markChanged(), h = !0), i.outputsLocked !== s.outputsLocked && (i.outputsLocked && l("outputs unlocking is not permitted"), i.outputsLocked = s.outputsLocked, p(i.lockedChange).markChanged(), h = !0), i.resourceReady !== s.resourceReady) {
507
507
  const u = i.resourceReady;
508
- i.resourceReady = a.resourceReady, i.verifyReadyState(), i.isReadyOrError || l(
508
+ i.resourceReady = s.resourceReady, i.verifyReadyState(), i.isReadyOrError || l(
509
509
  `resource can't lose it's ready or error state (ready state before ${u})`
510
510
  ), p(i.resourceStateChange).markChanged(), h = !0;
511
511
  }
512
512
  let k = !1;
513
- for (const u of a.kv) {
513
+ for (const u of s.kv) {
514
514
  const c = i.kv.get(u.key);
515
515
  (c === void 0 || Buffer.compare(c, u.value) !== 0) && (i.kv.set(u.key, u.value), k = !0);
516
516
  }
517
- if (i.kv.size > a.kv.length) {
518
- const u = new Set(a.kv.map((c) => c.key));
517
+ if (i.kv.size > s.kv.length) {
518
+ const u = new Set(s.kv.map((c) => c.key));
519
519
  i.kv.forEach((c, v, y) => {
520
520
  u.has(v) || y.delete(v);
521
521
  }), k = !0;
522
522
  }
523
523
  k && p(i.kvChanged).markChanged(), h && (i.dataVersion = i.version, this.isFinalPredicate(i) && i.markFinal());
524
524
  } else {
525
- i = new Q(a), i.verifyReadyState(), g(i.error) && r.push(i.error);
526
- for (const h of a.fields) {
525
+ i = new Q(s), i.verifyReadyState(), g(i.error) && r.push(i.error);
526
+ for (const h of s.fields) {
527
527
  const k = new x(
528
528
  h.name,
529
529
  h.type,
@@ -531,37 +531,37 @@ class O {
531
531
  h.error,
532
532
  h.status,
533
533
  h.valueIsFinal,
534
- L
534
+ T
535
535
  );
536
536
  g(h.value) && r.push(h.value), g(h.error) && r.push(h.error), i.fieldsMap.set(h.name, k);
537
537
  }
538
- for (const h of a.kv) i.kv.set(h.key, h.value);
538
+ for (const h of s.kv) i.kv.set(h.key, h.value);
539
539
  this.isFinalPredicate(i) && i.markFinal(), this.resources.set(i.id, i), this.resourcesAdded.markChanged();
540
540
  }
541
541
  }
542
- for (const a of r) {
543
- const i = this.resources.get(a);
542
+ for (const s of r) {
543
+ const i = this.resources.get(s);
544
544
  if (!i)
545
- throw this.invalidateTree(), new R(`orphan resource ${a}`);
545
+ throw this.invalidateTree(), new R(`orphan resource ${s}`);
546
546
  i.refCount++;
547
547
  }
548
- let o = s;
548
+ let o = a;
549
549
  for (; o.length > 0; ) {
550
- const a = [];
550
+ const s = [];
551
551
  for (const i of o) {
552
552
  const f = this.resources.get(i);
553
553
  if (!f)
554
554
  throw this.invalidateTree(), new R(`orphan resource ${i}`);
555
555
  f.refCount--, f.refCount === 0 && f.id !== this.root && (f.fieldsMap.forEach((l) => {
556
- g(l.value) && a.push(l.value), g(l.error) && a.push(l.error), l.change.markChanged();
557
- }), g(f.error) && a.push(f.error), f.resourceRemoved.markChanged(), this.resources.delete(i));
556
+ g(l.value) && s.push(l.value), g(l.error) && s.push(l.error), l.change.markChanged();
557
+ }), g(f.error) && s.push(f.error), f.resourceRemoved.markChanged(), this.resources.delete(i));
558
558
  }
559
- o = a;
559
+ o = s;
560
560
  }
561
561
  if (!t) {
562
- for (const a of e)
563
- if (!this.resources.has(a.id))
564
- throw this.invalidateTree(), new R(`orphan input resource ${a.id}`);
562
+ for (const s of e)
563
+ if (!this.resources.has(s.id))
564
+ throw this.invalidateTree(), new R(`orphan input resource ${s.id}`);
565
565
  }
566
566
  }
567
567
  /** @deprecated use "entry" instead */
@@ -582,11 +582,11 @@ class O {
582
582
  }
583
583
  function X(n, e) {
584
584
  const t = [], r = /* @__PURE__ */ new Set();
585
- return n.forEachResource((s) => {
586
- s.finalState ? r.add(s.id) : t.push(s.id);
585
+ return n.forEachResource((a) => {
586
+ a.finalState ? r.add(a.id) : t.push(a.id);
587
587
  }), t.length === 0 && r.size === 0 && t.push(n.root), { seedResources: t, finalResources: r, pruningFunction: e };
588
588
  }
589
- function F() {
589
+ function D() {
590
590
  return {
591
591
  requests: 0,
592
592
  roundTrips: 0,
@@ -617,7 +617,7 @@ async function Z(n, e, t) {
617
617
  var c;
618
618
  const r = Date.now();
619
619
  t && t.requests++;
620
- const { seedResources: s, finalResources: o, pruningFunction: a } = e, i = new j();
620
+ const { seedResources: a, finalResources: o, pruningFunction: s } = e, i = new j();
621
621
  let f = !0, l = 0;
622
622
  const h = /* @__PURE__ */ new Set(), k = (v) => {
623
623
  if (V(v) || h.has(v)) return;
@@ -637,7 +637,7 @@ async function Z(n, e, t) {
637
637
  })()
638
638
  );
639
639
  };
640
- s.forEach((v) => k(v));
640
+ a.forEach((v) => k(v));
641
641
  const u = [];
642
642
  for (; ; ) {
643
643
  const v = i.shift();
@@ -645,8 +645,8 @@ async function Z(n, e, t) {
645
645
  break;
646
646
  let y = await v;
647
647
  if (y !== void 0) {
648
- if (a !== void 0) {
649
- const w = a(y);
648
+ if (s !== void 0) {
649
+ const w = s(y);
650
650
  t && (t.prunedFields += y.fields.length - w.length), y = { ...y, fields: w };
651
651
  }
652
652
  k(y.error);
@@ -665,16 +665,16 @@ function fe(n) {
665
665
  return n;
666
666
  }
667
667
  function ge(n, e, t) {
668
- var a;
668
+ var s;
669
669
  const r = n instanceof C ? p(t).accessor(n).node() : n instanceof E ? n.node() : n, o = { ...r.resourceInfo };
670
670
  if (e.data !== void 0 && (e.data === "raw" ? o.data = r.getData() : o.data = e.data.parse(r.getDataAsJson())), e.fields !== void 0) {
671
671
  const i = {};
672
672
  for (const [f, l] of Object.entries(e.fields))
673
- i[f] = (a = r.traverse({
673
+ i[f] = (s = r.traverse({
674
674
  field: f,
675
675
  errorIfFieldNotSet: l,
676
676
  stableIfNotFound: !l
677
- })) == null ? void 0 : a.id;
677
+ })) == null ? void 0 : s.id;
678
678
  o.fields = i;
679
679
  }
680
680
  if (e.kv !== void 0) {
@@ -691,15 +691,15 @@ function ge(n, e, t) {
691
691
  }
692
692
  function pe(n, e, t) {
693
693
  if (n instanceof C) {
694
- const r = t.accessor(n).node(), s = r.resourceInfo, o = e.map((a) => {
694
+ const r = t.accessor(n).node(), a = r.resourceInfo, o = e.map((s) => {
695
695
  var i, f;
696
696
  return [
697
- a,
698
- (f = (i = r.getField(a)) == null ? void 0 : i.value) == null ? void 0 : f.id
697
+ s,
698
+ (f = (i = r.getField(s)) == null ? void 0 : i.value) == null ? void 0 : f.id
699
699
  ];
700
700
  });
701
701
  return {
702
- ...s,
702
+ ...a,
703
703
  fields: new Map(o),
704
704
  data: r.getData() ?? new Uint8Array()
705
705
  };
@@ -708,14 +708,14 @@ function pe(n, e, t) {
708
708
  }
709
709
  function ve(n, e, t) {
710
710
  if (!(n instanceof C)) return n;
711
- const r = t.accessor(n).node(), s = r.resourceInfo, o = e.map((a) => [a, r.getKeyValue(a)]);
711
+ const r = t.accessor(n).node(), a = r.resourceInfo, o = e.map((s) => [s, r.getKeyValue(s)]);
712
712
  return {
713
- ...s,
713
+ ...a,
714
714
  metadata: Object.fromEntries(o)
715
715
  };
716
716
  }
717
717
  class B {
718
- constructor(e, t, r, s) {
718
+ constructor(e, t, r, a) {
719
719
  d(this, "finalPredicate");
720
720
  d(this, "state");
721
721
  d(this, "pollingInterval");
@@ -723,6 +723,7 @@ class B {
723
723
  d(this, "logStat");
724
724
  d(this, "hooks");
725
725
  d(this, "abortController", new AbortController());
726
+ d(this, "currentLoopDelayInterrupt");
726
727
  d(this, "scheduledOnNextState", []);
727
728
  /** If true, main loop will continue polling pl state. */
728
729
  d(this, "keepRunning", !1);
@@ -730,9 +731,9 @@ class B {
730
731
  d(this, "currentLoop");
731
732
  /** If true this tree state is permanently terminaed. */
732
733
  d(this, "terminated", !1);
733
- this.pl = e, this.root = t, this.logger = s;
734
- const { finalPredicateOverride: o, pruning: a, pollingInterval: i, stopPollingDelay: f, logStat: l } = r;
735
- this.pruning = a, this.pollingInterval = i, this.finalPredicate = o ?? e.finalPredicate, this.logStat = l, this.state = new O(t, this.finalPredicate), this.hooks = new z(
734
+ this.pl = e, this.root = t, this.logger = a;
735
+ const { finalPredicateOverride: o, pruning: s, pollingInterval: i, stopPollingDelay: f, logStat: l } = r;
736
+ this.pruning = s, this.pollingInterval = i, this.finalPredicate = o ?? e.finalPredicate, this.logStat = l, this.state = new O(t, this.finalPredicate), this.hooks = new z(
736
737
  () => this.startUpdating(),
737
738
  () => this.stopUpdating(),
738
739
  { stopDebounce: f },
@@ -754,8 +755,9 @@ class B {
754
755
  if (this.terminated) throw new Error("tree synchronization is terminated");
755
756
  await this.hooks.refreshState();
756
757
  }
758
+ /** Called from computable hooks when external observer asks for state refresh */
757
759
  scheduleOnNextState(e, t) {
758
- this.terminated ? t(new Error("tree synchronization is terminated")) : this.scheduledOnNextState.push({ resolve: e, reject: t });
760
+ this.terminated ? t(new Error("tree synchronization is terminated")) : (this.scheduledOnNextState.push({ resolve: e, reject: t }), this.currentLoopDelayInterrupt && (this.currentLoopDelayInterrupt.abort(), this.currentLoopDelayInterrupt = void 0));
759
761
  }
760
762
  /** Called from observer */
761
763
  startUpdating() {
@@ -768,31 +770,37 @@ class B {
768
770
  /** Executed from the main loop, and initialization procedure. */
769
771
  async refresh(e, t) {
770
772
  if (this.terminated) throw new Error("tree synchronization is terminated");
771
- const r = X(this.state, this.pruning), s = await this.pl.withReadTx("ReadingTree", async (o) => await Z(o, r, e), t);
772
- this.state.updateFromResourceData(s, !0);
773
+ const r = X(this.state, this.pruning), a = await this.pl.withReadTx("ReadingTree", async (o) => await Z(o, r, e), t);
774
+ this.state.updateFromResourceData(a, !0);
773
775
  }
774
776
  async mainLoop() {
775
- var t, r;
776
- let e = this.logStat ? F() : void 0;
777
- for (; this.keepRunning; ) {
778
- let s;
779
- this.scheduledOnNextState.length > 0 && (s = this.scheduledOnNextState, this.scheduledOnNextState = []);
777
+ var r, a;
778
+ let e = this.logStat ? D() : void 0, t = Date.now();
779
+ for (; !(!this.keepRunning || this.terminated); ) {
780
+ let o;
781
+ this.scheduledOnNextState.length > 0 && (o = this.scheduledOnNextState, this.scheduledOnNextState = []);
780
782
  try {
781
- if (this.logStat === "per-request" && (e = F()), await this.refresh(e), e && this.logger && this.logger.info(`Tree stat (success): ${JSON.stringify(e)}`), s !== void 0) for (const o of s) o.resolve();
782
- } catch (o) {
783
- if (e && this.logger && this.logger.info(`Tree stat (error): ${JSON.stringify(e)}`), s !== void 0) for (const a of s) a.reject(o);
784
- if (o instanceof R) {
785
- (t = this.logger) == null || t.error(o), this.state.invalidateTree("stat update error"), this.state = new O(this.root, this.finalPredicate);
783
+ if (this.logStat === "per-request" && (e = D()), await this.refresh(e), e && this.logger && this.logger.info(`Tree stat (success, after ${Date.now() - t}ms): ${JSON.stringify(e)}`), t = Date.now(), o !== void 0) for (const s of o) s.resolve();
784
+ } catch (s) {
785
+ if (e && this.logger && this.logger.info(`Tree stat (error, after ${Date.now() - t}ms): ${JSON.stringify(e)}`), t = Date.now(), o !== void 0) for (const i of o) i.reject(s);
786
+ if (s instanceof R) {
787
+ (r = this.logger) == null || r.error(s), this.state.invalidateTree("stat update error"), this.state = new O(this.root, this.finalPredicate);
786
788
  continue;
787
- } else (r = this.logger) == null || r.warn(o);
789
+ } else (a = this.logger) == null || a.warn(s);
788
790
  }
789
791
  if (!this.keepRunning || this.terminated) break;
790
- try {
791
- await Y.setTimeout(this.pollingInterval, this.abortController.signal);
792
- } catch (o) {
793
- if (!q(o)) throw new Error("Unexpected error", { cause: o });
794
- break;
795
- }
792
+ if (this.scheduledOnNextState.length === 0)
793
+ try {
794
+ this.currentLoopDelayInterrupt = new AbortController(), await Y.setTimeout(
795
+ this.pollingInterval,
796
+ AbortSignal.any([this.abortController.signal, this.currentLoopDelayInterrupt.signal])
797
+ );
798
+ } catch (s) {
799
+ if (!q(s)) throw new Error("Unexpected error", { cause: s });
800
+ break;
801
+ } finally {
802
+ this.currentLoopDelayInterrupt = void 0;
803
+ }
796
804
  }
797
805
  this.currentLoop = void 0;
798
806
  }
@@ -814,16 +822,16 @@ class B {
814
822
  async awaitSyncLoopTermination() {
815
823
  this.currentLoop !== void 0 && await this.currentLoop;
816
824
  }
817
- static async init(e, t, r, s) {
818
- const o = new B(e, t, r, s), a = r.logStat ? F() : void 0;
825
+ static async init(e, t, r, a) {
826
+ const o = new B(e, t, r, a), s = r.logStat ? D() : void 0;
819
827
  let i = !1;
820
828
  try {
821
- await o.refresh(a, {
829
+ await o.refresh(s, {
822
830
  timeout: r.initialTreeLoadingTimeout
823
831
  }), i = !0;
824
832
  } finally {
825
- a && s && s.info(
826
- `Tree stat (initial load, ${i ? "success" : "failure"}): ${JSON.stringify(a)}`
833
+ s && a && a.info(
834
+ `Tree stat (initial load, ${i ? "success" : "failure"}): ${JSON.stringify(s)}`
827
835
  );
828
836
  }
829
837
  return o;
@@ -843,8 +851,8 @@ function ye(n) {
843
851
  byResourceType: {}
844
852
  };
845
853
  for (const r of n) {
846
- const s = `${r.type.name}/${r.type.version}`;
847
- e.byResourceType[s] || (e.byResourceType[s] = {
854
+ const a = `${r.type.name}/${r.type.version}`;
855
+ e.byResourceType[a] || (e.byResourceType[a] = {
848
856
  count: 0,
849
857
  fieldNameBytes: 0,
850
858
  fieldsCount: 0,
@@ -852,17 +860,17 @@ function ye(n) {
852
860
  kvCount: 0,
853
861
  kvBytes: 0
854
862
  });
855
- const o = e.byResourceType[s];
863
+ const o = e.byResourceType[a];
856
864
  o.count++, e.total.count++;
857
- for (const a of r.fields)
858
- o.fieldNameBytes += a.name.length, o.fieldsCount++, e.total.fieldNameBytes += a.name.length, e.total.fieldsCount++;
865
+ for (const s of r.fields)
866
+ o.fieldNameBytes += s.name.length, o.fieldsCount++, e.total.fieldNameBytes += s.name.length, e.total.fieldsCount++;
859
867
  if (r.data) {
860
- const a = ((t = r.data) == null ? void 0 : t.length) ?? 0;
861
- o.dataBytes += a, e.total.dataBytes += a;
868
+ const s = ((t = r.data) == null ? void 0 : t.length) ?? 0;
869
+ o.dataBytes += s, e.total.dataBytes += s;
862
870
  }
863
871
  o.kvCount += r.kv.length, e.total.kvCount += r.kv.length;
864
- for (const a of r.kv) {
865
- const i = a.key.length + a.value.length;
872
+ for (const s of r.kv) {
873
+ const i = s.key.length + s.value.length;
866
874
  o.kvBytes += i, e.total.kvBytes += i;
867
875
  }
868
876
  }
@@ -879,7 +887,7 @@ export {
879
887
  R as TreeStateUpdateError,
880
888
  X as constructTreeLoadingRequest,
881
889
  le as formatTreeLoadingStat,
882
- F as initialTreeLoadingStat,
890
+ D as initialTreeLoadingStat,
883
891
  ue as isPlTreeEntry,
884
892
  de as isPlTreeEntryAccessor,
885
893
  ce as isPlTreeNodeAccessor,