@latticexyz/recs 2.2.18-ebe1aea8d4afb690ce1c7c2bcb42dc0f1faf6e77 → 2.2.18

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.
@@ -0,0 +1,403 @@
1
+ // src/constants.ts
2
+ var Type = /* @__PURE__ */ ((Type2) => {
3
+ Type2[Type2["Boolean"] = 0] = "Boolean";
4
+ Type2[Type2["Number"] = 1] = "Number";
5
+ Type2[Type2["OptionalNumber"] = 2] = "OptionalNumber";
6
+ Type2[Type2["BigInt"] = 3] = "BigInt";
7
+ Type2[Type2["OptionalBigInt"] = 4] = "OptionalBigInt";
8
+ Type2[Type2["String"] = 5] = "String";
9
+ Type2[Type2["OptionalString"] = 6] = "OptionalString";
10
+ Type2[Type2["NumberArray"] = 7] = "NumberArray";
11
+ Type2[Type2["OptionalNumberArray"] = 8] = "OptionalNumberArray";
12
+ Type2[Type2["BigIntArray"] = 9] = "BigIntArray";
13
+ Type2[Type2["OptionalBigIntArray"] = 10] = "OptionalBigIntArray";
14
+ Type2[Type2["StringArray"] = 11] = "StringArray";
15
+ Type2[Type2["OptionalStringArray"] = 12] = "OptionalStringArray";
16
+ Type2[Type2["Entity"] = 13] = "Entity";
17
+ Type2[Type2["OptionalEntity"] = 14] = "OptionalEntity";
18
+ Type2[Type2["EntityArray"] = 15] = "EntityArray";
19
+ Type2[Type2["OptionalEntityArray"] = 16] = "OptionalEntityArray";
20
+ Type2[Type2["T"] = 17] = "T";
21
+ Type2[Type2["OptionalT"] = 18] = "OptionalT";
22
+ return Type2;
23
+ })(Type || {});
24
+ var UpdateType = /* @__PURE__ */ ((UpdateType2) => {
25
+ UpdateType2[UpdateType2["Enter"] = 0] = "Enter";
26
+ UpdateType2[UpdateType2["Exit"] = 1] = "Exit";
27
+ UpdateType2[UpdateType2["Update"] = 2] = "Update";
28
+ UpdateType2[UpdateType2["Noop"] = 3] = "Noop";
29
+ return UpdateType2;
30
+ })(UpdateType || {});
31
+ var OptionalTypes = [
32
+ 14 /* OptionalEntity */,
33
+ 16 /* OptionalEntityArray */,
34
+ 2 /* OptionalNumber */,
35
+ 8 /* OptionalNumberArray */,
36
+ 4 /* OptionalBigInt */,
37
+ 10 /* OptionalBigIntArray */,
38
+ 6 /* OptionalString */,
39
+ 12 /* OptionalStringArray */,
40
+ 18 /* OptionalT */
41
+ ];
42
+
43
+ // src/Component.ts
44
+ import { transformIterator, uuid } from "@latticexyz/utils";
45
+ import { mapObject } from "@latticexyz/utils";
46
+ import { filter, map as map2, Subject } from "rxjs";
47
+
48
+ // src/Indexer.ts
49
+ function createIndexer(component) {
50
+ const valueToEntities = /* @__PURE__ */ new Map();
51
+ function getEntitiesWithValue2(value) {
52
+ const entities = valueToEntities.get(getValueKey(value));
53
+ return entities ? new Set([...entities].map(getEntityString)) : /* @__PURE__ */ new Set();
54
+ }
55
+ function getValueKey(value) {
56
+ return Object.values(value).join("/");
57
+ }
58
+ function add(entity, value) {
59
+ if (!value) return;
60
+ const valueKey = getValueKey(value);
61
+ let entitiesWithValue = valueToEntities.get(valueKey);
62
+ if (!entitiesWithValue) {
63
+ entitiesWithValue = /* @__PURE__ */ new Set();
64
+ valueToEntities.set(valueKey, entitiesWithValue);
65
+ }
66
+ entitiesWithValue.add(entity);
67
+ }
68
+ function remove(entity, value) {
69
+ if (!value) return;
70
+ const valueKey = getValueKey(value);
71
+ const entitiesWithValue = valueToEntities.get(valueKey);
72
+ if (!entitiesWithValue) return;
73
+ entitiesWithValue.delete(entity);
74
+ }
75
+ for (const entity of getComponentEntities(component)) {
76
+ const value = getComponentValue(component, entity);
77
+ add(getEntitySymbol(entity), value);
78
+ }
79
+ const subscription = component.update$.subscribe(({ entity, value }) => {
80
+ remove(getEntitySymbol(entity), value[1]);
81
+ add(getEntitySymbol(entity), value[0]);
82
+ });
83
+ component.world.registerDisposer(() => subscription?.unsubscribe());
84
+ return { ...component, getEntitiesWithValue: getEntitiesWithValue2 };
85
+ }
86
+
87
+ // src/utils.ts
88
+ import { map, pipe } from "rxjs";
89
+ function isComponentUpdate(update, component) {
90
+ return update.component === component;
91
+ }
92
+ function toUpdate(entity, component) {
93
+ const value = getComponentValue(component, entity);
94
+ return {
95
+ entity,
96
+ component,
97
+ value: [value, void 0],
98
+ type: value == null ? 3 /* Noop */ : 0 /* Enter */
99
+ };
100
+ }
101
+ function toUpdateStream(component) {
102
+ return pipe(map((entity) => toUpdate(entity, component)));
103
+ }
104
+ function isIndexer(c) {
105
+ return "getEntitiesWithValue" in c;
106
+ }
107
+ function isFullComponentValue(component, value) {
108
+ return Object.keys(component.schema).every((key) => key in value);
109
+ }
110
+
111
+ // src/Component.ts
112
+ function getComponentName(component) {
113
+ return component.metadata?.componentName ?? component.metadata?.tableName ?? component.metadata?.tableId ?? component.metadata?.contractId ?? component.id;
114
+ }
115
+ function defineComponent(world, schema, options) {
116
+ if (Object.keys(schema).length === 0) throw new Error("Component schema must have at least one key");
117
+ const id = options?.id ?? uuid();
118
+ const values = mapObject(schema, () => /* @__PURE__ */ new Map());
119
+ const update$ = new Subject();
120
+ const metadata = options?.metadata;
121
+ const entities = () => transformIterator(Object.values(values)[0].keys(), getEntityString);
122
+ let component = { values, schema, id, update$, metadata, entities, world };
123
+ if (options?.indexed) component = createIndexer(component);
124
+ world.registerComponent(component);
125
+ return component;
126
+ }
127
+ function setComponent(component, entity, value, options = {}) {
128
+ const entitySymbol = getEntitySymbol(entity);
129
+ const prevValue = getComponentValue(component, entity);
130
+ for (const [key, val] of Object.entries(value)) {
131
+ if (component.values[key]) {
132
+ component.values[key].set(entitySymbol, val);
133
+ } else {
134
+ const isTableFieldIndex = component.metadata?.tableId && /^\d+$/.test(key);
135
+ if (!isTableFieldIndex) {
136
+ console.warn(
137
+ "Component definition for",
138
+ getComponentName(component),
139
+ "is missing key",
140
+ key,
141
+ ", ignoring value",
142
+ val,
143
+ "for entity",
144
+ entity,
145
+ ". Existing keys: ",
146
+ Object.keys(component.values)
147
+ );
148
+ }
149
+ }
150
+ }
151
+ if (!options.skipUpdateStream) {
152
+ component.update$.next({ entity, value: [value, prevValue], component });
153
+ }
154
+ }
155
+ function updateComponent(component, entity, value, initialValue, options = {}) {
156
+ const currentValue = getComponentValue(component, entity);
157
+ if (currentValue === void 0) {
158
+ if (initialValue === void 0) {
159
+ throw new Error(`Can't update component ${getComponentName(component)} without a current value or initial value`);
160
+ }
161
+ setComponent(component, entity, { ...initialValue, ...value }, options);
162
+ } else {
163
+ setComponent(component, entity, { ...currentValue, ...value }, options);
164
+ }
165
+ }
166
+ function removeComponent(component, entity, options = {}) {
167
+ const entitySymbol = getEntitySymbol(entity);
168
+ const prevValue = getComponentValue(component, entity);
169
+ for (const key of Object.keys(component.values)) {
170
+ component.values[key].delete(entitySymbol);
171
+ }
172
+ if (!options.skipUpdateStream) {
173
+ component.update$.next({ entity, value: [void 0, prevValue], component });
174
+ }
175
+ }
176
+ function hasComponent(component, entity) {
177
+ const entitySymbol = getEntitySymbol(entity);
178
+ const map3 = Object.values(component.values)[0];
179
+ return map3.has(entitySymbol);
180
+ }
181
+ function getComponentValue(component, entity) {
182
+ const value = {};
183
+ const entitySymbol = getEntitySymbol(entity);
184
+ const schemaKeys = Object.keys(component.schema);
185
+ for (const key of schemaKeys) {
186
+ const val = component.values[key].get(entitySymbol);
187
+ if (val === void 0 && !OptionalTypes.includes(component.schema[key])) return void 0;
188
+ value[key] = val;
189
+ }
190
+ return value;
191
+ }
192
+ function getComponentValueStrict(component, entity) {
193
+ const value = getComponentValue(component, entity);
194
+ if (!value) throw new Error(`No value for component ${getComponentName(component)} on entity ${entity}`);
195
+ return value;
196
+ }
197
+ function componentValueEquals(a, b) {
198
+ if (!a && !b) return true;
199
+ if (!a || !b) return false;
200
+ let equals = true;
201
+ for (const key of Object.keys(a)) {
202
+ equals = a[key] === b[key];
203
+ if (!equals) return false;
204
+ }
205
+ return equals;
206
+ }
207
+ function withValue(component, value) {
208
+ return [component, value];
209
+ }
210
+ function getEntitiesWithValue(component, value) {
211
+ if (isIndexer(component) && isFullComponentValue(component, value)) {
212
+ return component.getEntitiesWithValue(value);
213
+ }
214
+ const entities = /* @__PURE__ */ new Set();
215
+ for (const entity of getComponentEntities(component)) {
216
+ const val = getComponentValue(component, entity);
217
+ if (componentValueEquals(value, val)) {
218
+ entities.add(entity);
219
+ }
220
+ }
221
+ return entities;
222
+ }
223
+ function getComponentEntities(component) {
224
+ return component.entities();
225
+ }
226
+ function overridableComponent(component) {
227
+ let nonce = 0;
228
+ const overrides = /* @__PURE__ */ new Map();
229
+ const overriddenEntityValues = /* @__PURE__ */ new Map();
230
+ const update$ = new Subject();
231
+ function addOverride(id, update) {
232
+ overrides.set(id, { update, nonce: nonce++ });
233
+ setOverriddenComponentValue(update.entity, update.value);
234
+ }
235
+ function removeOverride(id) {
236
+ const affectedEntity = overrides.get(id)?.update.entity;
237
+ overrides.delete(id);
238
+ if (affectedEntity == null) return;
239
+ const relevantOverrides = [...overrides.values()].filter((o) => o.update.entity === affectedEntity).sort((a, b) => a.nonce < b.nonce ? -1 : 1);
240
+ if (relevantOverrides.length > 0) {
241
+ const lastOverride = relevantOverrides[relevantOverrides.length - 1];
242
+ setOverriddenComponentValue(affectedEntity, lastOverride.update.value);
243
+ } else {
244
+ setOverriddenComponentValue(affectedEntity, void 0);
245
+ }
246
+ }
247
+ function getOverriddenComponentValue(entity) {
248
+ const originalValue = getComponentValue(component, entity);
249
+ const entitySymbol = getEntitySymbol(entity);
250
+ const overriddenValue = overriddenEntityValues.get(entitySymbol);
251
+ return (originalValue || overriddenValue) && overriddenValue !== null ? { ...originalValue, ...overriddenValue } : void 0;
252
+ }
253
+ const valueProxyHandler = (key) => ({
254
+ get(target, prop) {
255
+ if (prop === "get") {
256
+ return (entity) => {
257
+ const originalValue = target.get(entity);
258
+ const overriddenValue = overriddenEntityValues.get(entity);
259
+ return overriddenValue && overriddenValue[key] != null ? overriddenValue[key] : originalValue;
260
+ };
261
+ }
262
+ if (prop === "has") {
263
+ return (entity) => {
264
+ return target.has(entity) || overriddenEntityValues.has(entity);
265
+ };
266
+ }
267
+ if (prop === "keys") {
268
+ return () => (/* @__PURE__ */ new Set([...target.keys(), ...overriddenEntityValues.keys()])).values();
269
+ }
270
+ return Reflect.get(target, prop, target);
271
+ }
272
+ });
273
+ const partialValues = {};
274
+ for (const key of Object.keys(component.values)) {
275
+ partialValues[key] = new Proxy(component.values[key], valueProxyHandler(key));
276
+ }
277
+ const valuesProxy = partialValues;
278
+ const overriddenComponent = new Proxy(component, {
279
+ get(target, prop) {
280
+ if (prop === "addOverride") return addOverride;
281
+ if (prop === "removeOverride") return removeOverride;
282
+ if (prop === "values") return valuesProxy;
283
+ if (prop === "update$") return update$;
284
+ if (prop === "entities")
285
+ return () => (/* @__PURE__ */ new Set([
286
+ ...transformIterator(overriddenEntityValues.keys(), getEntityString),
287
+ ...target.entities()
288
+ ])).values();
289
+ return Reflect.get(target, prop);
290
+ },
291
+ has(target, prop) {
292
+ if (prop === "addOverride" || prop === "removeOverride") return true;
293
+ return prop in target;
294
+ }
295
+ });
296
+ function setOverriddenComponentValue(entity, value) {
297
+ const entitySymbol = getEntitySymbol(entity);
298
+ const prevValue = getOverriddenComponentValue(entity);
299
+ if (value !== void 0) overriddenEntityValues.set(entitySymbol, value);
300
+ else overriddenEntityValues.delete(entitySymbol);
301
+ update$.next({ entity, value: [getOverriddenComponentValue(entity), prevValue], component: overriddenComponent });
302
+ }
303
+ component.update$.pipe(
304
+ filter((e) => !overriddenEntityValues.get(getEntitySymbol(e.entity))),
305
+ map2((update) => ({ ...update, component: overriddenComponent }))
306
+ ).subscribe(update$);
307
+ return overriddenComponent;
308
+ }
309
+ function getLocalCacheId(component, uniqueWorldIdentifier) {
310
+ return `localcache-${uniqueWorldIdentifier}-${component.id}`;
311
+ }
312
+ function clearLocalCache(component, uniqueWorldIdentifier) {
313
+ localStorage.removeItem(getLocalCacheId(component, uniqueWorldIdentifier));
314
+ }
315
+ function createLocalCache(component, uniqueWorldIdentifier) {
316
+ const { world, update$, values } = component;
317
+ const cacheId = getLocalCacheId(component, uniqueWorldIdentifier);
318
+ let numUpdates = 0;
319
+ const creation = Date.now();
320
+ const encodedCache = localStorage.getItem(cacheId);
321
+ if (encodedCache) {
322
+ const cache = JSON.parse(encodedCache);
323
+ const state = {};
324
+ for (const [key, values2] of cache) {
325
+ for (const [entity, value] of values2) {
326
+ state[entity] = state[entity] || {};
327
+ state[entity][key] = value;
328
+ }
329
+ }
330
+ for (const [entityId, value] of Object.entries(state)) {
331
+ const entity = world.registerEntity({ id: entityId });
332
+ setComponent(component, entity, value);
333
+ }
334
+ console.info("Loading component", getComponentName(component), "from local cache.");
335
+ }
336
+ const updateSub = update$.subscribe(() => {
337
+ numUpdates++;
338
+ const encoded = JSON.stringify(
339
+ Object.entries(mapObject(values, (m) => [...m.entries()].map((e) => [getEntityString(e[0]), e[1]])))
340
+ );
341
+ localStorage.setItem(cacheId, encoded);
342
+ if (numUpdates > 200) {
343
+ console.warn(
344
+ "Component",
345
+ getComponentName(component),
346
+ "was locally cached",
347
+ numUpdates,
348
+ "times since",
349
+ new Date(creation).toLocaleTimeString(),
350
+ "- the local cache is in an alpha state and should not be used with components that update frequently yet"
351
+ );
352
+ }
353
+ });
354
+ component.world.registerDisposer(() => updateSub?.unsubscribe());
355
+ return component;
356
+ }
357
+
358
+ // src/Entity.ts
359
+ function createEntity(world, components, options) {
360
+ const entity = world.registerEntity(options ?? {});
361
+ if (components) {
362
+ for (const [component, value] of components) {
363
+ setComponent(component, entity, value);
364
+ }
365
+ }
366
+ return entity;
367
+ }
368
+ function getEntitySymbol(entityString) {
369
+ return Symbol.for(entityString);
370
+ }
371
+ function getEntityString(entity) {
372
+ return Symbol.keyFor(entity);
373
+ }
374
+
375
+ export {
376
+ Type,
377
+ UpdateType,
378
+ OptionalTypes,
379
+ createEntity,
380
+ getEntitySymbol,
381
+ getEntityString,
382
+ createIndexer,
383
+ isComponentUpdate,
384
+ toUpdate,
385
+ toUpdateStream,
386
+ isIndexer,
387
+ isFullComponentValue,
388
+ defineComponent,
389
+ setComponent,
390
+ updateComponent,
391
+ removeComponent,
392
+ hasComponent,
393
+ getComponentValue,
394
+ getComponentValueStrict,
395
+ componentValueEquals,
396
+ withValue,
397
+ getEntitiesWithValue,
398
+ getComponentEntities,
399
+ overridableComponent,
400
+ clearLocalCache,
401
+ createLocalCache
402
+ };
403
+ //# sourceMappingURL=chunk-PAKOIJAK.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/constants.ts","../src/Component.ts","../src/Indexer.ts","../src/utils.ts","../src/Entity.ts"],"sourcesContent":["/**\n * Type enum is used to specify value types in {@link ComponentSchema} to be able\n * to access type values in JavaScript in addition to TypeScript type checks.\n */\nexport enum Type {\n Boolean,\n Number,\n OptionalNumber,\n BigInt,\n OptionalBigInt,\n String,\n OptionalString,\n NumberArray,\n OptionalNumberArray,\n BigIntArray,\n OptionalBigIntArray,\n StringArray,\n OptionalStringArray,\n Entity,\n OptionalEntity,\n EntityArray,\n OptionalEntityArray,\n T,\n OptionalT,\n}\n\n/**\n * Used to specify type of {@link ComponentUpdate}.\n * - Enter: Update added a value to an entity that did not have a value before\n * - Exit: Update removed a value from an entity that had a value before\n * - Update: Update changed a value of an entity that already had a value before. Note: the value doesn't need to be different from the previous value.\n * - Noop: Update did nothing (removed a value from an entity that did not have a value)\n */\nexport enum UpdateType {\n Enter,\n Exit,\n Update,\n Noop,\n}\n\n/**\n * Helper constant with all optional {@link Type}s.\n */\nexport const OptionalTypes = [\n Type.OptionalEntity,\n Type.OptionalEntityArray,\n Type.OptionalNumber,\n Type.OptionalNumberArray,\n Type.OptionalBigInt,\n Type.OptionalBigIntArray,\n Type.OptionalString,\n Type.OptionalStringArray,\n Type.OptionalT,\n];\n","import { transformIterator, uuid } from \"@latticexyz/utils\";\nimport { mapObject } from \"@latticexyz/utils\";\nimport { filter, map, Subject } from \"rxjs\";\nimport { OptionalTypes } from \"./constants\";\nimport { createIndexer } from \"./Indexer\";\nimport {\n Component,\n ComponentValue,\n Entity,\n EntitySymbol,\n Indexer,\n Metadata,\n OverridableComponent,\n Override,\n Schema,\n World,\n} from \"./types\";\nimport { isFullComponentValue, isIndexer } from \"./utils\";\nimport { getEntityString, getEntitySymbol } from \"./Entity\";\n\nexport type ComponentMutationOptions = {\n /** Skip publishing this mutation to the component's update stream. Mostly used internally during initial hydration. */\n skipUpdateStream?: boolean;\n};\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction getComponentName(component: Component<any, any, any>) {\n return (\n component.metadata?.componentName ??\n component.metadata?.tableName ??\n component.metadata?.tableId ??\n component.metadata?.contractId ??\n component.id\n );\n}\n\n/**\n * Components contain state indexed by entities and are one of the fundamental building blocks in ECS.\n * Besides containing the state, components expose an rxjs update$ stream, that emits an event any time the value\n * of an entity in this component is updated.\n *\n * @param world {@link World} object this component should be registered onto.\n * @param schema {@link Schema} of component values. Uses Type enum as bridge between typescript types and javascript accessible values.\n * @param options Optional: {\n * id: descriptive id for this component (otherwise an autogenerated id is used),\n * metadata: arbitrary metadata,\n * indexed: if this flag is set, an indexer is applied to this component (see {@link createIndexer})\n * }\n * @returns Component object linked to the provided World\n *\n * @example\n * ```\n * const Position = defineComponent(world, { x: Type.Number, y: Type.Number }, { id: \"Position\" });\n * ```\n */\nexport function defineComponent<S extends Schema, M extends Metadata, T = unknown>(\n world: World,\n schema: S,\n options?: { id?: string; metadata?: M; indexed?: boolean },\n) {\n if (Object.keys(schema).length === 0) throw new Error(\"Component schema must have at least one key\");\n const id = options?.id ?? uuid();\n const values = mapObject(schema, () => new Map());\n const update$ = new Subject();\n const metadata = options?.metadata;\n const entities = () =>\n transformIterator((Object.values(values)[0] as Map<EntitySymbol, unknown>).keys(), getEntityString);\n let component = { values, schema, id, update$, metadata, entities, world } as Component<S, M, T>;\n if (options?.indexed) component = createIndexer(component);\n world.registerComponent(component as Component);\n return component;\n}\n\n/**\n * Set the value for a given entity in a given component.\n *\n * @param component {@link defineComponent Component} to be updated.\n * @param entity {@link Entity} whose value in the given component should be set.\n * @param value Value to set, schema must match the component schema.\n *\n * @example\n * ```\n * setComponent(Position, entity, { x: 1, y: 2 });\n * ```\n */\nexport function setComponent<S extends Schema, T = unknown>(\n component: Component<S, Metadata, T>,\n entity: Entity,\n value: ComponentValue<S, T>,\n options: ComponentMutationOptions = {},\n) {\n const entitySymbol = getEntitySymbol(entity);\n const prevValue = getComponentValue(component, entity);\n for (const [key, val] of Object.entries(value)) {\n if (component.values[key]) {\n component.values[key].set(entitySymbol, val);\n } else {\n const isTableFieldIndex = component.metadata?.tableId && /^\\d+$/.test(key);\n if (!isTableFieldIndex) {\n // If this key looks like a field index from `defineStoreComponents`,\n // we can ignore this value without logging anything.\n //\n // Otherwise, we should let the user know we found undefined data.\n console.warn(\n \"Component definition for\",\n getComponentName(component),\n \"is missing key\",\n key,\n \", ignoring value\",\n val,\n \"for entity\",\n entity,\n \". Existing keys: \",\n Object.keys(component.values),\n );\n }\n }\n }\n if (!options.skipUpdateStream) {\n component.update$.next({ entity, value: [value, prevValue], component });\n }\n}\n\n/**\n * Update the value for a given entity in a given component while keeping the old value of keys not included in the update.\n *\n * @param component {@link defineComponent Component} to be updated.\n * @param entity {@link Entity} whose value in the given component should be updated.\n * @param value Partial value to be set, remaining keys will be taken from the existing component value.\n *\n * @remarks\n * This function fails silently during runtime if a partial value is set for an entity that\n * does not have a component value yet, since then a partial value will be set in the component for this entity.\n *\n * @example\n * ```\n * updateComponent(Position, entity, { x: 1 });\n * ```\n */\nexport function updateComponent<S extends Schema, T = unknown>(\n component: Component<S, Metadata, T>,\n entity: Entity,\n value: Partial<ComponentValue<S, T>>,\n initialValue?: ComponentValue<S, T>,\n options: ComponentMutationOptions = {},\n) {\n const currentValue = getComponentValue(component, entity);\n if (currentValue === undefined) {\n if (initialValue === undefined) {\n throw new Error(`Can't update component ${getComponentName(component)} without a current value or initial value`);\n }\n setComponent(component, entity, { ...initialValue, ...value }, options);\n } else {\n setComponent(component, entity, { ...currentValue, ...value }, options);\n }\n}\n\n/**\n * Remove a given entity from a given component.\n *\n * @param component {@link defineComponent Component} to be updated.\n * @param entity {@link Entity} whose value should be removed from this component.\n */\nexport function removeComponent<S extends Schema, M extends Metadata, T = unknown>(\n component: Component<S, M, T>,\n entity: Entity,\n options: ComponentMutationOptions = {},\n) {\n const entitySymbol = getEntitySymbol(entity);\n const prevValue = getComponentValue(component, entity);\n for (const key of Object.keys(component.values)) {\n component.values[key].delete(entitySymbol);\n }\n if (!options.skipUpdateStream) {\n component.update$.next({ entity, value: [undefined, prevValue], component });\n }\n}\n\n/**\n * Check whether a component contains a value for a given entity.\n *\n * @param component {@link defineComponent Component} to check whether it has a value for the given entity.\n * @param entity {@link Entity} to check whether it has a value in the given component.\n * @returns true if the component contains a value for the given entity, else false.\n */\nexport function hasComponent<S extends Schema, T = unknown>(\n component: Component<S, Metadata, T>,\n entity: Entity,\n): boolean {\n const entitySymbol = getEntitySymbol(entity);\n const map = Object.values(component.values)[0];\n return map.has(entitySymbol);\n}\n\n/**\n * Get the value of a given entity in the given component.\n * Returns undefined if no value or only a partial value is found.\n *\n * @param component {@link defineComponent Component} to get the value from for the given entity.\n * @param entity {@link Entity} to get the value for from the given component.\n * @returns Value of the given entity in the given component or undefined if no value exists.\n */\nexport function getComponentValue<S extends Schema, T = unknown>(\n component: Component<S, Metadata, T>,\n entity: Entity,\n): ComponentValue<S, T> | undefined {\n const value: Record<string, unknown> = {};\n const entitySymbol = getEntitySymbol(entity);\n\n // Get the value of each schema key\n const schemaKeys = Object.keys(component.schema);\n for (const key of schemaKeys) {\n const val = component.values[key].get(entitySymbol);\n if (val === undefined && !OptionalTypes.includes(component.schema[key])) return undefined;\n value[key] = val;\n }\n\n return value as ComponentValue<S, T>;\n}\n\n/**\n * Get the value of a given entity in the given component.\n * Throws an error if no value exists for the given entity in the given component.\n *\n * @param component {@link defineComponent Component} to get the value from for the given entity.\n * @param entity {@link Entity} of the entity to get the value for from the given component.\n * @returns Value of the given entity in the given component.\n *\n * @remarks\n * Throws an error if no value exists in the component for the given entity.\n */\nexport function getComponentValueStrict<S extends Schema, T = unknown>(\n component: Component<S, Metadata, T>,\n entity: Entity,\n): ComponentValue<S, T> {\n const value = getComponentValue(component, entity);\n if (!value) throw new Error(`No value for component ${getComponentName(component)} on entity ${entity}`);\n return value;\n}\n\n/**\n * Compare two {@link ComponentValue}s.\n * `a` can be a partial component value, in which case only the keys present in `a` are compared to the corresponding keys in `b`.\n *\n * @param a Partial {@link ComponentValue} to compare to `b`\n * @param b Component value to compare `a` to.\n * @returns True if `a` equals `b` in the keys present in a or neither `a` nor `b` are defined, else false.\n *\n * @example\n * ```\n * componentValueEquals({ x: 1, y: 2 }, { x: 1, y: 3 }) // returns false because value of y doesn't match\n * componentValueEquals({ x: 1 }, { x: 1, y: 3 }) // returns true because x is equal and y is not present in a\n * ```\n */\nexport function componentValueEquals<S extends Schema, T = unknown>(\n a?: Partial<ComponentValue<S, T>>,\n b?: ComponentValue<S, T>,\n): boolean {\n if (!a && !b) return true;\n if (!a || !b) return false;\n\n let equals = true;\n for (const key of Object.keys(a)) {\n equals = a[key] === b[key];\n if (!equals) return false;\n }\n return equals;\n}\n\n/**\n * Util to create a tuple of a component and value with matching schema.\n * (Used to enforce Typescript type safety.)\n *\n * @param component {@link defineComponent Component} with {@link ComponentSchema} `S`\n * @param value {@link ComponentValue} with {@link ComponentSchema} `S`\n * @returns Tuple `[component, value]`\n */\nexport function withValue<S extends Schema, T = unknown>(\n component: Component<S, Metadata, T>,\n value: ComponentValue<S, T>,\n): [Component<S, Metadata, T>, ComponentValue<S, T>] {\n return [component, value];\n}\n\n/**\n * Get a set of entities that have the given component value in the given component.\n *\n * @param component {@link defineComponent Component} to get entities with the given value from.\n * @param value look for entities with this {@link ComponentValue}.\n * @returns Set with {@link Entity Entities} with the given component value.\n */\nexport function getEntitiesWithValue<S extends Schema>(\n component: Component<S> | Indexer<S>,\n value: Partial<ComponentValue<S>>,\n): Set<Entity> {\n // Shortcut for indexers\n if (isIndexer(component) && isFullComponentValue(component, value)) {\n return component.getEntitiesWithValue(value);\n }\n\n // Trivial implementation for regular components\n const entities = new Set<Entity>();\n for (const entity of getComponentEntities(component)) {\n const val = getComponentValue(component, entity);\n if (componentValueEquals(value, val)) {\n entities.add(entity);\n }\n }\n return entities;\n}\n\n/**\n * Get a set of all entities of the given component.\n *\n * @param component {@link defineComponent Component} to get all entities from\n * @returns Set of all entities in the given component.\n */\nexport function getComponentEntities<S extends Schema, T = unknown>(\n component: Component<S, Metadata, T>,\n): IterableIterator<Entity> {\n return component.entities();\n}\n\n/**\n * An overridable component is a mirror of the source component, with functions to lazily override specific entity values.\n * Lazily override means the values are not actually set to the source component, but the override is only returned if the value is read.\n *\n * - When an override for an entity is added to the component, the override is propagated via the component's `update$` stream.\n * - While an override is set for a specific entity, no updates to the source component for this entity will be propagated to the `update$` stream.\n * - When an override is removed for a specific entity and there are more overrides targeting this entity,\n * the override with the highest nonce will be propagated to the `update$` stream.\n * - When an override is removed for a specific entity and there are no more overrides targeting this entity,\n * the non-overridden underlying component value of this entity will be propagated to the `update$` stream.\n *\n * @param component {@link defineComponent Component} to use as underlying source for the overridable component\n * @returns overridable component\n */\nexport function overridableComponent<S extends Schema, M extends Metadata, T = unknown>(\n component: Component<S, M, T>,\n): OverridableComponent<S, M, T> {\n let nonce = 0;\n\n // Map from OverrideId to Override (to be able to add multiple overrides to the same Entity)\n const overrides = new Map<string, { update: Override<S, T>; nonce: number }>();\n\n // Map from EntitySymbol to current overridden component value\n const overriddenEntityValues = new Map<EntitySymbol, Partial<ComponentValue<S, T>> | null>();\n\n // Update event stream that takes into account overridden entity values\n const update$ = new Subject<{\n entity: Entity;\n value: [ComponentValue<S, T> | undefined, ComponentValue<S, T> | undefined];\n component: Component<S, Metadata, T>;\n }>();\n\n // Add a new override to some entity\n function addOverride(id: string, update: Override<S, T>) {\n overrides.set(id, { update, nonce: nonce++ });\n setOverriddenComponentValue(update.entity, update.value);\n }\n\n // Remove an override from an entity\n function removeOverride(id: string) {\n const affectedEntity = overrides.get(id)?.update.entity;\n overrides.delete(id);\n\n if (affectedEntity == null) return;\n\n // If there are more overries affecting this entity,\n // set the overriddenEntityValue to the last override\n const relevantOverrides = [...overrides.values()]\n .filter((o) => o.update.entity === affectedEntity)\n .sort((a, b) => (a.nonce < b.nonce ? -1 : 1));\n\n if (relevantOverrides.length > 0) {\n const lastOverride = relevantOverrides[relevantOverrides.length - 1];\n setOverriddenComponentValue(affectedEntity, lastOverride.update.value);\n } else {\n setOverriddenComponentValue(affectedEntity, undefined);\n }\n }\n\n // Internal function to get the current overridden value or value of the source component\n function getOverriddenComponentValue(entity: Entity): ComponentValue<S, T> | undefined {\n const originalValue = getComponentValue(component, entity);\n const entitySymbol = getEntitySymbol(entity);\n const overriddenValue = overriddenEntityValues.get(entitySymbol);\n return (originalValue || overriddenValue) && overriddenValue !== null // null is a valid override, in this case return undefined\n ? ({ ...originalValue, ...overriddenValue } as ComponentValue<S, T>)\n : undefined;\n }\n\n const valueProxyHandler: (key: keyof S) => ProxyHandler<(typeof component.values)[typeof key]> = (key: keyof S) => ({\n get(target, prop) {\n // Intercept calls to component.value[key].get(entity)\n if (prop === \"get\") {\n return (entity: EntitySymbol) => {\n const originalValue = target.get(entity);\n const overriddenValue = overriddenEntityValues.get(entity);\n return overriddenValue && overriddenValue[key] != null ? overriddenValue[key] : originalValue;\n };\n }\n\n // Intercept calls to component.value[key].has(entity)\n if (prop === \"has\") {\n return (entity: EntitySymbol) => {\n return target.has(entity) || overriddenEntityValues.has(entity);\n };\n }\n\n // Intercept calls to component.value[key].keys()\n if (prop === \"keys\") {\n return () => new Set([...target.keys(), ...overriddenEntityValues.keys()]).values();\n }\n\n return Reflect.get(target, prop, target);\n },\n });\n\n const partialValues: Partial<Component<S, M, T>[\"values\"]> = {};\n for (const key of Object.keys(component.values) as (keyof S)[]) {\n partialValues[key] = new Proxy(component.values[key], valueProxyHandler(key));\n }\n const valuesProxy = partialValues as Component<S, M, T>[\"values\"];\n\n const overriddenComponent = new Proxy(component, {\n get(target, prop) {\n if (prop === \"addOverride\") return addOverride;\n if (prop === \"removeOverride\") return removeOverride;\n if (prop === \"values\") return valuesProxy;\n if (prop === \"update$\") return update$;\n if (prop === \"entities\")\n return () =>\n new Set([\n ...transformIterator(overriddenEntityValues.keys(), getEntityString),\n ...target.entities(),\n ]).values();\n\n return Reflect.get(target, prop);\n },\n has(target, prop) {\n if (prop === \"addOverride\" || prop === \"removeOverride\") return true;\n return prop in target;\n },\n }) as OverridableComponent<S, M, T>;\n\n // Internal function to set the current overridden component value and emit the update event\n function setOverriddenComponentValue(entity: Entity, value?: Partial<ComponentValue<S, T>> | null) {\n const entitySymbol = getEntitySymbol(entity);\n // Check specifically for undefined - null is a valid override\n const prevValue = getOverriddenComponentValue(entity);\n if (value !== undefined) overriddenEntityValues.set(entitySymbol, value);\n else overriddenEntityValues.delete(entitySymbol);\n update$.next({ entity, value: [getOverriddenComponentValue(entity), prevValue], component: overriddenComponent });\n }\n\n // Channel through update events from the original component if there are no overrides\n component.update$\n .pipe(\n filter((e) => !overriddenEntityValues.get(getEntitySymbol(e.entity))),\n map((update) => ({ ...update, component: overriddenComponent })),\n )\n .subscribe(update$);\n\n return overriddenComponent;\n}\n\nfunction getLocalCacheId(component: Component, uniqueWorldIdentifier?: string): string {\n return `localcache-${uniqueWorldIdentifier}-${component.id}`;\n}\n\nexport function clearLocalCache(component: Component, uniqueWorldIdentifier?: string): void {\n localStorage.removeItem(getLocalCacheId(component, uniqueWorldIdentifier));\n}\n\n// Note: Only proof of concept for now - use this only for component that do not update frequently\nexport function createLocalCache<S extends Schema, M extends Metadata, T = unknown>(\n component: Component<S, M, T>,\n uniqueWorldIdentifier?: string,\n): Component<S, M, T> {\n const { world, update$, values } = component;\n const cacheId = getLocalCacheId(component as Component, uniqueWorldIdentifier);\n let numUpdates = 0;\n const creation = Date.now();\n\n // On creation, check if this component has locally cached values\n const encodedCache = localStorage.getItem(cacheId);\n if (encodedCache) {\n const cache = JSON.parse(encodedCache) as [string, [Entity, unknown][]][];\n const state: { [entity: Entity]: { [key: string]: unknown } } = {};\n\n for (const [key, values] of cache) {\n for (const [entity, value] of values) {\n state[entity] = state[entity] || {};\n state[entity][key] = value;\n }\n }\n\n for (const [entityId, value] of Object.entries(state)) {\n const entity = world.registerEntity({ id: entityId });\n setComponent(component, entity, value as ComponentValue<S, T>);\n }\n\n console.info(\"Loading component\", getComponentName(component), \"from local cache.\");\n }\n\n // Flush the entire component to the local cache every time it updates.\n // Note: this is highly unperformant and should only be used for components that\n // don't update often and don't have many values\n const updateSub = update$.subscribe(() => {\n numUpdates++;\n const encoded = JSON.stringify(\n Object.entries(mapObject(values, (m) => [...m.entries()].map((e) => [getEntityString(e[0]), e[1]]))),\n );\n localStorage.setItem(cacheId, encoded);\n if (numUpdates > 200) {\n console.warn(\n \"Component\",\n getComponentName(component),\n \"was locally cached\",\n numUpdates,\n \"times since\",\n new Date(creation).toLocaleTimeString(),\n \"- the local cache is in an alpha state and should not be used with components that update frequently yet\",\n );\n }\n });\n component.world.registerDisposer(() => updateSub?.unsubscribe());\n\n return component;\n}\n","import { getComponentEntities, getComponentValue } from \"./Component\";\nimport { getEntityString, getEntitySymbol } from \"./Entity\";\nimport { Component, ComponentValue, Entity, EntitySymbol, Indexer, Metadata, Schema } from \"./types\";\n\n/**\n * Create an indexed component from a given component.\n *\n * @remarks\n * An indexed component keeps a \"reverse mapping\" from {@link ComponentValue} to the Set of {@link createEntity Entities} with this value.\n * This adds a performance overhead to modifying component values and a memory overhead since in the worst case there is one\n * Set per entity (if every entity has a different component value).\n * In return the performance for querying for entities with a given component value is close to O(1) (instead of O(#entities) in a regular non-indexed component).\n * As a rule of thumb only components that are added to many entities and are queried with {@link HasValue} a lot should be indexed (eg. the Position component).\n *\n * @dev This could be made more (memory) efficient by using a hash of the component value as key, but would require handling hash collisions.\n *\n * @param component {@link defineComponent Component} to index.\n * @returns Indexed version of the component.\n */\nexport function createIndexer<S extends Schema, M extends Metadata, T = unknown>(\n component: Component<S, M, T>,\n): Indexer<S, M, T> {\n const valueToEntities = new Map<string, Set<EntitySymbol>>();\n\n function getEntitiesWithValue(value: ComponentValue<S, T>) {\n const entities = valueToEntities.get(getValueKey(value));\n return entities ? new Set([...entities].map(getEntityString)) : new Set<Entity>();\n }\n\n function getValueKey(value: ComponentValue<S, T>): string {\n return Object.values(value).join(\"/\");\n }\n\n function add(entity: EntitySymbol, value: ComponentValue<S, T> | undefined) {\n if (!value) return;\n const valueKey = getValueKey(value);\n let entitiesWithValue = valueToEntities.get(valueKey);\n if (!entitiesWithValue) {\n entitiesWithValue = new Set<EntitySymbol>();\n valueToEntities.set(valueKey, entitiesWithValue);\n }\n entitiesWithValue.add(entity);\n }\n\n function remove(entity: EntitySymbol, value: ComponentValue<S, T> | undefined) {\n if (!value) return;\n const valueKey = getValueKey(value);\n const entitiesWithValue = valueToEntities.get(valueKey);\n if (!entitiesWithValue) return;\n entitiesWithValue.delete(entity);\n }\n\n // Initial indexing\n for (const entity of getComponentEntities(component)) {\n const value = getComponentValue(component, entity);\n add(getEntitySymbol(entity), value);\n }\n\n // Keeping index up to date\n const subscription = component.update$.subscribe(({ entity, value }) => {\n // Remove from previous location\n remove(getEntitySymbol(entity), value[1]);\n\n // Add to new location\n add(getEntitySymbol(entity), value[0]);\n });\n\n component.world.registerDisposer(() => subscription?.unsubscribe());\n\n return { ...component, getEntitiesWithValue };\n}\n","import { map, pipe } from \"rxjs\";\nimport { getComponentValue } from \"./Component\";\nimport { UpdateType } from \"./constants\";\nimport { Component, ComponentUpdate, ComponentValue, Entity, Indexer, Schema } from \"./types\";\n\n/**\n * Type guard to infer the TypeScript type of a given component update\n *\n * @param update Component update to infer the type of.\n * @param component {@link defineComponent Component} to check whether the given update corresponds to it.\n * @returns True (+ infered type for `update`) if `update` belongs to `component`. Else false.\n */\nexport function isComponentUpdate<S extends Schema>(\n update: ComponentUpdate,\n component: Component<S>,\n): update is ComponentUpdate<S> {\n return update.component === component;\n}\n\n/**\n * Helper function to create a component update for the current component value of a given entity.\n *\n * @param entity Entity to create the component update for.\n * @param component Component to create the component update for.\n * @returns Component update corresponding to the given entity, the given component and the entity's current component value.\n */\nexport function toUpdate<S extends Schema>(entity: Entity, component: Component<S>) {\n const value = getComponentValue(component, entity);\n return {\n entity,\n component,\n value: [value, undefined],\n type: value == null ? UpdateType.Noop : UpdateType.Enter,\n } as ComponentUpdate<S> & {\n type: UpdateType;\n };\n}\n\n/**\n * Helper function to turn a stream of {@link Entity Entities} into a stream of component updates of the given component.\n * @param component Component to create update stream for.\n * @returns Unary function to be used with RxJS that turns stream of {@link Entity Entities} into stream of component updates.\n */\nexport function toUpdateStream<S extends Schema>(component: Component<S>) {\n return pipe(map((entity: Entity) => toUpdate(entity, component)));\n}\n\n/**\n * Helper function to check whether a given component is indexed.\n * @param c\n * @returns\n */\nexport function isIndexer<S extends Schema>(c: Component<S> | Indexer<S>): c is Indexer<S> {\n return \"getEntitiesWithValue\" in c;\n}\n\n/**\n * Helper function to check whether a given component value is partial or full.\n * @param component\n * @param value\n * @returns\n */\nexport function isFullComponentValue<S extends Schema>(\n component: Component<S>,\n value: Partial<ComponentValue<S>>,\n): value is ComponentValue<S> {\n return Object.keys(component.schema).every((key) => key in value);\n}\n","import { setComponent } from \"./Component\";\nimport { Component, ComponentValue, Entity, EntitySymbol, World } from \"./types\";\n\n/**\n * Register a new entity in the given {@link World} and initialize it with the given {@link ComponentValue}s.\n *\n * @param world World object this entity should be registered in.\n * @param components Array of [{@link defineComponent Component}, {@link ComponentValue}] tuples to be added to this entity.\n * (Use {@link withValue} to generate these tuples with type safety.)\n * @param options Optional: {\n * id: {@link Entity} for this entity. Use this for entities that were created outside of recs.\n * idSuffix: string to be appended to the auto-generated id. Use this for improved readability. Do not use this if the `id` option is provided.\n * }\n * @returns index of this entity in the {@link World}. This {@link Entity} is used to refer to this entity in other recs methods (eg {@link setComponent}).\n * (This is to avoid having to store strings in every component.)\n */\nexport function createEntity(\n world: World,\n components?: [Component, ComponentValue][],\n options?: { id?: string } | { idSuffix?: string },\n): Entity {\n const entity = world.registerEntity(options ?? {});\n\n if (components) {\n for (const [component, value] of components) {\n setComponent(component, entity, value);\n }\n }\n\n return entity;\n}\n\n/*\n * Get the symbol corresponding to an entity's string ID.\n * Entities are represented as symbols internally for memory efficiency.\n */\nexport function getEntitySymbol(entityString: string): EntitySymbol {\n return Symbol.for(entityString) as EntitySymbol;\n}\n\n/**\n * Get the underlying entity string of an entity symbol.\n */\nexport function getEntityString(entity: EntitySymbol): Entity {\n return Symbol.keyFor(entity) as Entity;\n}\n"],"mappings":"AAIO,IAAKA,OACVA,IAAA,qBACAA,IAAA,mBACAA,IAAA,mCACAA,IAAA,mBACAA,IAAA,mCACAA,IAAA,mBACAA,IAAA,mCACAA,IAAA,6BACAA,IAAA,6CACAA,IAAA,6BACAA,IAAA,8CACAA,IAAA,8BACAA,IAAA,8CACAA,IAAA,oBACAA,IAAA,oCACAA,IAAA,8BACAA,IAAA,8CACAA,IAAA,UACAA,IAAA,0BAnBUA,OAAA,IA6BAC,OACVA,IAAA,iBACAA,IAAA,eACAA,IAAA,mBACAA,IAAA,eAJUA,OAAA,IAUCC,EAAgB,CAC3B,GACA,GACA,EACA,EACA,EACA,GACA,EACA,GACA,EACF,ECrDA,OAAS,qBAAAC,EAAmB,QAAAC,MAAY,oBACxC,OAAS,aAAAC,MAAiB,oBAC1B,OAAS,UAAAC,EAAQ,OAAAC,EAAK,WAAAC,MAAe,OCiB9B,SAASC,EACdC,EACkB,CAClB,IAAMC,EAAkB,IAAI,IAE5B,SAASC,EAAqBC,EAA6B,CACzD,IAAMC,EAAWH,EAAgB,IAAII,EAAYF,CAAK,CAAC,EACvD,OAAOC,EAAW,IAAI,IAAI,CAAC,GAAGA,CAAQ,EAAE,IAAIE,CAAe,CAAC,EAAI,IAAI,GACtE,CAEA,SAASD,EAAYF,EAAqC,CACxD,OAAO,OAAO,OAAOA,CAAK,EAAE,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,KACN,YACAxE,EAAiBC,CAAS,EAC1B,qBACAuE,EACA,cACA,IAAI,KAAKC,CAAQ,EAAE,mBAAmB,EACtC,0GACF,CAEJ,CAAC,EACD,OAAAxE,EAAU,MAAM,iBAAiB,IAAM6E,GAAW,YAAY,CAAC,EAExD7E,CACT,CGlgBO,SAASgF,GACdC,EACAC,EACAC,EACQ,CACR,IAAMC,EAASH,EAAM,eAAeE,GAAW,CAAC,CAAC,EAEjD,GAAID,EACF,OAAW,CAACG,EAAWC,CAAK,IAAKJ,EAC/BK,EAAaF,EAAWD,EAAQE,CAAK,EAIzC,OAAOF,CACT,CAMO,SAASI,EAAgBC,EAAoC,CAClE,OAAO,OAAO,IAAIA,CAAY,CAChC,CAKO,SAASC,EAAgBN,EAA8B,CAC5D,OAAO,OAAO,OAAOA,CAAM,CAC7B","names":["Type","UpdateType","OptionalTypes","transformIterator","uuid","mapObject","filter","map","Subject","createIndexer","component","valueToEntities","getEntitiesWithValue","value","entities","getValueKey","getEntityString","add","entity","valueKey","entitiesWithValue","remove","getComponentEntities","getComponentValue","getEntitySymbol","subscription","map","pipe","isComponentUpdate","update","component","toUpdate","entity","value","getComponentValue","toUpdateStream","pipe","map","isIndexer","c","isFullComponentValue","key","getComponentName","component","defineComponent","world","schema","options","id","uuid","values","mapObject","update$","Subject","metadata","transformIterator","getEntityString","createIndexer","setComponent","entity","value","entitySymbol","getEntitySymbol","prevValue","getComponentValue","key","val","updateComponent","initialValue","currentValue","removeComponent","hasComponent","schemaKeys","OptionalTypes","getComponentValueStrict","componentValueEquals","a","b","equals","withValue","getEntitiesWithValue","isIndexer","isFullComponentValue","entities","getComponentEntities","overridableComponent","nonce","overrides","overriddenEntityValues","addOverride","update","setOverriddenComponentValue","removeOverride","affectedEntity","relevantOverrides","o","lastOverride","getOverriddenComponentValue","originalValue","overriddenValue","valueProxyHandler","target","prop","partialValues","valuesProxy","overriddenComponent","filter","e","map","getLocalCacheId","uniqueWorldIdentifier","clearLocalCache","createLocalCache","cacheId","numUpdates","creation","encodedCache","cache","state","entityId","updateSub","encoded","m","createEntity","world","components","options","entity","component","value","setComponent","getEntitySymbol","entityString","getEntityString"]}
1
+ {"version":3,"sources":["../src/constants.ts","../src/Component.ts","../src/Indexer.ts","../src/utils.ts","../src/Entity.ts"],"sourcesContent":["/**\n * Type enum is used to specify value types in {@link ComponentSchema} to be able\n * to access type values in JavaScript in addition to TypeScript type checks.\n */\nexport enum Type {\n Boolean,\n Number,\n OptionalNumber,\n BigInt,\n OptionalBigInt,\n String,\n OptionalString,\n NumberArray,\n OptionalNumberArray,\n BigIntArray,\n OptionalBigIntArray,\n StringArray,\n OptionalStringArray,\n Entity,\n OptionalEntity,\n EntityArray,\n OptionalEntityArray,\n T,\n OptionalT,\n}\n\n/**\n * Used to specify type of {@link ComponentUpdate}.\n * - Enter: Update added a value to an entity that did not have a value before\n * - Exit: Update removed a value from an entity that had a value before\n * - Update: Update changed a value of an entity that already had a value before. Note: the value doesn't need to be different from the previous value.\n * - Noop: Update did nothing (removed a value from an entity that did not have a value)\n */\nexport enum UpdateType {\n Enter,\n Exit,\n Update,\n Noop,\n}\n\n/**\n * Helper constant with all optional {@link Type}s.\n */\nexport const OptionalTypes = [\n Type.OptionalEntity,\n Type.OptionalEntityArray,\n Type.OptionalNumber,\n Type.OptionalNumberArray,\n Type.OptionalBigInt,\n Type.OptionalBigIntArray,\n Type.OptionalString,\n Type.OptionalStringArray,\n Type.OptionalT,\n];\n","import { transformIterator, uuid } from \"@latticexyz/utils\";\nimport { mapObject } from \"@latticexyz/utils\";\nimport { filter, map, Subject } from \"rxjs\";\nimport { OptionalTypes } from \"./constants\";\nimport { createIndexer } from \"./Indexer\";\nimport {\n Component,\n ComponentValue,\n Entity,\n EntitySymbol,\n Indexer,\n Metadata,\n OverridableComponent,\n Override,\n Schema,\n World,\n} from \"./types\";\nimport { isFullComponentValue, isIndexer } from \"./utils\";\nimport { getEntityString, getEntitySymbol } from \"./Entity\";\n\nexport type ComponentMutationOptions = {\n /** Skip publishing this mutation to the component's update stream. Mostly used internally during initial hydration. */\n skipUpdateStream?: boolean;\n};\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction getComponentName(component: Component<any, any, any>) {\n return (\n component.metadata?.componentName ??\n component.metadata?.tableName ??\n component.metadata?.tableId ??\n component.metadata?.contractId ??\n component.id\n );\n}\n\n/**\n * Components contain state indexed by entities and are one of the fundamental building blocks in ECS.\n * Besides containing the state, components expose an rxjs update$ stream, that emits an event any time the value\n * of an entity in this component is updated.\n *\n * @param world {@link World} object this component should be registered onto.\n * @param schema {@link Schema} of component values. Uses Type enum as bridge between typescript types and javascript accessible values.\n * @param options Optional: {\n * id: descriptive id for this component (otherwise an autogenerated id is used),\n * metadata: arbitrary metadata,\n * indexed: if this flag is set, an indexer is applied to this component (see {@link createIndexer})\n * }\n * @returns Component object linked to the provided World\n *\n * @example\n * ```\n * const Position = defineComponent(world, { x: Type.Number, y: Type.Number }, { id: \"Position\" });\n * ```\n */\nexport function defineComponent<S extends Schema, M extends Metadata, T = unknown>(\n world: World,\n schema: S,\n options?: { id?: string; metadata?: M; indexed?: boolean },\n) {\n if (Object.keys(schema).length === 0) throw new Error(\"Component schema must have at least one key\");\n const id = options?.id ?? uuid();\n const values = mapObject(schema, () => new Map());\n const update$ = new Subject();\n const metadata = options?.metadata;\n const entities = () =>\n transformIterator((Object.values(values)[0] as Map<EntitySymbol, unknown>).keys(), getEntityString);\n let component = { values, schema, id, update$, metadata, entities, world } as Component<S, M, T>;\n if (options?.indexed) component = createIndexer(component);\n world.registerComponent(component as Component);\n return component;\n}\n\n/**\n * Set the value for a given entity in a given component.\n *\n * @param component {@link defineComponent Component} to be updated.\n * @param entity {@link Entity} whose value in the given component should be set.\n * @param value Value to set, schema must match the component schema.\n *\n * @example\n * ```\n * setComponent(Position, entity, { x: 1, y: 2 });\n * ```\n */\nexport function setComponent<S extends Schema, T = unknown>(\n component: Component<S, Metadata, T>,\n entity: Entity,\n value: ComponentValue<S, T>,\n options: ComponentMutationOptions = {},\n) {\n const entitySymbol = getEntitySymbol(entity);\n const prevValue = getComponentValue(component, entity);\n for (const [key, val] of Object.entries(value)) {\n if (component.values[key]) {\n component.values[key].set(entitySymbol, val);\n } else {\n const isTableFieldIndex = component.metadata?.tableId && /^\\d+$/.test(key);\n if (!isTableFieldIndex) {\n // If this key looks like a field index from `defineStoreComponents`,\n // we can ignore this value without logging anything.\n //\n // Otherwise, we should let the user know we found undefined data.\n console.warn(\n \"Component definition for\",\n getComponentName(component),\n \"is missing key\",\n key,\n \", ignoring value\",\n val,\n \"for entity\",\n entity,\n \". Existing keys: \",\n Object.keys(component.values),\n );\n }\n }\n }\n if (!options.skipUpdateStream) {\n component.update$.next({ entity, value: [value, prevValue], component });\n }\n}\n\n/**\n * Update the value for a given entity in a given component while keeping the old value of keys not included in the update.\n *\n * @param component {@link defineComponent Component} to be updated.\n * @param entity {@link Entity} whose value in the given component should be updated.\n * @param value Partial value to be set, remaining keys will be taken from the existing component value.\n *\n * @remarks\n * This function fails silently during runtime if a partial value is set for an entity that\n * does not have a component value yet, since then a partial value will be set in the component for this entity.\n *\n * @example\n * ```\n * updateComponent(Position, entity, { x: 1 });\n * ```\n */\nexport function updateComponent<S extends Schema, T = unknown>(\n component: Component<S, Metadata, T>,\n entity: Entity,\n value: Partial<ComponentValue<S, T>>,\n initialValue?: ComponentValue<S, T>,\n options: ComponentMutationOptions = {},\n) {\n const currentValue = getComponentValue(component, entity);\n if (currentValue === undefined) {\n if (initialValue === undefined) {\n throw new Error(`Can't update component ${getComponentName(component)} without a current value or initial value`);\n }\n setComponent(component, entity, { ...initialValue, ...value }, options);\n } else {\n setComponent(component, entity, { ...currentValue, ...value }, options);\n }\n}\n\n/**\n * Remove a given entity from a given component.\n *\n * @param component {@link defineComponent Component} to be updated.\n * @param entity {@link Entity} whose value should be removed from this component.\n */\nexport function removeComponent<S extends Schema, M extends Metadata, T = unknown>(\n component: Component<S, M, T>,\n entity: Entity,\n options: ComponentMutationOptions = {},\n) {\n const entitySymbol = getEntitySymbol(entity);\n const prevValue = getComponentValue(component, entity);\n for (const key of Object.keys(component.values)) {\n component.values[key].delete(entitySymbol);\n }\n if (!options.skipUpdateStream) {\n component.update$.next({ entity, value: [undefined, prevValue], component });\n }\n}\n\n/**\n * Check whether a component contains a value for a given entity.\n *\n * @param component {@link defineComponent Component} to check whether it has a value for the given entity.\n * @param entity {@link Entity} to check whether it has a value in the given component.\n * @returns true if the component contains a value for the given entity, else false.\n */\nexport function hasComponent<S extends Schema, T = unknown>(\n component: Component<S, Metadata, T>,\n entity: Entity,\n): boolean {\n const entitySymbol = getEntitySymbol(entity);\n const map = Object.values(component.values)[0];\n return map.has(entitySymbol);\n}\n\n/**\n * Get the value of a given entity in the given component.\n * Returns undefined if no value or only a partial value is found.\n *\n * @param component {@link defineComponent Component} to get the value from for the given entity.\n * @param entity {@link Entity} to get the value for from the given component.\n * @returns Value of the given entity in the given component or undefined if no value exists.\n */\nexport function getComponentValue<S extends Schema, T = unknown>(\n component: Component<S, Metadata, T>,\n entity: Entity,\n): ComponentValue<S, T> | undefined {\n const value: Record<string, unknown> = {};\n const entitySymbol = getEntitySymbol(entity);\n\n // Get the value of each schema key\n const schemaKeys = Object.keys(component.schema);\n for (const key of schemaKeys) {\n const val = component.values[key].get(entitySymbol);\n if (val === undefined && !OptionalTypes.includes(component.schema[key])) return undefined;\n value[key] = val;\n }\n\n return value as ComponentValue<S, T>;\n}\n\n/**\n * Get the value of a given entity in the given component.\n * Throws an error if no value exists for the given entity in the given component.\n *\n * @param component {@link defineComponent Component} to get the value from for the given entity.\n * @param entity {@link Entity} of the entity to get the value for from the given component.\n * @returns Value of the given entity in the given component.\n *\n * @remarks\n * Throws an error if no value exists in the component for the given entity.\n */\nexport function getComponentValueStrict<S extends Schema, T = unknown>(\n component: Component<S, Metadata, T>,\n entity: Entity,\n): ComponentValue<S, T> {\n const value = getComponentValue(component, entity);\n if (!value) throw new Error(`No value for component ${getComponentName(component)} on entity ${entity}`);\n return value;\n}\n\n/**\n * Compare two {@link ComponentValue}s.\n * `a` can be a partial component value, in which case only the keys present in `a` are compared to the corresponding keys in `b`.\n *\n * @param a Partial {@link ComponentValue} to compare to `b`\n * @param b Component value to compare `a` to.\n * @returns True if `a` equals `b` in the keys present in a or neither `a` nor `b` are defined, else false.\n *\n * @example\n * ```\n * componentValueEquals({ x: 1, y: 2 }, { x: 1, y: 3 }) // returns false because value of y doesn't match\n * componentValueEquals({ x: 1 }, { x: 1, y: 3 }) // returns true because x is equal and y is not present in a\n * ```\n */\nexport function componentValueEquals<S extends Schema, T = unknown>(\n a?: Partial<ComponentValue<S, T>>,\n b?: ComponentValue<S, T>,\n): boolean {\n if (!a && !b) return true;\n if (!a || !b) return false;\n\n let equals = true;\n for (const key of Object.keys(a)) {\n equals = a[key] === b[key];\n if (!equals) return false;\n }\n return equals;\n}\n\n/**\n * Util to create a tuple of a component and value with matching schema.\n * (Used to enforce Typescript type safety.)\n *\n * @param component {@link defineComponent Component} with {@link ComponentSchema} `S`\n * @param value {@link ComponentValue} with {@link ComponentSchema} `S`\n * @returns Tuple `[component, value]`\n */\nexport function withValue<S extends Schema, T = unknown>(\n component: Component<S, Metadata, T>,\n value: ComponentValue<S, T>,\n): [Component<S, Metadata, T>, ComponentValue<S, T>] {\n return [component, value];\n}\n\n/**\n * Get a set of entities that have the given component value in the given component.\n *\n * @param component {@link defineComponent Component} to get entities with the given value from.\n * @param value look for entities with this {@link ComponentValue}.\n * @returns Set with {@link Entity Entities} with the given component value.\n */\nexport function getEntitiesWithValue<S extends Schema>(\n component: Component<S> | Indexer<S>,\n value: Partial<ComponentValue<S>>,\n): Set<Entity> {\n // Shortcut for indexers\n if (isIndexer(component) && isFullComponentValue(component, value)) {\n return component.getEntitiesWithValue(value);\n }\n\n // Trivial implementation for regular components\n const entities = new Set<Entity>();\n for (const entity of getComponentEntities(component)) {\n const val = getComponentValue(component, entity);\n if (componentValueEquals(value, val)) {\n entities.add(entity);\n }\n }\n return entities;\n}\n\n/**\n * Get a set of all entities of the given component.\n *\n * @param component {@link defineComponent Component} to get all entities from\n * @returns Set of all entities in the given component.\n */\nexport function getComponentEntities<S extends Schema, T = unknown>(\n component: Component<S, Metadata, T>,\n): IterableIterator<Entity> {\n return component.entities();\n}\n\n/**\n * An overridable component is a mirror of the source component, with functions to lazily override specific entity values.\n * Lazily override means the values are not actually set to the source component, but the override is only returned if the value is read.\n *\n * - When an override for an entity is added to the component, the override is propagated via the component's `update$` stream.\n * - While an override is set for a specific entity, no updates to the source component for this entity will be propagated to the `update$` stream.\n * - When an override is removed for a specific entity and there are more overrides targeting this entity,\n * the override with the highest nonce will be propagated to the `update$` stream.\n * - When an override is removed for a specific entity and there are no more overrides targeting this entity,\n * the non-overridden underlying component value of this entity will be propagated to the `update$` stream.\n *\n * @param component {@link defineComponent Component} to use as underlying source for the overridable component\n * @returns overridable component\n */\nexport function overridableComponent<S extends Schema, M extends Metadata, T = unknown>(\n component: Component<S, M, T>,\n): OverridableComponent<S, M, T> {\n let nonce = 0;\n\n // Map from OverrideId to Override (to be able to add multiple overrides to the same Entity)\n const overrides = new Map<string, { update: Override<S, T>; nonce: number }>();\n\n // Map from EntitySymbol to current overridden component value\n const overriddenEntityValues = new Map<EntitySymbol, Partial<ComponentValue<S, T>> | null>();\n\n // Update event stream that takes into account overridden entity values\n const update$ = new Subject<{\n entity: Entity;\n value: [ComponentValue<S, T> | undefined, ComponentValue<S, T> | undefined];\n component: Component<S, Metadata, T>;\n }>();\n\n // Add a new override to some entity\n function addOverride(id: string, update: Override<S, T>) {\n overrides.set(id, { update, nonce: nonce++ });\n setOverriddenComponentValue(update.entity, update.value);\n }\n\n // Remove an override from an entity\n function removeOverride(id: string) {\n const affectedEntity = overrides.get(id)?.update.entity;\n overrides.delete(id);\n\n if (affectedEntity == null) return;\n\n // If there are more overries affecting this entity,\n // set the overriddenEntityValue to the last override\n const relevantOverrides = [...overrides.values()]\n .filter((o) => o.update.entity === affectedEntity)\n .sort((a, b) => (a.nonce < b.nonce ? -1 : 1));\n\n if (relevantOverrides.length > 0) {\n const lastOverride = relevantOverrides[relevantOverrides.length - 1];\n setOverriddenComponentValue(affectedEntity, lastOverride.update.value);\n } else {\n setOverriddenComponentValue(affectedEntity, undefined);\n }\n }\n\n // Internal function to get the current overridden value or value of the source component\n function getOverriddenComponentValue(entity: Entity): ComponentValue<S, T> | undefined {\n const originalValue = getComponentValue(component, entity);\n const entitySymbol = getEntitySymbol(entity);\n const overriddenValue = overriddenEntityValues.get(entitySymbol);\n return (originalValue || overriddenValue) && overriddenValue !== null // null is a valid override, in this case return undefined\n ? ({ ...originalValue, ...overriddenValue } as ComponentValue<S, T>)\n : undefined;\n }\n\n const valueProxyHandler: (key: keyof S) => ProxyHandler<(typeof component.values)[typeof key]> = (key: keyof S) => ({\n get(target, prop) {\n // Intercept calls to component.value[key].get(entity)\n if (prop === \"get\") {\n return (entity: EntitySymbol) => {\n const originalValue = target.get(entity);\n const overriddenValue = overriddenEntityValues.get(entity);\n return overriddenValue && overriddenValue[key] != null ? overriddenValue[key] : originalValue;\n };\n }\n\n // Intercept calls to component.value[key].has(entity)\n if (prop === \"has\") {\n return (entity: EntitySymbol) => {\n return target.has(entity) || overriddenEntityValues.has(entity);\n };\n }\n\n // Intercept calls to component.value[key].keys()\n if (prop === \"keys\") {\n return () => new Set([...target.keys(), ...overriddenEntityValues.keys()]).values();\n }\n\n return Reflect.get(target, prop, target);\n },\n });\n\n const partialValues: Partial<Component<S, M, T>[\"values\"]> = {};\n for (const key of Object.keys(component.values) as (keyof S)[]) {\n partialValues[key] = new Proxy(component.values[key], valueProxyHandler(key));\n }\n const valuesProxy = partialValues as Component<S, M, T>[\"values\"];\n\n const overriddenComponent = new Proxy(component, {\n get(target, prop) {\n if (prop === \"addOverride\") return addOverride;\n if (prop === \"removeOverride\") return removeOverride;\n if (prop === \"values\") return valuesProxy;\n if (prop === \"update$\") return update$;\n if (prop === \"entities\")\n return () =>\n new Set([\n ...transformIterator(overriddenEntityValues.keys(), getEntityString),\n ...target.entities(),\n ]).values();\n\n return Reflect.get(target, prop);\n },\n has(target, prop) {\n if (prop === \"addOverride\" || prop === \"removeOverride\") return true;\n return prop in target;\n },\n }) as OverridableComponent<S, M, T>;\n\n // Internal function to set the current overridden component value and emit the update event\n function setOverriddenComponentValue(entity: Entity, value?: Partial<ComponentValue<S, T>> | null) {\n const entitySymbol = getEntitySymbol(entity);\n // Check specifically for undefined - null is a valid override\n const prevValue = getOverriddenComponentValue(entity);\n if (value !== undefined) overriddenEntityValues.set(entitySymbol, value);\n else overriddenEntityValues.delete(entitySymbol);\n update$.next({ entity, value: [getOverriddenComponentValue(entity), prevValue], component: overriddenComponent });\n }\n\n // Channel through update events from the original component if there are no overrides\n component.update$\n .pipe(\n filter((e) => !overriddenEntityValues.get(getEntitySymbol(e.entity))),\n map((update) => ({ ...update, component: overriddenComponent })),\n )\n .subscribe(update$);\n\n return overriddenComponent;\n}\n\nfunction getLocalCacheId(component: Component, uniqueWorldIdentifier?: string): string {\n return `localcache-${uniqueWorldIdentifier}-${component.id}`;\n}\n\nexport function clearLocalCache(component: Component, uniqueWorldIdentifier?: string): void {\n localStorage.removeItem(getLocalCacheId(component, uniqueWorldIdentifier));\n}\n\n// Note: Only proof of concept for now - use this only for component that do not update frequently\nexport function createLocalCache<S extends Schema, M extends Metadata, T = unknown>(\n component: Component<S, M, T>,\n uniqueWorldIdentifier?: string,\n): Component<S, M, T> {\n const { world, update$, values } = component;\n const cacheId = getLocalCacheId(component as Component, uniqueWorldIdentifier);\n let numUpdates = 0;\n const creation = Date.now();\n\n // On creation, check if this component has locally cached values\n const encodedCache = localStorage.getItem(cacheId);\n if (encodedCache) {\n const cache = JSON.parse(encodedCache) as [string, [Entity, unknown][]][];\n const state: { [entity: Entity]: { [key: string]: unknown } } = {};\n\n for (const [key, values] of cache) {\n for (const [entity, value] of values) {\n state[entity] = state[entity] || {};\n state[entity][key] = value;\n }\n }\n\n for (const [entityId, value] of Object.entries(state)) {\n const entity = world.registerEntity({ id: entityId });\n setComponent(component, entity, value as ComponentValue<S, T>);\n }\n\n console.info(\"Loading component\", getComponentName(component), \"from local cache.\");\n }\n\n // Flush the entire component to the local cache every time it updates.\n // Note: this is highly unperformant and should only be used for components that\n // don't update often and don't have many values\n const updateSub = update$.subscribe(() => {\n numUpdates++;\n const encoded = JSON.stringify(\n Object.entries(mapObject(values, (m) => [...m.entries()].map((e) => [getEntityString(e[0]), e[1]]))),\n );\n localStorage.setItem(cacheId, encoded);\n if (numUpdates > 200) {\n console.warn(\n \"Component\",\n getComponentName(component),\n \"was locally cached\",\n numUpdates,\n \"times since\",\n new Date(creation).toLocaleTimeString(),\n \"- the local cache is in an alpha state and should not be used with components that update frequently yet\",\n );\n }\n });\n component.world.registerDisposer(() => updateSub?.unsubscribe());\n\n return component;\n}\n","import { getComponentEntities, getComponentValue } from \"./Component\";\nimport { getEntityString, getEntitySymbol } from \"./Entity\";\nimport { Component, ComponentValue, Entity, EntitySymbol, Indexer, Metadata, Schema } from \"./types\";\n\n/**\n * Create an indexed component from a given component.\n *\n * @remarks\n * An indexed component keeps a \"reverse mapping\" from {@link ComponentValue} to the Set of {@link createEntity Entities} with this value.\n * This adds a performance overhead to modifying component values and a memory overhead since in the worst case there is one\n * Set per entity (if every entity has a different component value).\n * In return the performance for querying for entities with a given component value is close to O(1) (instead of O(#entities) in a regular non-indexed component).\n * As a rule of thumb only components that are added to many entities and are queried with {@link HasValue} a lot should be indexed (eg. the Position component).\n *\n * @dev This could be made more (memory) efficient by using a hash of the component value as key, but would require handling hash collisions.\n *\n * @param component {@link defineComponent Component} to index.\n * @returns Indexed version of the component.\n */\nexport function createIndexer<S extends Schema, M extends Metadata, T = unknown>(\n component: Component<S, M, T>,\n): Indexer<S, M, T> {\n const valueToEntities = new Map<string, Set<EntitySymbol>>();\n\n function getEntitiesWithValue(value: ComponentValue<S, T>) {\n const entities = valueToEntities.get(getValueKey(value));\n return entities ? new Set([...entities].map(getEntityString)) : new Set<Entity>();\n }\n\n function getValueKey(value: ComponentValue<S, T>): string {\n return Object.values(value).join(\"/\");\n }\n\n function add(entity: EntitySymbol, value: ComponentValue<S, T> | undefined) {\n if (!value) return;\n const valueKey = getValueKey(value);\n let entitiesWithValue = valueToEntities.get(valueKey);\n if (!entitiesWithValue) {\n entitiesWithValue = new Set<EntitySymbol>();\n valueToEntities.set(valueKey, entitiesWithValue);\n }\n entitiesWithValue.add(entity);\n }\n\n function remove(entity: EntitySymbol, value: ComponentValue<S, T> | undefined) {\n if (!value) return;\n const valueKey = getValueKey(value);\n const entitiesWithValue = valueToEntities.get(valueKey);\n if (!entitiesWithValue) return;\n entitiesWithValue.delete(entity);\n }\n\n // Initial indexing\n for (const entity of getComponentEntities(component)) {\n const value = getComponentValue(component, entity);\n add(getEntitySymbol(entity), value);\n }\n\n // Keeping index up to date\n const subscription = component.update$.subscribe(({ entity, value }) => {\n // Remove from previous location\n remove(getEntitySymbol(entity), value[1]);\n\n // Add to new location\n add(getEntitySymbol(entity), value[0]);\n });\n\n component.world.registerDisposer(() => subscription?.unsubscribe());\n\n return { ...component, getEntitiesWithValue };\n}\n","import { map, pipe } from \"rxjs\";\nimport { getComponentValue } from \"./Component\";\nimport { UpdateType } from \"./constants\";\nimport { Component, ComponentUpdate, ComponentValue, Entity, Indexer, Schema } from \"./types\";\n\n/**\n * Type guard to infer the TypeScript type of a given component update\n *\n * @param update Component update to infer the type of.\n * @param component {@link defineComponent Component} to check whether the given update corresponds to it.\n * @returns True (+ infered type for `update`) if `update` belongs to `component`. Else false.\n */\nexport function isComponentUpdate<S extends Schema>(\n update: ComponentUpdate,\n component: Component<S>,\n): update is ComponentUpdate<S> {\n return update.component === component;\n}\n\n/**\n * Helper function to create a component update for the current component value of a given entity.\n *\n * @param entity Entity to create the component update for.\n * @param component Component to create the component update for.\n * @returns Component update corresponding to the given entity, the given component and the entity's current component value.\n */\nexport function toUpdate<S extends Schema>(entity: Entity, component: Component<S>) {\n const value = getComponentValue(component, entity);\n return {\n entity,\n component,\n value: [value, undefined],\n type: value == null ? UpdateType.Noop : UpdateType.Enter,\n } as ComponentUpdate<S> & {\n type: UpdateType;\n };\n}\n\n/**\n * Helper function to turn a stream of {@link Entity Entities} into a stream of component updates of the given component.\n * @param component Component to create update stream for.\n * @returns Unary function to be used with RxJS that turns stream of {@link Entity Entities} into stream of component updates.\n */\nexport function toUpdateStream<S extends Schema>(component: Component<S>) {\n return pipe(map((entity: Entity) => toUpdate(entity, component)));\n}\n\n/**\n * Helper function to check whether a given component is indexed.\n * @param c\n * @returns\n */\nexport function isIndexer<S extends Schema>(c: Component<S> | Indexer<S>): c is Indexer<S> {\n return \"getEntitiesWithValue\" in c;\n}\n\n/**\n * Helper function to check whether a given component value is partial or full.\n * @param component\n * @param value\n * @returns\n */\nexport function isFullComponentValue<S extends Schema>(\n component: Component<S>,\n value: Partial<ComponentValue<S>>,\n): value is ComponentValue<S> {\n return Object.keys(component.schema).every((key) => key in value);\n}\n","import { setComponent } from \"./Component\";\nimport { Component, ComponentValue, Entity, EntitySymbol, World } from \"./types\";\n\n/**\n * Register a new entity in the given {@link World} and initialize it with the given {@link ComponentValue}s.\n *\n * @param world World object this entity should be registered in.\n * @param components Array of [{@link defineComponent Component}, {@link ComponentValue}] tuples to be added to this entity.\n * (Use {@link withValue} to generate these tuples with type safety.)\n * @param options Optional: {\n * id: {@link Entity} for this entity. Use this for entities that were created outside of recs.\n * idSuffix: string to be appended to the auto-generated id. Use this for improved readability. Do not use this if the `id` option is provided.\n * }\n * @returns index of this entity in the {@link World}. This {@link Entity} is used to refer to this entity in other recs methods (eg {@link setComponent}).\n * (This is to avoid having to store strings in every component.)\n */\nexport function createEntity(\n world: World,\n components?: [Component, ComponentValue][],\n options?: { id?: string } | { idSuffix?: string },\n): Entity {\n const entity = world.registerEntity(options ?? {});\n\n if (components) {\n for (const [component, value] of components) {\n setComponent(component, entity, value);\n }\n }\n\n return entity;\n}\n\n/*\n * Get the symbol corresponding to an entity's string ID.\n * Entities are represented as symbols internally for memory efficiency.\n */\nexport function getEntitySymbol(entityString: string): EntitySymbol {\n return Symbol.for(entityString) as EntitySymbol;\n}\n\n/**\n * Get the underlying entity string of an entity symbol.\n */\nexport function getEntityString(entity: EntitySymbol): Entity {\n return Symbol.keyFor(entity) as Entity;\n}\n"],"mappings":";AAIO,IAAK,OAAL,kBAAKA,UAAL;AACL,EAAAA,YAAA;AACA,EAAAA,YAAA;AACA,EAAAA,YAAA;AACA,EAAAA,YAAA;AACA,EAAAA,YAAA;AACA,EAAAA,YAAA;AACA,EAAAA,YAAA;AACA,EAAAA,YAAA;AACA,EAAAA,YAAA;AACA,EAAAA,YAAA;AACA,EAAAA,YAAA;AACA,EAAAA,YAAA;AACA,EAAAA,YAAA;AACA,EAAAA,YAAA;AACA,EAAAA,YAAA;AACA,EAAAA,YAAA;AACA,EAAAA,YAAA;AACA,EAAAA,YAAA;AACA,EAAAA,YAAA;AAnBU,SAAAA;AAAA,GAAA;AA6BL,IAAK,aAAL,kBAAKC,gBAAL;AACL,EAAAA,wBAAA;AACA,EAAAA,wBAAA;AACA,EAAAA,wBAAA;AACA,EAAAA,wBAAA;AAJU,SAAAA;AAAA,GAAA;AAUL,IAAM,gBAAgB;AAAA,EAC3B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;;;ACrDA,SAAS,mBAAmB,YAAY;AACxC,SAAS,iBAAiB;AAC1B,SAAS,QAAQ,OAAAC,MAAK,eAAe;;;ACiB9B,SAAS,cACd,WACkB;AAClB,QAAM,kBAAkB,oBAAI,IAA+B;AAE3D,WAASC,sBAAqB,OAA6B;AACzD,UAAM,WAAW,gBAAgB,IAAI,YAAY,KAAK,CAAC;AACvD,WAAO,WAAW,IAAI,IAAI,CAAC,GAAG,QAAQ,EAAE,IAAI,eAAe,CAAC,IAAI,oBAAI,IAAY;AAAA,EAClF;AAEA,WAAS,YAAY,O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