teamplay 0.5.0-alpha.10 → 0.5.0-alpha.12

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.
@@ -3,15 +3,17 @@ import type {
3
3
  QuerySubscriptions,
4
4
  QuerySignalOptions
5
5
  } from './Query.js'
6
+ import type { PathSegment } from './types/path.js'
6
7
 
7
8
  export const IS_AGGREGATION: unique symbol
8
9
  export const AGGREGATIONS: '$aggregations'
9
10
  export const aggregationSubscriptions: QuerySubscriptions
10
11
  export function getAggregationSignal (collectionName: string, params: unknown, options?: QuerySignalOptions): Signal
11
12
  export function isAggregationSignal ($signal: unknown): boolean | undefined
13
+ export function getAggregationRowId (row: unknown, collectionName?: string): string | undefined
12
14
  export function getAggregationDocId (
13
- segments: readonly unknown[],
15
+ segments: readonly PathSegment[],
14
16
  rootId?: string,
15
- method?: (path: unknown[]) => unknown
17
+ method?: (path: PathSegment[]) => unknown
16
18
  ): string | undefined
17
- export function getAggregationCollectionName (segments: readonly unknown[]): string | undefined
19
+ export function getAggregationCollectionName (segments: readonly PathSegment[]): string | undefined
@@ -8,6 +8,7 @@ import { delPrivateData, getPrivateData, setPrivateData } from './privateData.js
8
8
  import { setSignalRuntimeDescriptor } from "./signalRuntimeDescriptor.js";
9
9
  export const IS_AGGREGATION = Symbol('is aggregation signal');
10
10
  export const AGGREGATIONS = '$aggregations';
