How to use @casual-simulation/causal-trees - 10 common examples

To help you get started, we’ve selected a few @casual-simulation/causal-trees examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github casual-simulation / aux / src / causal-tree-server / ChannelManagerImpl.ts View on Github external
signingKey = privKey;

            let publicKey = await this._crypto.exportKey(pubKey);
            let privateKey = await this._crypto.exportKey(privKey);
            await this._store.putKeys(id, privateKey, publicKey);
            treeWithCrypto = storedTree(
                site(1, {
                    // TODO: Allow storing the crypto algorithm with the keys
                    signatureAlgorithm: 'ECDSA-SHA256-NISTP256',
                    publicKey: publicKey,
                })
            );
            console.log('[ChannelManagerImpl] Keys created.');
        } else {
            console.log('[ChannelManagerImpl] Not generating keys.');
            treeWithCrypto = storedTree(site(1));
        }
        let validator = new AtomValidator(this._crypto);

        return this._factory.create(type, treeWithCrypto, {
            garbageCollect: true,
            validator: validator,
            signingKey: signingKey,
        });
    }
}
github casual-simulation / aux / src / causal-tree-server / ChannelManagerImpl.ts View on Github external
const { added: loaded } = await tree.import(stored);
            sub.unsubscribe();
            console.log(`[ChannelManagerImpl] ${loaded.length} atoms loaded.`);

            if (stored.formatVersion < currentFormatVersion) {
                // Update the stored data but don't delete archived atoms
                console.log(
                    `[ChannelManagerImpl] Updating stored atoms from ${
                        stored.formatVersion
                    } to ${currentFormatVersion}...`
                );
                const exported = tree.export();
                await this._store.put(info.id, exported, false);

                const upgraded = upgrade(exported);
                await this._store.add(info.id, upgraded.weave, false);
            }

            return tree;
        } catch (ex) {
            // TODO: Improve to be able to issue an error to the client
            // saying that the data became corrupted somehow.
            console.warn(
                '[ChannelManagerImpl] Unable to load tree',
                info.id,
                ex
            );
            return await this._createNewTree(info);
        }
    }
github casual-simulation / aux / src / aux-server / aux-web / shared / AppManager.ts View on Github external
channelId = channelId || 'default';

        const user = await this._getCurrentUserOrGuest();
        this._user = user;
        // Always give the user a new ID.
        this._user.id = uuid();

        await this._setCurrentUser(user);
        await this.simulationManager.clear();
        await this.simulationManager.setPrimary(channelId);

        this._userSubject.next(this._user);

        const sim = this.simulationManager.primary;

        sim.progress.updates.pipe(map(remapProgressPercent(0.1, 1))).subscribe(
            (m: ProgressMessage) => {
                this._progress.next(m);
                if (m.error) {
                    this._progress.complete();
                }
            },
            err => console.error(err),
            () => {
                this._progress.next({
                    type: 'progress',
                    message: 'Done.',
                    progress: 1,
                    done: true,
                });
                this._progress.complete();
            }
github casual-simulation / aux / src / aux-server / aux-web / shared / AppManager.ts View on Github external
channelId = channelId || 'default';

        const user = await this._getCurrentUserOrGuest();
        this._user = user;
        // Always give the user a new ID.
        this._user.id = uuid();

        await this._setCurrentUser(user);
        await this.simulationManager.clear();
        await this.simulationManager.setPrimary(channelId);

        this._userSubject.next(this._user);

        const sim = this.simulationManager.primary;

        sim.progress.updates.pipe(map(remapProgressPercent(0.1, 1))).subscribe(
            (m: ProgressMessage) => {
                this._progress.next(m);
                if (m.error) {
                    this._progress.complete();
                }
            },
            err => console.error(err),
            () => {
                this._progress.next({
                    type: 'progress',
                    message: 'Done.',
                    progress: 1,
                    done: true,
                });
                this._progress.complete();
            }
github casual-simulation / aux / src / aux-vm-node / modules / AdminModule.spec.ts View on Github external
channel.remoteEvents.subscribe(e => events.push(...e));

                await channel.sendEvents([
                    {
                        type: 'device',
                        device: device,
                        event: echo('test'),
                    },
                ]);

                // Wait for the async operations to finish
                await Promise.resolve();
                await Promise.resolve();

                expect(events).toEqual([
                    remote(action('test'), {
                        sessionId: device.claims[SESSION_ID_CLAIM],
                    }),
                ]);
            });
        });
