automerge

This commit is contained in:
Cat /dev/Nulo 2023-04-30 17:39:57 -03:00
commit 2132890875
19 changed files with 1847 additions and 0 deletions

24
.gitignore vendored Normal file
View file

@ -0,0 +1,24 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*
node_modules
dist
dist-ssr
*.local
# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?

3
.vscode/extensions.json vendored Normal file
View file

@ -0,0 +1,3 @@
{
"recommendations": ["svelte.svelte-vscode"]
}

47
README.md Normal file
View file

@ -0,0 +1,47 @@
# Svelte + TS + Vite
This template should help get you started developing with Svelte and TypeScript in Vite.
## Recommended IDE Setup
[VS Code](https://code.visualstudio.com/) + [Svelte](https://marketplace.visualstudio.com/items?itemName=svelte.svelte-vscode).
## Need an official Svelte framework?
Check out [SvelteKit](https://github.com/sveltejs/kit#readme), which is also powered by Vite. Deploy anywhere with its serverless-first approach and adapt to various platforms, with out of the box support for TypeScript, SCSS, and Less, and easily-added support for mdsvex, GraphQL, PostCSS, Tailwind CSS, and more.
## Technical considerations
**Why use this over SvelteKit?**
- It brings its own routing solution which might not be preferable for some users.
- It is first and foremost a framework that just happens to use Vite under the hood, not a Vite app.
This template contains as little as possible to get started with Vite + TypeScript + Svelte, while taking into account the developer experience with regards to HMR and intellisense. It demonstrates capabilities on par with the other `create-vite` templates and is a good starting point for beginners dipping their toes into a Vite + Svelte project.
Should you later need the extended capabilities and extensibility provided by SvelteKit, the template has been structured similarly to SvelteKit so that it is easy to migrate.
**Why `global.d.ts` instead of `compilerOptions.types` inside `jsconfig.json` or `tsconfig.json`?**
Setting `compilerOptions.types` shuts out all other types not explicitly listed in the configuration. Using triple-slash references keeps the default TypeScript setting of accepting type information from the entire workspace, while also adding `svelte` and `vite/client` type information.
**Why include `.vscode/extensions.json`?**
Other templates indirectly recommend extensions via the README, but this file allows VS Code to prompt the user to install the recommended extension upon opening the project.
**Why enable `allowJs` in the TS template?**
While `allowJs: false` would indeed prevent the use of `.js` files in the project, it does not prevent the use of JavaScript syntax in `.svelte` files. In addition, it would force `checkJs: false`, bringing the worst of both worlds: not being able to guarantee the entire codebase is TypeScript, and also having worse typechecking for the existing JavaScript. In addition, there are valid use cases in which a mixed codebase may be relevant.
**Why is HMR not preserving my local component state?**
HMR state preservation comes with a number of gotchas! It has been disabled by default in both `svelte-hmr` and `@sveltejs/vite-plugin-svelte` due to its often surprising behavior. You can read the details [here](https://github.com/rixo/svelte-hmr#svelte-hmr).
If you have state that's important to retain within a component, consider creating an external store which would not be replaced by HMR.
```ts
// store.ts
// An extremely simple external store
import { writable } from 'svelte/store'
export default writable(0)
```

12
index.html Normal file
View file

@ -0,0 +1,12 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Vite + Svelte + TS</title>
</head>
<body>
<div id="app"></div>
<script type="module" src="/src/main.ts"></script>
</body>
</html>

32
package.json Normal file
View file

@ -0,0 +1,32 @@
{
"name": "enprogreso",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "vite build",
"preview": "vite preview",
"check": "svelte-check --tsconfig ./tsconfig.json"
},
"devDependencies": {
"@sveltejs/vite-plugin-svelte": "^2.0.3",
"@tsconfig/svelte": "^4.0.1",
"svelte": "^3.57.0",
"svelte-check": "^2.10.3",
"tslib": "^2.5.0",
"typescript": "^5.0.2",
"vite": "^4.3.2",
"vite-plugin-top-level-await": "^1.3.0",
"vite-plugin-wasm": "^3.2.2"
},
"dependencies": {
"@automerge/automerge": "^2.0.3",
"@automerge/automerge-wasm": "^0.1.26",
"automerge-repo": "https://gitpkg.now.sh/onsetsoftware/automerge-repo/packages/automerge-repo?dummy-release-0.0.51-2",
"automerge-repo-network-broadcastchannel": "^0.0.50",
"automerge-repo-network-localfirstrelay": "https://gitpkg.now.sh/onsetsoftware/automerge-repo/packages/automerge-repo-network-localfirstrelay?0.0.51-dummy-release",
"automerge-repo-network-messagechannel": "^0.0.50",
"automerge-repo-storage-localforage": "^0.0.50"
}
}

1391
pnpm-lock.yaml Normal file

File diff suppressed because it is too large Load diff

22
src/App.svelte Normal file
View file

@ -0,0 +1,22 @@
<script lang="ts">
import { setContextRepo } from "./automerge-repo-svelte";
import { repo } from "./repo";
import Doing from "./lib/Doing.svelte";
setContextRepo(repo);
let rootDocId = localStorage.rootDocId;
if (!rootDocId) {
const handle = repo.create();
localStorage.rootDocId = rootDocId = handle.documentId;
}
</script>
<main>
<div class="card">
<Doing documentId={rootDocId} />
</div>
</main>
<style>
</style>

80
src/app.css Normal file
View file

@ -0,0 +1,80 @@
:root {
font-family: Inter, system-ui, Avenir, Helvetica, Arial, sans-serif;
line-height: 1.5;
font-weight: 400;
color-scheme: light dark;
color: rgba(255, 255, 255, 0.87);
background-color: #242424;
font-synthesis: none;
text-rendering: optimizeLegibility;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
-webkit-text-size-adjust: 100%;
}
a {
font-weight: 500;
color: #646cff;
text-decoration: inherit;
}
a:hover {
color: #535bf2;
}
body {
margin: 0;
display: flex;
place-items: center;
min-width: 320px;
min-height: 100vh;
}
h1 {
font-size: 3.2em;
line-height: 1.1;
}
.card {
padding: 2em;
}
#app {
max-width: 1280px;
margin: 0 auto;
padding: 2rem;
text-align: center;
}
button {
border-radius: 8px;
border: 1px solid transparent;
padding: 0.6em 1.2em;
font-size: 1em;
font-weight: 500;
font-family: inherit;
background-color: #1a1a1a;
cursor: pointer;
transition: border-color 0.25s;
}
button:hover {
border-color: #646cff;
}
button:focus,
button:focus-visible {
outline: 4px auto -webkit-focus-ring-color;
}
@media (prefers-color-scheme: light) {
:root {
color: #213547;
background-color: #ffffff;
}
a:hover {
color: #747bff;
}
button {
background-color: #f9f9f9;
}
}

View file

@ -0,0 +1,38 @@
import type { Doc, ChangeFn } from "@automerge/automerge";
import { setContext, getContext } from "svelte";
import { writable, type Readable, readable } from "svelte/store";
import {
Repo,
type DocumentId,
type DocHandlePatchPayload,
} from "automerge-repo";
const ContextRepoKey = Symbol("svelte-context-automerge-repo");
export function getContextRepo(): Repo {
return getContext<Repo>(ContextRepoKey);
}
export function setContextRepo(repo: Repo) {
setContext(ContextRepoKey, repo);
}
export function document<T>(documentId: DocumentId) {
const repo = getContextRepo();
const handle = repo.find<T>(documentId);
const { subscribe } = readable<Doc<T>>(null, (set) => {
const onPatch = (h: DocHandlePatchPayload<T>) => {
set(h.after);
};
handle.addListener("patch", onPatch);
return () => handle.removeListener("patch", onPatch);
});
return {
subscribe,
change: (fn: ChangeFn<T>) => {
handle.change(fn);
},
};
}

10
src/lib/Counter.svelte Normal file
View file

@ -0,0 +1,10 @@
<script lang="ts">
let count: number = 0
const increment = () => {
count += 1
}
</script>
<button on:click={increment}>
count is {count}
</button>

59
src/lib/Doing.svelte Normal file
View file

@ -0,0 +1,59 @@
<script lang="ts">
import { type DocumentId } from "automerge-repo";
import { document } from "../automerge-repo-svelte";
export let documentId: DocumentId;
interface Person {
doing?: {
description: string;
started: number;
}[];
done?: {
description: string;
started: number;
finished: number;
}[];
}
const doc = document<Person>(documentId);
const start = (description: string) => {
doc.change((p) => {
if (!p.doing) (p as Person).doing = [];
p.doing.insertAt(0, { description, started: new Date().getTime() });
});
};
const finish = (index: number) => {
doc.change((p) => {
const thing = p.doing[index];
p.doing.deleteAt(index);
if (!p.done) (p as Person).done = [];
p.done.push({ ...thing, finished: new Date().getTime() });
});
};
$: console.debug($doc?.doing[0]);
</script>
{#if $doc?.doing?.length > 0}
{#each $doc.doing as doing, index}
<div>
<span>{doing.description} </span>
<button on:click={() => finish(index)}>Terminar</button>
</div>
{/each}
{:else}
<form
on:submit|preventDefault={(e) => start(e.currentTarget.description.value)}
>
<input type="text" placeholder="¿Que estás haciendo?" name="description" />
<button>Empezar</button>
</form>
{/if}
{#if $doc?.done?.length > 0}
<h2>Ya hecho</h2>
<ul>
{#each $doc?.done as thing}
<li>{thing.description}</li>
{/each}
</ul>
{/if}

8
src/main.ts Normal file
View file

@ -0,0 +1,8 @@
import './app.css'
import App from './App.svelte'
const app = new App({
target: document.getElementById('app'),
})
export default app

15
src/repo.ts Normal file
View file

@ -0,0 +1,15 @@
import { Repo } from "automerge-repo";
import { BroadcastChannelNetworkAdapter } from "automerge-repo-network-broadcastchannel";
import { LocalForageStorageAdapter } from "automerge-repo-storage-localforage";
import { LocalFirstRelayNetworkAdapter } from "automerge-repo-network-localfirstrelay/src/index";
// import { MessageChannelNetworkAdapter } from "automerge-repo-network-messagechannel";
export const repo = new Repo({
network: [
// new MessageChannelNetworkAdapter(),
new BroadcastChannelNetworkAdapter(),
new LocalFirstRelayNetworkAdapter("wss://localfirstrelay.nulo.ar"),
// new BrowserWebSocketClientAdapter("ws://localhost:3030"),
],
storage: new LocalForageStorageAdapter(),
});

2
src/vite-env.d.ts vendored Normal file
View file

@ -0,0 +1,2 @@
/// <reference types="svelte" />
/// <reference types="vite/client" />

42
src/ystore.old Normal file
View file

@ -0,0 +1,42 @@
import { syncedStore, getYjsDoc } from "@syncedstore/core";
import { WebrtcProvider } from "y-webrtc";
import { svelteSyncedStore } from "@syncedstore/svelte";
import { IndexeddbPersistence } from "y-indexeddb";
type DoingThing = { description: string; start: number };
export const synced = syncedStore<{
doing: { thing?: DoingThing };
}>({ doing: {} });
export const store = svelteSyncedStore(synced);
// Get the Yjs document and sync automatically using y-webrtc
const doc = getYjsDoc(synced);
// setup p2p
const credsReq = fetch(
"https://nulo.metered.live/api/v1/turn/credentials?apiKey=205de2914a8564e2efa19a7d7f299a95e574"
).then((res) => res.json());
const docId = "uwjwifsighsglks";
const webrtcProvider = new WebrtcProvider(docId, doc, {
signaling: [
"wss://webrtc-signaling.schreiben.nulo.ar",
"wss://y-webrtc-eu.fly.dev",
],
});
credsReq.then((iceServers) => {
// change the default for future connections
webrtcProvider.peerOpts.config = { iceServers };
if (!webrtcProvider.room?.webrtcConns) return;
// change the configuration in current connections
for (const conn of webrtcProvider.room?.webrtcConns?.values()) {
const pc: RTCPeerConnection = conn.peer._pc;
pc.setConfiguration({
iceServers,
});
}
});
const idbProvider = new IndexeddbPersistence(docId, doc);

7
svelte.config.js Normal file
View file

@ -0,0 +1,7 @@
import { vitePreprocess } from '@sveltejs/vite-plugin-svelte'
export default {
// Consult https://svelte.dev/docs#compile-time-svelte-preprocess
// for more information about preprocessors
preprocess: vitePreprocess(),
}

20
tsconfig.json Normal file
View file

@ -0,0 +1,20 @@
{
"extends": "@tsconfig/svelte/tsconfig.json",
"compilerOptions": {
"target": "ESNext",
"useDefineForClassFields": true,
"module": "ESNext",
"resolveJsonModule": true,
/**
* Typecheck JS in `.svelte` and `.js` files by default.
* Disable checkJs if you'd like to use dynamic types in JS.
* Note that setting allowJs false does not prevent the use
* of JS in `.svelte` files.
*/
"allowJs": true,
"checkJs": true,
"isolatedModules": true
},
"include": ["src/**/*.d.ts", "src/**/*.ts", "src/**/*.js", "src/**/*.svelte"],
"references": [{ "path": "./tsconfig.node.json" }]
}

9
tsconfig.node.json Normal file
View file

@ -0,0 +1,9 @@
{
"compilerOptions": {
"composite": true,
"skipLibCheck": true,
"module": "ESNext",
"moduleResolution": "bundler"
},
"include": ["vite.config.ts"]
}

26
vite.config.ts Normal file
View file

@ -0,0 +1,26 @@
import { defineConfig } from "vite";
import { svelte } from "@sveltejs/vite-plugin-svelte";
import wasm from "vite-plugin-wasm";
import topLevelAwait from "vite-plugin-top-level-await";
// https://github.com/automerge/automerge-repo/blob/9b5aa0788996c64e7c11c9f8bc00a55b38afb7dd/packages/automerge-repo-demo-counter-svelte/vite.config.ts
// https://vitejs.dev/config/
export default defineConfig({
plugins: [wasm(), topLevelAwait(), svelte()],
worker: {
format: "es",
plugins: [wasm(), topLevelAwait()],
},
optimizeDeps: {
// This is necessary because otherwise `vite dev` includes two separate
// versions of the JS wrapper. This causes problems because the JS
// wrapper has a module level variable to track JS side heap
// allocations, and initializing this twice causes horrible breakage
exclude: [
"@automerge/automerge-wasm",
"@automerge/automerge-wasm/bundler/bindgen_bg.wasm",
"@syntect/wasm",
],
},
});