11
+ const DEFAULT_AGGREGATION_ID_FIELDS = ['_id', 'id'];
11
12
  class Aggregation extends Query {
12
13
  _initData() {
13
14
  this._syncAllRootsData();
@@ -39,17 +40,27 @@ aggregationSubscriptions.runtimeKind = 'aggregation';
39
40
  function injectAggregationIds(extra, collectionName) {
40
41
  if (!Array.isArray(extra))
41
42
  return;
42
- const idFields = getIdFieldsForSegments([collectionName, '']);
43
+ const idFields = getCollectionIdFields(collectionName);
43
44
  for (const doc of extra) {
44
45
  if (!isPlainObject(doc))
45
46
  continue;
46
- const docId = doc._id ?? doc.id;
47
+ const docId = getAggregationRowId(doc, collectionName);
47
48
  if (docId == null)
48
49
  continue;
49
- if (idFields.includes('_id') && doc._id !== docId)
50
- doc._id = docId;
51
- if (idFields.includes('id') && doc.id !== docId)
52
- doc.id = docId;
50
+ for (const field of idFields) {
51
+ if (doc[field] !== docId)
52
+ doc[field] = docId;
53
+ }
54
+ }
55
+ }
56
+ export function getAggregationRowId(row, collectionName) {
57
+ if (!isPlainObject(row))
58
+ return;
59
+ const idFields = getAggregationIdFields(collectionName);
60
+ for (const field of idFields) {
61
+ const value = row[field];
62
+ if (typeof value === 'string')
63
+ return value;
53
64
  }
54
65
  }
55
66
  export function getAggregationSignal(collectionName, params, options) {
@@ -80,7 +91,7 @@ export function isAggregationSignal($signal) {
80
91
  return true;
81
92
  }
82
93
  // example: ['$aggregations', '{"active":true}', 42]
83
- // AND only if it also has either '_id' or 'id' field inside
94
+ // AND only if the aggregation row carries a source document id field
84
95
  export function getAggregationDocId(segments, rootId, method) {
85
96
  if (!(segments.length >= 3))
86
97
  return;
@@ -88,15 +99,16 @@ export function getAggregationDocId(segments, rootId, method) {
88
99
  return;
89
100
  if (!(typeof segments[2] === 'number'))
90
101
  return;
102
+ const collectionName = getAggregationCollectionName(segments);
103
+ const idFields = getAggregationIdFields(collectionName);
91
104
  if (typeof method !== 'function') {
92
105
  method = path => rootId == null ? getRaw(path) : getPrivateData(rootId, path);
93
106
  }
94
- const underscoreId = method([...segments.slice(0, 3), '_id']);
95
- if (typeof underscoreId === 'string')
96
- return underscoreId;
97
- const id = method([...segments.slice(0, 3), 'id']);
98
- if (typeof id === 'string')
99
- return id;
107
+ for (const field of idFields) {
108
+ const id = method([...segments.slice(0, 3), field]);
109
+ if (typeof id === 'string')
110
+ return id;
111
+ }
100
112
  }
101
113
  export function getAggregationCollectionName(segments) {
102
114
  if (!(segments.length >= 2))
@@ -117,3 +129,15 @@ function parseAggregationSignalOptions(options) {
117
129
  const { root, ...signalOptions } = options;
118
130
  return { root, signalOptions };
119
131
  }
132
+ function getAggregationIdFields(collectionName) {
133
+ const idFields = getCollectionIdFields(collectionName);
134
+ return uniq(idFields.concat(DEFAULT_AGGREGATION_ID_FIELDS));
135
+ }
136
+ function getCollectionIdFields(collectionName) {
137
+ return collectionName
138
+ ? getIdFieldsForSegments([collectionName, ''])
139
+ : [];
140
+ }
141
+ function uniq(values) {
142
+ return Array.from(new Set(values));
143
+ }
@@ -5,7 +5,7 @@ import { getRoot, ROOT, ROOT_ID, getRootSignal, GLOBAL_ROOT_ID, unregisterRootFi
5
5
  import { isPrivateMutationForbidden } from "../connection.js";
6
6
  import { docSubscriptions } from '../Doc.js';
7
7
  import { IS_QUERY, getQuerySignal, querySubscriptions } from '../Query.js';
8
- import { IS_AGGREGATION, aggregationSubscriptions, getAggregationSignal } from '../Aggregation.js';
8
+ import { AGGREGATIONS, IS_AGGREGATION, aggregationSubscriptions, getAggregationSignal } from '../Aggregation.js';
9
9
  import { getIdFieldsForSegments, isIdFieldPath, isPublicDocPath, normalizeIdFields, isPlainObject } from "../idFields.js";
10
10
  import { incrementPublic as _incrementPublic, arrayPushPublic as _arrayPushPublic, arrayUnshiftPublic as _arrayUnshiftPublic, arrayInsertPublic as _arrayInsertPublic, arrayPopPublic as _arrayPopPublic, arrayShiftPublic as _arrayShiftPublic, arrayRemovePublic as _arrayRemovePublic, arrayMovePublic as _arrayMovePublic, setPublicDocReplace as _setPublicDocReplace, stringInsertPublic as _stringInsertPublic, stringRemovePublic as _stringRemovePublic } from '../dataTree.js';
11
11
  import { on as onCustomEvent, removeListener as removeCustomEventListener } from './eventsCompat.js';
@@ -28,6 +28,8 @@ class SignalCompat extends Signal {
28
28
  return super.path();
29
29
  }
30
30
  getId() {
31
+ if (isAggregationValuePath(this[SEGMENTS]))
32
+ return super.getId();
31
33
  const $target = resolveRefSignal(this);
32
34
  if ($target !== this)
33
35
  return $target.getId();
@@ -612,6 +614,11 @@ function readRefValue($signal) {
612
614
  throw err;
613
615
  }
614
616
  }
617
+ function isAggregationValuePath(segments) {
618
+ return Array.isArray(segments) &&
619
+ segments.length >= 3 &&
620
+ segments[0] === AGGREGATIONS;
621
+ }
615
622
  function resolveRefSignal($signal) {
616
623
  const directTarget = resolveRefSignalSafe($signal);
617
624
  if (directTarget && directTarget !== $signal)
@@ -8,39 +8,21 @@ export function isModelEventsSilentContextActive() {
8
8
  }
9
9
  export function runInSilentContext(fn) {
10
10
  silentDepth += 1;
11
- let result;
12
11
  try {
13
- result = fn();
12
+ return fn();
14
13
  }
15
- catch (error) {
14
+ finally {
16
15
  silentDepth -= 1;
17
- throw error;
18
16
  }
19
- if (result?.then) {
20
- return Promise.resolve(result).finally(() => {
21
- silentDepth -= 1;
22
- });
23
- }
24
- silentDepth -= 1;
25
- return result;
26
17
  }
27
18
  export function runInModelEventsSilentContext(fn) {
28
19
  modelEventsSilentDepth += 1;
29
- let result;
30
20
  try {
31
- result = fn();
21
+ return fn();
32
22
  }
33
- catch (error) {
23
+ finally {
34
24
  modelEventsSilentDepth -= 1;
35
- throw error;
36
- }
37
- if (result?.then) {
38
- return Promise.resolve(result).finally(() => {
39
- modelEventsSilentDepth -= 1;
40
- });
41
25
  }
42
- modelEventsSilentDepth -= 1;
43
- return result;
44
26
  }
45
27
  export function __resetSilentContextForTests() {
46
28
  silentDepth = 0;
@@ -1,4 +1,5 @@
1
1
  import { observe, raw, unobserve } from '@nx-js/observer-util';
2
+ import { getActiveDocOpContext } from '../Doc.js';
2
3
  import { getRoot } from "../Root.js";
3
4
  import { scheduleReaction } from '../batchScheduler.js';
4
5
  const START_REACTIONS = Symbol('compat start reactions');
@@ -19,11 +20,15 @@ export function compatStartOnRoot($root, targetPath, ...depsAndGetter) {
19
20
  const targetSegments = parsePathSegments(targetPath);
20
21
  const $target = resolveSignal($root, targetSegments);
21
22
  const targetKey = $target.path();
23
+ const depPaths = deps
24
+ .map(dep => getStartDepPath(dep, $root))
25
+ .filter(Boolean);
22
26
  const store = getStartStore($root);
23
27
  const existing = store.get(targetKey);
24
28
  if (existing)
25
29
  existing.stop();
26
30
  let lastSourceSnapshot = UNSET;
31
+ let lastTargetSnapshot = UNSET;
27
32
  const reaction = observe(() => {
28
33
  const resolvedDeps = [];
29
34
  for (const dep of deps) {
@@ -45,8 +50,23 @@ export function compatStartOnRoot($root, targetPath, ...depsAndGetter) {
45
50
  if (lastSourceSnapshot !== UNSET && deepEqualStartValue(lastSourceSnapshot, sourceSnapshot)) {
46
51
  return;
47
52
  }
53
+ const currentTargetSnapshot = lastTargetSnapshot === UNSET
54
+ ? UNSET
55
+ : detachStartValue($target.peek());
56
+ if (currentTargetSnapshot !== UNSET && deepEqualStartValue(currentTargetSnapshot, sourceSnapshot)) {
57
+ lastSourceSnapshot = sourceSnapshot;
58
+ lastTargetSnapshot = sourceSnapshot;
59
+ return;
60
+ }
61
+ if (currentTargetSnapshot !== UNSET &&
62
+ !deepEqualStartValue(lastTargetSnapshot, currentTargetSnapshot) &&
63
+ isActiveLocalDocOpForDeps(depPaths)) {
64
+ lastSourceSnapshot = sourceSnapshot;
65
+ return;
66
+ }
48
67
  lastSourceSnapshot = sourceSnapshot;
49
68
  const detachedValue = detachStartValue(sourceSnapshot);
69
+ lastTargetSnapshot = detachStartValue(detachedValue);
50
70
  // Keep the detached snapshot to avoid aliasing source and target.
51
71
  // Old racer start() writes through diffDeep by default. In compat mode we must preserve
52
72
  // that behavior, but also avoid reading the target reactively inside start(), otherwise
@@ -104,9 +124,22 @@ function resolveStartDep(dep, $root) {
104
124
  throw err;
105
125
  }
106
126
  }
127
+ function getStartDepPath(dep, $root) {
128
+ if (isSignalLike(dep))
129
+ return dep.path();
130
+ if (typeof dep === 'string')
131
+ return resolveSignal($root, parsePathSegments(dep)).path();
132
+ }
107
133
  function getStartDepValue($signal) {
108
134
  return readReactiveSnapshot($signal.get());
109
135
  }
136
+ function isActiveLocalDocOpForDeps(depPaths) {
137
+ const context = getActiveDocOpContext();
138
+ if (!context?.source)
139
+ return false;
140
+ const docPath = `${context.collection}.${context.docId}`;
141
+ return depPaths.some(depPath => depPath === docPath || depPath.startsWith(docPath + '.'));
142
+ }
110
143
  function readReactiveSnapshot(value) {
111
144
  if (!value || typeof value !== 'object')
112
145
  return value;
package/dist/orm/Doc.js CHANGED
@@ -12,6 +12,43 @@ import { getRoot, ROOT_ID, GLOBAL_ROOT_ID, getRootTransportMode } from "./Root.j
12
12
  import { registerRootOwnedDirectDocSubscription, unregisterRootOwnedDirectDocSubscription, getRootOwnedDirectDocSubscriptions, clearRootOwnedDirectDocSubscriptions } from "./rootContext.js";
13
13
  const ERROR_ON_EXCESSIVE_UNSUBSCRIBES = false;
14
14
  const DOC_FINALIZATION_TOKENS = new WeakMap();
15
+ const RECENT_DOC_OP_CONTEXT_TTL = 100;
16
+ const ACTIVE_DOC_OP_CONTEXTS = [];
17
+ let recentDocOpContext;
18
+ export function getActiveDocOpContext() {
19
+ return ACTIVE_DOC_OP_CONTEXTS[ACTIVE_DOC_OP_CONTEXTS.length - 1] || recentDocOpContext;
20
+ }
21
+ function pushActiveDocOpContext(collection, docId, source) {
22
+ const context = { collection, docId, source };
23
+ ACTIVE_DOC_OP_CONTEXTS.push(context);
24
+ recentDocOpContext = context;
25
+ }
26
+ function popActiveDocOpContext(collection, docId, source) {
27
+ const current = ACTIVE_DOC_OP_CONTEXTS[ACTIVE_DOC_OP_CONTEXTS.length - 1];
28
+ if (current?.collection === collection && current?.docId === docId && current?.source === source) {
29
+ ACTIVE_DOC_OP_CONTEXTS.pop();
30
+ clearRecentDocOpContext(current);
31
+ return;
32
+ }
33
+ let index = -1;
34
+ for (let i = ACTIVE_DOC_OP_CONTEXTS.length - 1; i >= 0; i--) {
35
+ const context = ACTIVE_DOC_OP_CONTEXTS[i];
36
+ if (context.collection === collection && context.docId === docId && context.source === source) {
37
+ index = i;
38
+ break;
39
+ }
40
+ }
41
+ if (index === -1)
42
+ return;
43
+ const [context] = ACTIVE_DOC_OP_CONTEXTS.splice(index, 1);
44
+ clearRecentDocOpContext(context);
45
+ }
46
+ function clearRecentDocOpContext(context) {
47
+ setTimeout(() => {
48
+ if (recentDocOpContext === context)
49
+ recentDocOpContext = undefined;
50
+ }, RECENT_DOC_OP_CONTEXT_TTL);
51
+ }
15
52
  function getDocFinalizationToken($doc) {
16
53
  let token = DOC_FINALIZATION_TOKENS.get($doc);
17
54
  if (!token) {
@@ -149,7 +186,15 @@ class Doc {
149
186
  doc.on('create', () => this._refData());
150
187
  doc.on('del', () => this._refMissingData());
151
188
  if (isModelEventsEnabled()) {
152
- doc.on('op', op => emitDocOp(this.collection, this.docId, op));
189
+ doc.on('before op', (_op, source) => pushActiveDocOpContext(this.collection, this.docId, source));
190
+ doc.on('op', (op, source) => {
191
+ try {
192
+ emitDocOp(this.collection, this.docId, op, source);
193
+ }
194
+ finally {
195
+ popActiveDocOpContext(this.collection, this.docId, source);
196
+ }
197
+ });
153
198
  }
154
199
  }
155
200
  _refMissingData() {
@@ -870,7 +915,7 @@ function createPendingDestroyEntry() {
870
915
  reject: rejectPending
871
916
  };
872
917
  }
873
- function emitDocOp(collection, docId, op) {
918
+ function emitDocOp(collection, docId, op, source) {
874
919
  if (!isModelEventsEnabled())
875
920
  return;
876
921
  const ops = Array.isArray(op) ? op : [op];
@@ -879,7 +924,7 @@ function emitDocOp(collection, docId, op) {
879
924
  continue;
880
925
  const baseSegments = [collection, docId];
881
926
  let pathSegments = baseSegments.concat(component.p);
882
- const meta = {};
927
+ const meta = { source };
883
928
  let value;
884
929
  let prevValue;
885
930
  if (has(component, 'si') || has(component, 'sd')) {
@@ -36,14 +36,14 @@ export function getSignalId($signal, rootId, readPath) {
36
36
  throw Error('Can\'t get the id of a collection');
37
37
  if (isDirectPublicDocumentSegments(segments))
38
38
  return getLeafId(segments);
39
+ if (segments[0] === AGGREGATIONS && segments.length === 3) {
40
+ return getAggregationDocId(segments, rootId, readPath);
41
+ }
39
42
  if (readPath) {
40
43
  const valueId = getValueIdFromPaths(segments, readPath);
41
44
  if (valueId.found)
42
45
  return valueId.id;
43
46
  }
44
- if (segments[0] === AGGREGATIONS && segments.length === 3) {
45
- return getAggregationDocId(segments, rootId);
46
- }
47
47
  return getLeafId(segments);
48
48
  }
49
49
  export function getSignalCollection($signal) {
@@ -1,4 +1,4 @@
1
- import { AGGREGATIONS, IS_AGGREGATION } from './Aggregation.js';
1
+ import { AGGREGATIONS, IS_AGGREGATION, getAggregationCollectionName, getAggregationRowId } from './Aggregation.js';
2
2
  import { HASH, IS_QUERY, QUERIES } from './Query.js';
3
3
  import { SEGMENTS } from "./signalSymbols.js";
4
4
  export function readSignalValue($signal, context, method, rawMethod) {
@@ -41,7 +41,8 @@ export function getSignalIds($signal, context) {
41
41
  const docs = context.readPrivateData(rootId, $signal[SEGMENTS], false);
42
42
  if (!Array.isArray(docs))
43
43
  return [];
44
- return docs.map(getAggregationRowId).filter(isString);
44
+ const collectionName = getAggregationCollectionName($signal[SEGMENTS]);
45
+ return docs.map(doc => getAggregationRowId(doc, collectionName)).filter(isString);
45
46
  }
46
47
  context.error('Signal.getIds() can only be used on query signals or aggregation signals. ' +
47
48
  'Received a regular signal: ' + JSON.stringify($signal[SEGMENTS]));
@@ -55,13 +56,6 @@ export function isAggregationValueSignal($signal) {
55
56
  const segments = $signal[SEGMENTS];
56
57
  return segments.length >= 2 && segments[0] === AGGREGATIONS;
57
58
  }
58
- function getAggregationRowId(doc) {
59
- const row = doc;
60
- if (typeof row?._id === 'string')
61
- return row._id;
62
- if (typeof row?.id === 'string')
63
- return row.id;
64
- }
65
59
  function isString(value) {
66
60
  return typeof value === 'string';
67
61
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "teamplay",
3
- "version": "0.5.0-alpha.10",
3
+ "version": "0.5.0-alpha.12",
4
4
  "description": "Full-stack signals ORM with multiplayer",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -134,5 +134,5 @@
134
134
  ]
135
135
  },
136
136
  "license": "MIT",
137
- "gitHead": "618cf6d63af687cfa1480979b3c0b4b15f7dfc45"
137
+ "gitHead": "13e07eda7f31ee883390b3ad04bdc6ecfbcb7f4c"
138
138
  }