github casual-simulation / aux / src / aux-vm-node / managers / AuxChannelManagerImpl.spec.ts View on Github external
};
            const device: DeviceInfo = {
                claims: {
                    [USERNAME_CLAIM]: 'abc',
                    [DEVICE_ID_CLAIM]: 'deviceId',
                    [SESSION_ID_CLAIM]: 'sessionId',
                },
                roles: [ADMIN_ROLE],
            };
            const first = await manager.loadChannel(info);

            let events: DeviceEvent[] = [];
            first.channel.onDeviceEvents.subscribe(e => events.push(...e));

            await manager.sendEvents(first, [
                deviceEvent(
                    device,
                    fileAdded(
                        createFile('testId', {
                            abc: 'def',
                        })
                    )
                ),
            ]);

            // Should map events to DeviceEvent
            expect(events).toEqual([
                {
                    type: 'device',
                    device: device,
                    event: fileAdded(
                        createFile('testId', {
github casual-simulation / aux / src / aux-common / aux-format-2 / AuxCausalTree2.ts View on Github external
const updateTags = (bot: WeaveNode, tags: BotTags) => {
        let result: AuxResult = auxResultIdentity();
        for (let key in tags) {
            let node = findTagNode(bot, key);
            const val = tags[key];
            if (!node) {
                // create new tag
                const tagResult = addAtom(bot.atom, tag(key));

                result = mergeAuxResults(result, tagResult);

                const newAtom = addedAtom(tagResult.results[0]);

                if (!newAtom) {
                    continue;
                }
                node = tree.weave.getNode(newAtom.id) as WeaveNode;
            }

            const currentVal = findValueNode(node);
            if (!currentVal || val !== currentVal.atom.value.value) {
                const valueResult = addAtom(node.atom, value(val));
                result = mergeAuxResults(result, valueResult);

                const newAtom = addedAtom(valueResult.results[0]);
                if (newAtom) {
                    const weaveResult = tree.weave.removeSiblingsBefore(
                        newAtom
github casual-simulation / aux / src / causal-tree-server / CausalRepoServer.spec.ts View on Github external
import { waitAsync } from './test/TestHelpers';
import { Subject } from 'rxjs';
import {
    DeviceInfo,
    deviceInfo,
    remote,
    SESSION_ID_CLAIM,
    device as deviceEvent,
} from '@casual-simulation/causal-trees';

console.log = jest.fn();

const device1Info = deviceInfo('device1', 'device1', 'device1');
const device2Info = deviceInfo('device2', 'device2', 'device2');
const device3Info = deviceInfo('device3', 'device3', 'device3');
const device4Info = deviceInfo('device4', 'device4', 'device4');

describe('CausalRepoServer', () => {
    let server: CausalRepoServer;
    let connections: MemoryConnectionServer;
    let store: MemoryCausalRepoStore;
    let stageStore: MemoryStageStore;

    beforeEach(() => {
        store = new MemoryCausalRepoStore();
        stageStore = new MemoryStageStore();
        connections = new MemoryConnectionServer();
        server = new CausalRepoServer(connections, store, stageStore);
    });

    describe(WATCH_BRANCH, () => {
        it('should load the given branch and send the current atoms', async () => {
github casual-simulation / aux / src / aux-common / aux-format-2 / AuxCausalTree2.spec.ts View on Github external
it('should remove all bots with the given ID', () => {
                const bot1A = atom(atomId('b', 100), null, bot('test2'));
                const tag1A = atom(atomId('b', 101), bot1A, tag('tag1'));
                const val1A = atom(atomId('b', 102), tag1A, value('val1A'));
                const del1A = atom(atomId('b', 103), bot1A, del());

                const bot1B = atom(atomId('b', 110), null, bot('test2'));
                const tag1B = atom(atomId('b', 111), bot1B, tag('tag1'));
                const val1B = atom(atomId('b', 112), tag1B, value('val1B'));

                ({ tree } = applyAtoms(tree, [
                    bot1A,
                    tag1A,
                    val1A,
                    bot1B,
                    tag1B,
                    val1B,
                ]));

                expect(tree.state).toEqual({
                    test: createBot('test', {
                        abc: 'def',
                    }),
                    test2: createBot('test2', {
github casual-simulation / aux / src / aux-common / aux-format-2 / AuxWeaveReducer.spec.ts View on Github external
it('should keep the bot deleted', () => {
                const bot1 = atom(atomId('a', 1), null, bot('test'));
                const delete1A = atom(atomId('a', 2), bot1, {
                    type: 4,
                    extra: 'haha',
                });
                const delete1B = atom(atomId('a', 2), bot1, del());
                state = add(bot1, delete1A, delete1B);

                expect(state).toEqual({});
            });
        });