Compare commits

..

71 Commits

Author SHA1 Message Date
Guido D'Orsi
7f07f7e049 Merge pull request #1294 from boorad/authv2-web-example-refactoring
feat: update web examples to new auth system
2025-01-29 10:31:25 +01:00
Guido D'Orsi
b22589bbad test: add integration tests for the websocket peer 2025-01-29 10:26:09 +01:00
Guido D'Orsi
be144adeee chore: rename onSuccessCalles to isFirstMessage and add a test 2025-01-29 10:17:59 +01:00
Brad Anderson
513619b04e feat: update web examples to new auth system 2025-01-28 23:13:44 -05:00
Guido D'Orsi
81f6a75aac chore: add comment 2025-01-28 20:11:52 +01:00
Guido D'Orsi
913d03de75 feat: update the RN example apps with the new Auth system 2025-01-28 19:34:56 +01:00
Guido D'Orsi
2d0172d839 feat: update the React Native packages with the new auth system 2025-01-28 19:34:04 +01:00
Guido D'Orsi
27d46641e3 feat: unify React Native and Jazz Tools DemoAuth users management 2025-01-28 19:32:55 +01:00
Guido D'Orsi
1014816d79 feat: move WebSocketPeerWithReconnection to jazz-tools 2025-01-28 19:09:34 +01:00
Guido D'Orsi
441194acb7 feat: add onSuccess hook and close the WebSocket on error 2025-01-28 19:06:35 +01:00
Guido D'Orsi
c9bea7200f feat: rename jazz-browser-clerk-auth in jazz-clerk-auth and update jazz-react-native-auth-clerk 2025-01-28 19:05:43 +01:00
Guido D'Orsi
6ada48d57a chore: remove unused imports 2025-01-28 18:05:55 +01:00
Guido D'Orsi
8fa978df21 fix: initialize the anonymous storage only if newAccountProps is not provided 2025-01-28 16:27:25 +01:00
Guido D'Orsi
df7356fd24 chore: cleanup and small fix on websocket enable/disable 2025-01-28 14:45:58 +01:00
Guido D'Orsi
153fa4ce44 fix: invalidate context when localOnly is updated 2025-01-28 12:19:46 +01:00
Guido D'Orsi
6105bd2c88 test: cover createContext and ContextManager 2025-01-28 12:09:48 +01:00
Guido D'Orsi
c06d63eec1 fix: align passphrase auth with the current auth flow 2025-01-28 10:54:47 +01:00
Guido D'Orsi
4ee7359370 test: PassphraseAuth 2025-01-27 22:25:22 +01:00
Guido D'Orsi
7b5c47b377 test: cover DemoAuth 2025-01-27 22:12:42 +01:00
Guido D'Orsi
7ad57e88f3 test: add tests on the react-core auth hooks 2025-01-27 21:59:06 +01:00
Guido D'Orsi
c181e55557 feat: make auth state platform agnostic 2025-01-27 19:27:21 +01:00
Guido D'Orsi
7e0cd721e6 Merge remote-tracking branch 'origin/main' into authv2 2025-01-27 15:51:33 +01:00
Guido D'Orsi
4d01cbae03 Merge pull request #1288 from garden-co/sync-tests-improvements
Improve sync tests and add some utils to track the messages exchanges
2025-01-27 15:47:03 +01:00
Guido D'Orsi
13f6389559 chore: format text 2025-01-27 15:38:34 +01:00
Guido D'Orsi
f6ea9bcc50 test: remove flaky test 2025-01-27 15:37:02 +01:00
Guido D'Orsi
f6f2766eac test: cover the initial messages exchanges 2025-01-27 15:35:35 +01:00
Guido D'Orsi
f8f63bface test: simplify sync tests with the test sync pattern 2025-01-27 15:35:34 +01:00
Guido D'Orsi
5ec561fec4 Merge pull request #1281 from garden-co/changeset-release/main
Version Packages
2025-01-27 11:07:35 +01:00
github-actions[bot]
277787cbd2 Version Packages 2025-01-27 10:03:17 +00:00
Guido D'Orsi
dda4336721 Merge pull request #1252 from garden-co/fix-ts-symbol-error
fix(typescript): replace private symbols with prefixed strings
2025-01-27 11:01:37 +01:00
Guido D'Orsi
59ddff40ab Merge pull request #1270 from garden-co/authv2-clerk
feat: improve the clerk integration
2025-01-27 11:01:13 +01:00
Guido D'Orsi
064d19b48c chore: move jazz-react-core version up to 0.9.19 2025-01-27 09:27:18 +01:00
Guido D'Orsi
3ea269f4d8 chore: package json formatting 2025-01-27 09:27:00 +01:00
Guido D'Orsi
c4b8befe27 Merge pull request #1278 from garden-co/changeset-release/main
Version Packages
2025-01-27 09:21:29 +01:00
Guido D'Orsi
06f667ef2a Merge pull request #1280 from doingandlearning/patch-2
Update README.md
2025-01-27 09:21:16 +01:00
github-actions[bot]
bac3cc7bf8 Version Packages 2025-01-27 08:17:07 +00:00
Guido D'Orsi
6ad0a9f886 chore: changeset 2025-01-27 09:15:44 +01:00
Kevin Cunningham
9b12932b66 Update README.md 2025-01-26 09:10:49 +00:00
Guido D'Orsi
cb75cc62b2 chore: exclude storage from the propsChanged check 2025-01-25 00:38:09 +01:00
Guido D'Orsi
b141f6a62f fix: double context creation on React 2025-01-25 00:36:58 +01:00
Guido D'Orsi
4a251a528c feat: improve the clerk integration 2025-01-24 19:37:59 +01:00
Guido D'Orsi
f8b6119996 feat: translate isAnonymous checks into isAuthenticated and add tests 2025-01-24 16:15:18 +01:00
Guido D'Orsi
a7c90f749e feat: move the context manager into jazz-tools 2025-01-24 15:30:43 +01:00
Guido D'Orsi
b01cc1fe9d fix(typescript): fix type error on ItemsSym 2025-01-23 19:21:29 +01:00
Guido D'Orsi
3a6e34589f feat: defaultName and better props tracking 2025-01-23 18:34:37 +01:00
Guido D'Orsi
a1d512d9d7 Merge remote-tracking branch 'origin/main' into authv2 2025-01-23 17:28:14 +01:00
Guido D'Orsi
51bf6b7fdc Merge pull request #1223 from garden-co/auth-flow-rewrite
Auth flow rewrite
2025-01-23 17:26:53 +01:00
Guido D'Orsi
b5826fc0a5 Merge pull request #1176 from garden-co/user-onboarding-upgrade
feat: zero-setup auth, anonymous user upgrade and localOnly sync
2025-01-23 17:22:50 +01:00
Guido D'Orsi
becdd2f451 test(music-player): fix e2e tests 2025-01-23 17:12:47 +01:00
Guido D'Orsi
3b20bf354f feat: migrate svelte 2025-01-23 16:58:44 +01:00
Guido D'Orsi
fff7fe934b feat: update Vue 2025-01-23 12:55:12 +01:00
Guido D'Orsi
4c8d128eee feat: auth flow rewrite 2025-01-22 18:04:45 +01:00
Guido D'Orsi
df106ca680 test: fix create image test 2025-01-21 11:15:18 +01:00
Guido D'Orsi
c58f93b597 Merge remote-tracking branch 'origin/main' into user-onboarding-upgrade 2025-01-21 10:49:01 +01:00
Guido D'Orsi
3f2a0ead1b fix: self-review fixes 2025-01-21 10:34:42 +01:00
Guido D'Orsi
c9e6d2998e feat: improve the jazz-react provider 2025-01-20 20:10:18 +01:00
Guido D'Orsi
40634c6ec1 chore: update lockfile 2025-01-20 12:41:08 +01:00
Guido D'Orsi
8bc758ce95 Merge remote-tracking branch 'origin/main' into user-onboarding-upgrade 2025-01-20 12:32:25 +01:00
Guido D'Orsi
73079ca1b7 test: update e2e tests 2025-01-17 22:57:45 +01:00
Guido D'Orsi
c36f19a97f fix: fix imports & and tests on createJazzBrowserContext 2025-01-17 19:28:38 +01:00
Guido D'Orsi
109338923a chore: update lockfile 2025-01-17 18:18:57 +01:00
Guido D'Orsi
f4c2501b06 chore: move auth hook in useInJazzAuth 2025-01-17 18:18:24 +01:00
Guido D'Orsi
9161229474 chore: revert the changes on the todo example 2025-01-17 18:17:46 +01:00
Guido D'Orsi
265f2f40bf fix: fix passkey auth cancelation and add tests 2025-01-17 17:50:35 +01:00
Guido D'Orsi
d2935ac2ae feat: make clerk auth compatible with passkeys 2025-01-17 14:49:25 +01:00
Guido D'Orsi
aaf00b8a20 feat: update starter example with anonymous auth 2025-01-17 14:49:25 +01:00
Guido D'Orsi
f9c6a49d2a feat: onboarding auth on todo example 2025-01-17 14:49:25 +01:00
Guido D'Orsi
2f54a48a3d feat: make auth code disappear from the React setup 2025-01-17 14:49:25 +01:00
Guido D'Orsi
be4dd0a787 feat: centralize auth secret management 2025-01-17 14:49:25 +01:00
Guido D'Orsi
f3f072e7cf feat: improve login/signup code and better UX on the music player auth 2025-01-17 14:49:24 +01:00
Guido D'Orsi
a6270bf552 feat: add onboarding user upgrade to Passkey and Clerk auth 2025-01-17 14:49:24 +01:00
262 changed files with 11867 additions and 5758 deletions

View File

@@ -1,5 +1,24 @@
# chat-rn-clerk
## 1.0.61
### Patch Changes
- Updated dependencies [b01cc1f]
- jazz-tools@0.9.20
- jazz-react-native@0.9.20
- jazz-react-native-auth-clerk@0.9.20
- jazz-react-native-media-images@0.9.20
## 1.0.60
### Patch Changes
- jazz-react-native@0.9.19
- jazz-react-native-auth-clerk@0.9.19
- jazz-tools@0.9.19
- jazz-react-native-media-images@0.9.19
## 1.0.59
### Patch Changes

View File

@@ -1,9 +1,9 @@
import { Redirect, Stack } from "expo-router";
import { useIsAuthenticated } from "jazz-react-native";
import React from "react";
import { useAuth } from "../../src/auth-context";
export default function HomeLayout() {
const { isAuthenticated } = useAuth();
const isAuthenticated = useIsAuthenticated();
if (isAuthenticated) {
return <Redirect href={"/chat"} />;

View File

@@ -1,8 +1,8 @@
import { Redirect, Stack } from "expo-router";
import { useAuth } from "../../src/auth-context";
import { useIsAuthenticated } from "jazz-react-native";
export default function UnAuthenticatedLayout() {
const { isAuthenticated } = useAuth();
const isAuthenticated = useIsAuthenticated();
if (isAuthenticated) {
return <Redirect href={"/chat"} />;

View File

@@ -20,10 +20,15 @@ export default function ChatScreen() {
const navigation = useNavigation();
const { user } = useUser();
function handleLogOut() {
logOut();
router.navigate("/");
}
useLayoutEffect(() => {
navigation.setOptions({
headerTitle: "Chat",
headerRight: () => <Button onPress={logOut} title="Logout" />,
headerRight: () => <Button onPress={handleLogOut} title="Logout" />,
});
}, [navigation]);

View File

@@ -1,7 +1,7 @@
{
"name": "chat-rn-clerk",
"main": "index.js",
"version": "1.0.59",
"version": "1.0.61",
"scripts": {
"build": "expo export -p ios",
"start": "expo start",

View File

@@ -1,49 +1,17 @@
import { useClerk, useUser } from "@clerk/clerk-expo";
import { JazzProvider, setupKvStore } from "jazz-react-native";
import { useJazzClerkAuth } from "jazz-react-native-auth-clerk";
import React, { createContext, PropsWithChildren, useContext } from "react";
import { Text, View } from "react-native";
const AuthContext = createContext<{
isAuthenticated: boolean;
isLoading: boolean;
}>({
isAuthenticated: false,
isLoading: true,
});
export function useAuth() {
return useContext(AuthContext);
}
const kvStore = setupKvStore();
import { useClerk } from "@clerk/clerk-expo";
import { JazzProviderWithClerk } from "jazz-react-native-auth-clerk";
import React, { PropsWithChildren } from "react";
export function JazzAndAuth({ children }: PropsWithChildren) {
const { isSignedIn, isLoaded: isClerkLoaded } = useUser();
const clerk = useClerk();
const [auth, state] = useJazzClerkAuth(clerk, kvStore);
const isAuthenticated = Boolean(isSignedIn && isClerkLoaded && auth);
return (
<AuthContext.Provider
value={{ isAuthenticated, isLoading: !isClerkLoaded || !auth }}
<JazzProviderWithClerk
clerk={clerk}
storage="sqlite"
peer="wss://cloud.jazz.tools/?key=chat-rn-clerk-example-jazz@garden.co"
>
{state?.errors?.length > 0 &&
state.errors.map((error) => (
<View key={error}>
<Text style={{ color: "red" }}>{error}</Text>
</View>
))}
{auth && clerk.user ? (
<JazzProvider
auth={auth}
storage="sqlite"
peer="wss://cloud.jazz.tools/?key=chat-rn-clerk-example-jazz@garden.co"
>
{children}
</JazzProvider>
) : (
children
)}
</AuthContext.Provider>
{children}
</JazzProviderWithClerk>
);
}

View File

@@ -1,5 +1,20 @@
# chat-rn
## 1.0.58
### Patch Changes
- Updated dependencies [b01cc1f]
- jazz-tools@0.9.20
- jazz-react-native@0.9.20
## 1.0.57
### Patch Changes
- jazz-react-native@0.9.19
- jazz-tools@0.9.19
## 1.0.56
### Patch Changes

View File

@@ -1,6 +1,6 @@
{
"name": "chat-rn",
"version": "1.0.56",
"version": "1.0.58",
"main": "index.js",
"scripts": {
"build": "expo export -p ios",

View File

@@ -9,7 +9,7 @@ import * as Linking from "expo-linking";
import React, { StrictMode, useEffect, useState } from "react";
import HandleInviteScreen from "./invite";
import { DemoAuthBasicUI, JazzProvider, useDemoAuth } from "jazz-react-native";
import { JazzProvider } from "jazz-react-native";
import ChatScreen from "./chat";
const Stack = createNativeStackNavigator();
@@ -28,7 +28,6 @@ const linking = {
};
function App() {
const [auth, state] = useDemoAuth();
const [initialRoute, setInitialRoute] = useState<
"ChatScreen" | "HandleInviteScreen"
>("ChatScreen");
@@ -43,14 +42,9 @@ function App() {
});
}, []);
if (!auth) {
return null;
}
return (
<StrictMode>
<JazzProvider
auth={auth}
storage="sqlite"
peer="wss://cloud.jazz.tools/?key=chat-rn-example-jazz@garden.co"
>
@@ -69,9 +63,6 @@ function App() {
</Stack.Navigator>
</NavigationContainer>
</JazzProvider>
{state.state !== "signedIn" ? (
<DemoAuthBasicUI appName="Jazz Chat" state={state} />
) : null}
</StrictMode>
);
}

View File

@@ -1,6 +1,6 @@
import clsx from "clsx";
import * as Clipboard from "expo-clipboard";
import { Group, ID } from "jazz-tools";
import { Group, ID, Profile } from "jazz-tools";
import { useEffect, useState } from "react";
import React, {
Button,
@@ -22,10 +22,16 @@ export default function ChatScreen({ navigation }: { navigation: any }) {
const [chatId, setChatId] = useState<ID<Chat>>();
const loadedChat = useCoState(Chat, chatId, [{}]);
const [message, setMessage] = useState("");
const profile = useCoState(Profile, me._refs.profile?.id, {});
function handleLogOut() {
setChatId(undefined);
logOut();
}
useEffect(() => {
navigation.setOptions({
headerRight: () => <Button onPress={logOut} title="Logout" />,
headerRight: () => <Button onPress={handleLogOut} title="Logout" />,
headerLeft: () =>
loadedChat ? (
<Button
@@ -131,6 +137,18 @@ export default function ChatScreen({ navigation }: { navigation: any }) {
<View className="flex flex-col h-full">
{!loadedChat ? (
<View className="flex flex-col h-full items-center justify-center">
<Text className="text-m font-bold mb-6">Username</Text>
<TextInput
className="rounded h-12 p-2 mb-12 w-40 border border-gray-200 block"
value={profile?.name ?? ""}
onChangeText={(value) => {
if (profile) {
profile.name = value;
}
}}
textAlignVertical="center"
onSubmitEditing={sendMessage}
/>
<TouchableOpacity
onPress={createChat}
className="bg-blue-500 p-4 rounded-md"

View File

@@ -1,5 +1,22 @@
# chat-vue
## 0.0.45
### Patch Changes
- Updated dependencies [b01cc1f]
- jazz-tools@0.9.20
- jazz-browser@0.9.20
- jazz-vue@0.9.20
## 0.0.44
### Patch Changes
- jazz-browser@0.9.19
- jazz-tools@0.9.19
- jazz-vue@0.9.19
## 0.0.43
### Patch Changes

View File

@@ -1,6 +1,6 @@
{
"name": "chat-vue",
"version": "0.0.43",
"version": "0.0.45",
"private": true,
"type": "module",
"scripts": {

View File

@@ -4,29 +4,35 @@ import App from "./App.vue";
import "./index.css";
import router from "./router";
const AuthScreen = defineComponent({
name: "AuthScreen",
setup() {
const auth = useDemoAuth();
return () => [
auth.value.state === "anonymous"
? h(DemoAuthBasicUI, {
appName: "Jazz Vue Chat",
auth,
})
: h(App),
];
},
});
const RootComponent = defineComponent({
name: "RootComponent",
setup() {
const { authMethod, state } = useDemoAuth();
return () => [
return () =>
h(
JazzProvider,
{
auth: authMethod.value,
peer: "wss://cloud.jazz.tools/?key=chat-example-jazz@garden.co",
peer: "wss://cloud.jazz.tools/?key=vue-chat-example-jazz@garden.co",
},
{
default: () => h(App),
default: () => h(AuthScreen),
},
),
state.state !== "signedIn" &&
h(DemoAuthBasicUI, {
appName: "Jazz Chat",
state,
}),
];
);
},
});

View File

@@ -1,5 +1,22 @@
# jazz-example-chat
## 0.0.141
### Patch Changes
- Updated dependencies [b01cc1f]
- jazz-tools@0.9.20
- jazz-browser-media-images@0.9.20
- jazz-react@0.9.20
## 0.0.140
### Patch Changes
- jazz-react@0.9.19
- jazz-tools@0.9.19
- jazz-browser-media-images@0.9.19
## 0.0.139
### Patch Changes

View File

@@ -1,7 +1,7 @@
{
"name": "jazz-example-chat",
"private": true,
"version": "0.0.139",
"version": "0.0.141",
"type": "module",
"scripts": {
"dev": "vite",

View File

@@ -1,19 +1,11 @@
import { DemoAuthBasicUI, JazzProvider, useDemoAuth } from "jazz-react";
import { JazzProvider } from "jazz-react";
export function JazzAndAuth({ children }: { children: React.ReactNode }) {
const [auth, state] = useDemoAuth();
return (
<>
<JazzProvider
auth={auth}
peer="wss://cloud.jazz.tools/?key=chat-example-jazz@garden.co"
>
{children}
</JazzProvider>
{state.state !== "signedIn" && (
<DemoAuthBasicUI appName="Jazz Chat" state={state} />
)}
</>
<JazzProvider
localOnly="anonymous"
peer="wss://cloud.jazz.tools/?key=chat-example-jazz@garden.co"
>
{children}
</JazzProvider>
);
}

View File

@@ -1,5 +1,22 @@
# minimal-auth-clerk
## 0.0.40
### Patch Changes
- Updated dependencies [b01cc1f]
- jazz-tools@0.9.20
- jazz-react@0.9.20
- jazz-react-auth-clerk@0.9.20
## 0.0.39
### Patch Changes
- jazz-react@0.9.19
- jazz-react-auth-clerk@0.9.19
- jazz-tools@0.9.19
## 0.0.38
### Patch Changes

View File

@@ -1,7 +1,7 @@
{
"name": "clerk",
"private": true,
"version": "0.0.38",
"version": "0.0.40",
"type": "module",
"scripts": {
"dev": "vite",
@@ -13,7 +13,7 @@
"dependencies": {
"@clerk/clerk-react": "^5.4.1",
"jazz-react": "workspace:*",
"jazz-react-auth-clerk": "workspace:0.9.18",
"jazz-react-auth-clerk": "workspace:0.9.20",
"jazz-tools": "workspace:*",
"react": "^18.3.1",
"react-dom": "^18.3.1"

View File

@@ -1,13 +1,25 @@
import { useAccount } from "jazz-react";
import { SignInButton } from "@clerk/clerk-react";
import { useAccount, useIsAuthenticated } from "jazz-react";
function App() {
const { me, logOut } = useAccount();
const isAuthenticated = useIsAuthenticated();
if (isAuthenticated) {
return (
<div className="container">
<h1>You're logged in</h1>
<p>Welcome back, {me?.profile?.name}</p>
<button onClick={() => logOut()}>Logout</button>
</div>
);
}
return (
<div className="container">
<h1>You're logged in</h1>
<p>Welcome back, {me?.profile?.name}</p>
<button onClick={() => logOut()}>Logout</button>
<h1>You're not logged in</h1>
<SignInButton />
</div>
);
}

View File

@@ -62,7 +62,7 @@ button {
}
.container {
max-width: 200px;
max-width: 400px;
margin: 0 auto;
padding: 0 1rem;
display: flex;

View File

@@ -1,10 +1,9 @@
import { ClerkProvider, SignInButton, useClerk } from "@clerk/clerk-react";
import { useJazzClerkAuth } from "jazz-react-auth-clerk";
import { ClerkProvider, useClerk } from "@clerk/clerk-react";
import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import App from "./App.tsx";
import "./index.css";
import { JazzProvider } from "jazz-react";
import { JazzProviderWithClerk } from "jazz-react-auth-clerk";
// Import your publishable key
const PUBLISHABLE_KEY = import.meta.env.VITE_CLERK_PUBLISHABLE_KEY;
@@ -13,35 +12,26 @@ if (!PUBLISHABLE_KEY) {
throw new Error("Add your Clerk publishable key to the .env.local file");
}
function JazzAndAuth({ children }: { children: React.ReactNode }) {
function JazzProvider({ children }: { children: React.ReactNode }) {
const clerk = useClerk();
const [auth, state] = useJazzClerkAuth(clerk);
return (
<main className="container">
{state?.errors?.map((error) => (
<div key={error}>{error}</div>
))}
{clerk.user && auth ? (
<JazzProvider
auth={auth}
peer="wss://cloud.jazz.tools/?key=minimal-auth-clerk-example@garden.co"
>
{children}
</JazzProvider>
) : (
<SignInButton />
)}
</main>
<JazzProviderWithClerk
clerk={clerk}
localOnly="anonymous"
peer="wss://cloud.jazz.tools/?key=minimal-auth-clerk-example@garden.co"
>
{children}
</JazzProviderWithClerk>
);
}
createRoot(document.getElementById("root")!).render(
<StrictMode>
<ClerkProvider publishableKey={PUBLISHABLE_KEY} afterSignOutUrl="/">
<JazzAndAuth>
<JazzProvider>
<App />
</JazzAndAuth>
</JazzProvider>
</ClerkProvider>
</StrictMode>,
);

View File

@@ -1,5 +1,20 @@
# file-share-svelte
## 0.0.25
### Patch Changes
- Updated dependencies [b01cc1f]
- jazz-tools@0.9.20
- jazz-svelte@0.9.20
## 0.0.24
### Patch Changes
- jazz-svelte@0.9.19
- jazz-tools@0.9.19
## 0.0.23
### Patch Changes

View File

@@ -1,6 +1,6 @@
{
"name": "file-share-svelte",
"version": "0.0.23",
"version": "0.0.25",
"private": true,
"type": "module",
"scripts": {

View File

@@ -17,6 +17,6 @@ export function formatFileSize(bytes: number): string {
* @param createdAt The creation date
* @returns A unique file ID string
*/
export function generateTempFileId(fileName: string, createdAt: Date): string {
return `file-${fileName}-${createdAt.getTime()}`;
export function generateTempFileId(fileName: string | undefined, createdAt: Date | undefined): string {
return `file-${fileName ?? 'unknown'}-${createdAt?.getTime() ?? 0}`;
}

View File

@@ -14,9 +14,6 @@
import { FileShareAccount } from '$lib/schema';
let { children } = $props();
const auth = usePasskeyAuth({
appName: 'File Share'
});
</script>
<svelte:head>
@@ -25,21 +22,13 @@
<Toaster richColors />
{#if auth.state.state === 'ready'}
<div class="fixed inset-0 flex items-center justify-center bg-gray-50/80">
<div class="rounded-lg bg-white p-8 shadow-lg">
<PasskeyAuthBasicUI state={auth.state} />
</div>
</div>
{/if}
{#if auth.current}
<JazzProvider
AccountSchema={FileShareAccount}
auth={auth.current}
peer="wss://cloud.jazz.tools/?key=file-share-svelte@garden.co"
>
<JazzProvider
AccountSchema={FileShareAccount}
peer="wss://cloud.jazz.tools/?key=minimal-svelte-auth-passkey@garden.co"
>
<PasskeyAuthBasicUI auth={usePasskeyAuth({ appName: 'File Share' })}>
<div class="min-h-screen bg-gray-100">
{@render children()}
</div>
</JazzProvider>
{/if}
</PasskeyAuthBasicUI>
</JazzProvider>

View File

@@ -28,7 +28,7 @@
const input = event.target as HTMLInputElement;
const files = input.files;
if (!files || !files.length || !me?.root?.sharedFiles || !me.root.publicGroup) return;
if (!files || !files.length || !me.root?.sharedFiles || !me.root.publicGroup) return;
const file = files[0];
const fileName = file.name;
@@ -129,12 +129,14 @@
{#if sharedFiles.current}
{#if !(sharedFiles.current.length === 0 && uploadingFiles.size === 0)}
{#each [...sharedFiles.current, ...uploadingFiles.values()] as file (generateTempFileId(file?.name, file?.createdAt))}
<FileItem
{file}
loading={uploadingFiles.has(generateTempFileId(file?.name, file?.createdAt))}
onShare={shareFile}
onDelete={deleteFile}
/>
{#if file}
<FileItem
{file}
loading={uploadingFiles.has(generateTempFileId(file?.name, file?.createdAt))}
onShare={shareFile}
onDelete={deleteFile}
/>
{/if}
{/each}
{:else}
<p class="text-center text-gray-500">No files yet</p>

View File

@@ -1,5 +1,22 @@
# form
## 0.0.36
### Patch Changes
- Updated dependencies [b01cc1f]
- jazz-tools@0.9.20
- jazz-browser-media-images@0.9.20
- jazz-react@0.9.20
## 0.0.35
### Patch Changes
- jazz-react@0.9.19
- jazz-tools@0.9.19
- jazz-browser-media-images@0.9.19
## 0.0.34
### Patch Changes

View File

@@ -1,7 +1,7 @@
{
"name": "form",
"private": true,
"version": "0.0.34",
"version": "0.0.36",
"type": "module",
"scripts": {
"dev": "vite",

View File

@@ -1,4 +1,4 @@
import { DemoAuthBasicUI, JazzProvider, useDemoAuth } from "jazz-react";
import { JazzProvider } from "jazz-react";
import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import App from "./App.tsx";
@@ -6,22 +6,14 @@ import "./index.css";
import { JazzAccount } from "./schema.ts";
function JazzAndAuth({ children }: { children: React.ReactNode }) {
const [auth, authState] = useDemoAuth();
return (
<>
<JazzProvider
auth={auth}
peer="wss://cloud.jazz.tools/?key=form-example@garden.co"
AccountSchema={JazzAccount}
>
{children}
</JazzProvider>
{authState.state !== "signedIn" && (
<DemoAuthBasicUI appName="Form" state={authState} />
)}
</>
<JazzProvider
peer="wss://cloud.jazz.tools/?key=form-example@garden.co"
localOnly="anonymous"
AccountSchema={JazzAccount}
>
{children}
</JazzProvider>
);
}

View File

@@ -1,5 +1,22 @@
# image-upload
## 0.0.38
### Patch Changes
- Updated dependencies [b01cc1f]
- jazz-tools@0.9.20
- jazz-browser-media-images@0.9.20
- jazz-react@0.9.20
## 0.0.37
### Patch Changes
- jazz-react@0.9.19
- jazz-tools@0.9.19
- jazz-browser-media-images@0.9.19
## 0.0.36
### Patch Changes

View File

@@ -1,7 +1,7 @@
{
"name": "image-upload",
"private": true,
"version": "0.0.36",
"version": "0.0.38",
"type": "module",
"scripts": {
"dev": "vite",

View File

@@ -1,4 +1,4 @@
import { DemoAuthBasicUI, JazzProvider, useDemoAuth } from "jazz-react";
import { JazzProvider } from "jazz-react";
import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import App from "./App.tsx";
@@ -6,21 +6,15 @@ import "./index.css";
import { JazzAccount } from "./schema.ts";
function JazzAndAuth({ children }: { children: React.ReactNode }) {
const [auth, authState] = useDemoAuth();
return (
<>
<JazzProvider
auth={auth}
peer="wss://cloud.jazz.tools/?key=image-upload-example@garden.co"
localOnly="anonymous"
AccountSchema={JazzAccount}
>
{children}
</JazzProvider>
{authState.state !== "signedIn" && (
<DemoAuthBasicUI appName="Image upload" state={authState} />
)}
</>
);
}

View File

@@ -1,5 +1,13 @@
# jazz-example-inspector
## 0.0.100
### Patch Changes
- Updated dependencies [6ad0a9f]
- cojson@0.9.19
- cojson-transport-ws@0.9.19
## 0.0.99
### Patch Changes

View File

@@ -1,7 +1,7 @@
{
"name": "jazz-inspector-app",
"private": true,
"version": "0.0.99",
"version": "0.0.100",
"type": "module",
"scripts": {
"dev": "vite",
@@ -16,8 +16,8 @@
"@radix-ui/react-toast": "^1.1.4",
"class-variance-authority": "^0.7.0",
"clsx": "^2.0.0",
"cojson": "workspace:0.9.18",
"cojson-transport-ws": "workspace:0.9.18",
"cojson": "workspace:0.9.19",
"cojson-transport-ws": "workspace:0.9.19",
"hash-slash": "workspace:0.2.1",
"lucide-react": "^0.274.0",
"qrcode": "^1.5.3",

View File

@@ -1,5 +1,22 @@
# jazz-example-musicplayer
## 0.0.62
### Patch Changes
- Updated dependencies [b01cc1f]
- jazz-tools@0.9.20
- jazz-inspector@0.9.21
- jazz-react@0.9.20
## 0.0.61
### Patch Changes
- jazz-inspector@0.9.20
- jazz-react@0.9.19
- jazz-tools@0.9.19
## 0.0.60
### Patch Changes

View File

@@ -1,7 +1,7 @@
{
"name": "jazz-example-music-player",
"private": true,
"version": "0.0.60",
"version": "0.0.62",
"type": "module",
"scripts": {
"dev": "vite",
@@ -13,13 +13,16 @@
"test:ui": "playwright test --ui"
},
"dependencies": {
"@radix-ui/react-dialog": "^1.1.4",
"@radix-ui/react-dropdown-menu": "^2.1.1",
"@radix-ui/react-slot": "^1.0.2",
"@radix-ui/react-label": "^2.1.1",
"@radix-ui/react-slot": "^1.1.1",
"@radix-ui/react-toast": "^1.1.4",
"@radix-ui/react-tooltip": "^1.1.6",
"class-variance-authority": "^0.7.0",
"clsx": "^2.0.0",
"jazz-react": "workspace:0.9.18",
"jazz-tools": "workspace:0.9.18",
"jazz-react": "workspace:0.9.20",
"jazz-tools": "workspace:0.9.20",
"jazz-inspector": "workspace:*",
"lucide-react": "^0.274.0",
"react": "^18.3.1",

View File

@@ -86,7 +86,7 @@ export class MusicaAccount extends Account {
* You can use it to set up the account root and any other initial CoValues you need.
*/
migrate() {
if (!this._refs.root) {
if (this.root === undefined) {
const ownership = { owner: this };
const tracks = ListOfTracks.create([], ownership);

View File

@@ -11,7 +11,7 @@ import { PlayerControls } from "./components/PlayerControls";
import "./index.css";
import { MusicaAccount } from "@/1_schema";
import { DemoAuthBasicUI, JazzProvider, useDemoAuth } from "jazz-react";
import { JazzProvider } from "jazz-react";
import { useUploadExampleData } from "./lib/useUploadExampleData";
/**
@@ -54,30 +54,11 @@ function Main() {
);
}
function JazzAndAuth({ children }: { children: React.ReactNode }) {
const [auth, state] = useDemoAuth();
const peer =
(new URL(window.location.href).searchParams.get(
"peer",
) as `ws://${string}`) ??
"wss://cloud.jazz.tools/?key=music-player-example-jazz@garden.co";
return (
<>
<JazzProvider
storage="indexedDB"
auth={auth}
peer={peer}
AccountSchema={MusicaAccount}
>
{children}
<JazzInspector />
</JazzProvider>
<DemoAuthBasicUI appName="Jazz Music Player" state={state} />
</>
);
}
const peer =
(new URL(window.location.href).searchParams.get(
"peer",
) as `ws://${string}`) ??
"wss://cloud.jazz.tools/?key=music-player-example-jazz@garden.co";
declare module "jazz-react" {
interface Register {
@@ -87,8 +68,15 @@ declare module "jazz-react" {
ReactDOM.createRoot(document.getElementById("root")!).render(
<React.StrictMode>
<JazzAndAuth>
<JazzProvider
peer={peer}
storage="indexedDB"
localOnly="anonymous" // This makes the app work in local mode when the user is anonymous
AccountSchema={MusicaAccount}
defaultProfileName="Anonymous unicorn"
>
<Main />
</JazzAndAuth>
<JazzInspector />
</JazzProvider>
</React.StrictMode>,
);

View File

@@ -1,12 +1,17 @@
import { useToast } from "@/hooks/use-toast";
import { createInviteLink, useAccount, useCoState } from "jazz-react";
import {
createInviteLink,
useAccount,
useCoState,
useIsAuthenticated,
} from "jazz-react";
import { ID } from "jazz-tools";
import { useNavigate, useParams } from "react-router";
import { Playlist } from "./1_schema";
import { createNewPlaylist, uploadMusicTracks } from "./4_actions";
import { MediaPlayer } from "./5_useMediaPlayer";
import { AuthButton } from "./components/AuthButton";
import { FileUploadButton } from "./components/FileUploadButton";
import { LogoutButton } from "./components/LogoutButton";
import { MusicTrackRow } from "./components/MusicTrackRow";
import { PlaylistTitleInput } from "./components/PlaylistTitleInput";
import { SidePanel } from "./components/SidePanel";
@@ -66,6 +71,8 @@ export function HomePage({ mediaPlayer }: { mediaPlayer: MediaPlayer }) {
});
};
const isAuthenticated = useIsAuthenticated();
return (
<div className="flex flex-col h-screen text-gray-800 bg-blue-50">
<div className="flex flex-1 overflow-hidden">
@@ -86,12 +93,12 @@ export function HomePage({ mediaPlayer }: { mediaPlayer: MediaPlayer }) {
<Button onClick={handleCreatePlaylist}>New playlist</Button>
</>
)}
{!isRootPlaylist && (
{!isRootPlaylist && isAuthenticated && (
<Button onClick={handlePlaylistShareClick}>
Share playlist
</Button>
)}
<LogoutButton />
<AuthButton />
</div>
</div>
<ul className="flex flex-col">

View File

@@ -0,0 +1,40 @@
"use client";
import { Button } from "@/components/ui/button";
import { useAccount, useIsAuthenticated } from "jazz-react";
import { useState } from "react";
import { useNavigate } from "react-router-dom";
import { AuthModal } from "./AuthModal";
export function AuthButton() {
const [open, setOpen] = useState(false);
const { logOut } = useAccount();
const navigate = useNavigate();
const isAuthenticated = useIsAuthenticated();
function handleSignOut() {
logOut();
navigate("/");
}
if (isAuthenticated) {
return (
<Button variant="outline" onClick={handleSignOut}>
Sign out
</Button>
);
}
return (
<>
<Button
onClick={() => setOpen(true)}
className="bg-white text-black hover:bg-gray-100"
>
Sign up
</Button>
<AuthModal open={open} onOpenChange={setOpen} />
</>
);
}

View File

@@ -0,0 +1,97 @@
import { Button } from "@/components/ui/button";
import {
Dialog,
DialogContent,
DialogDescription,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { usePasskeyAuth } from "jazz-react";
import { useState } from "react";
interface AuthModalProps {
open: boolean;
onOpenChange: (open: boolean) => void;
}
export function AuthModal({ open, onOpenChange }: AuthModalProps) {
const [username, setUsername] = useState("");
const [isSignUp, setIsSignUp] = useState(true);
const [error, setError] = useState<string | null>(null);
const auth = usePasskeyAuth({
appName: "Jazz Music Player",
});
const handleViewChange = () => {
setIsSignUp(!isSignUp);
setError(null);
};
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
try {
if (isSignUp) {
await auth.signUp(username);
} else {
await auth.logIn();
}
onOpenChange(false);
} catch (error) {
setError(error instanceof Error ? error.message : "Unknown error");
}
};
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="sm:max-w-[425px]">
<DialogHeader>
<DialogTitle className="text-2xl font-bold">
{isSignUp ? "Create account" : "Welcome back"}
</DialogTitle>
<DialogDescription>
{isSignUp
? "Sign up to enable network sync and share your playlists with others"
: "Changes done before logging in will be lost"}
</DialogDescription>
</DialogHeader>
<form onSubmit={handleSubmit} className="space-y-4">
{isSignUp && (
<div className="space-y-2">
<Label htmlFor="username">Username</Label>
<Input
id="username"
value={username}
onChange={(e) => setUsername(e.target.value)}
placeholder="Enter your username"
required
/>
</div>
)}
{error && <div className="text-sm text-red-500">{error}</div>}
<div className="space-y-4">
<Button
type="submit"
className="w-full bg-blue-600 hover:bg-blue-700"
>
{isSignUp ? "Sign up with passkey" : "Login with passkey"}
</Button>
<div className="text-center text-sm">
{isSignUp ? "Already have an account?" : "Don't have an account?"}{" "}
<button
type="button"
onClick={handleViewChange}
className="text-blue-600 hover:underline"
>
{isSignUp ? "Login" : "Sign up"}
</button>
</div>
</div>
</form>
</DialogContent>
</Dialog>
);
}

View File

@@ -0,0 +1,37 @@
import { Badge } from "@/components/ui/badge";
import {
Tooltip,
TooltipContent,
TooltipProvider,
TooltipTrigger,
} from "@/components/ui/tooltip";
import { useIsAuthenticated } from "jazz-react";
import { Info } from "lucide-react";
export function LocalOnlyTag() {
const isAuthenticated = useIsAuthenticated();
if (isAuthenticated) {
return null;
}
return (
<TooltipProvider>
<Tooltip>
<TooltipTrigger asChild>
<div className="inline-flex items-center gap-1.5 cursor-help">
<Badge variant="default" className="h-5 text-xs font-normal">
Local only
</Badge>
<Info className="h-3.5 w-3.5 text-muted-foreground" />
</div>
</TooltipTrigger>
<TooltipContent className="max-w-[250px]">
<p>
Sign up to enable network sync and share your playlists with others
</p>
</TooltipContent>
</Tooltip>
</TooltipProvider>
);
}

View File

@@ -1,5 +1,6 @@
import { useAccount } from "jazz-react";
import { useNavigate, useParams } from "react-router";
import { LocalOnlyTag } from "./LocalOnlyTag";
export function SidePanel() {
const { playlistId } = useParams();
@@ -25,7 +26,7 @@ export function SidePanel() {
return (
<aside className="w-64 p-6 bg-white overflow-y-auto">
<div className="flex items-center mb-6">
<div className="flex items-center mb-1">
<svg
className="w-8 h-8 mr-2"
viewBox="0 0 24 24"
@@ -46,6 +47,9 @@ export function SidePanel() {
</svg>
<span className="text-xl font-bold text-blue-600">Music Player</span>
</div>
<div className="mb-6">
<LocalOnlyTag />
</div>
<nav>
<h2 className="mb-2 text-sm font-semibold text-gray-600">Playlists</h2>
<ul className="space-y-1">

View File

@@ -0,0 +1,36 @@
import { type VariantProps, cva } from "class-variance-authority";
import * as React from "react";
import { cn } from "@/lib/utils";
const badgeVariants = cva(
"inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2",
{
variants: {
variant: {
default:
"border-transparent bg-primary text-primary-foreground hover:bg-primary/80",
secondary:
"border-transparent bg-secondary text-secondary-foreground hover:bg-secondary/80",
destructive:
"border-transparent bg-destructive text-destructive-foreground hover:bg-destructive/80",
outline: "text-foreground",
},
},
defaultVariants: {
variant: "default",
},
},
);
export interface BadgeProps
extends React.HTMLAttributes<HTMLDivElement>,
VariantProps<typeof badgeVariants> {}
function Badge({ className, variant, ...props }: BadgeProps) {
return (
<div className={cn(badgeVariants({ variant }), className)} {...props} />
);
}
export { Badge, badgeVariants };

View File

@@ -0,0 +1,120 @@
import * as DialogPrimitive from "@radix-ui/react-dialog";
import { X } from "lucide-react";
import * as React from "react";
import { cn } from "@/lib/utils";
const Dialog = DialogPrimitive.Root;
const DialogTrigger = DialogPrimitive.Trigger;
const DialogPortal = DialogPrimitive.Portal;
const DialogClose = DialogPrimitive.Close;
const DialogOverlay = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Overlay>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Overlay>
>(({ className, ...props }, ref) => (
<DialogPrimitive.Overlay
ref={ref}
className={cn(
"fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",
className,
)}
{...props}
/>
));
DialogOverlay.displayName = DialogPrimitive.Overlay.displayName;
const DialogContent = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Content>
>(({ className, children, ...props }, ref) => (
<DialogPortal>
<DialogOverlay />
<DialogPrimitive.Content
ref={ref}
className={cn(
"fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",
className,
)}
{...props}
>
{children}
<DialogPrimitive.Close className="absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground">
<X className="h-4 w-4" />
<span className="sr-only">Close</span>
</DialogPrimitive.Close>
</DialogPrimitive.Content>
</DialogPortal>
));
DialogContent.displayName = DialogPrimitive.Content.displayName;
const DialogHeader = ({
className,
...props
}: React.HTMLAttributes<HTMLDivElement>) => (
<div
className={cn(
"flex flex-col space-y-1.5 text-center sm:text-left",
className,
)}
{...props}
/>
);
DialogHeader.displayName = "DialogHeader";
const DialogFooter = ({
className,
...props
}: React.HTMLAttributes<HTMLDivElement>) => (
<div
className={cn(
"flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",
className,
)}
{...props}
/>
);
DialogFooter.displayName = "DialogFooter";
const DialogTitle = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Title>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Title>
>(({ className, ...props }, ref) => (
<DialogPrimitive.Title
ref={ref}
className={cn(
"text-lg font-semibold leading-none tracking-tight",
className,
)}
{...props}
/>
));
DialogTitle.displayName = DialogPrimitive.Title.displayName;
const DialogDescription = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Description>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Description>
>(({ className, ...props }, ref) => (
<DialogPrimitive.Description
ref={ref}
className={cn("text-sm text-muted-foreground", className)}
{...props}
/>
));
DialogDescription.displayName = DialogPrimitive.Description.displayName;
export {
Dialog,
DialogPortal,
DialogOverlay,
DialogClose,
DialogTrigger,
DialogContent,
DialogHeader,
DialogFooter,
DialogTitle,
DialogDescription,
};

View File

@@ -0,0 +1,22 @@
import * as React from "react";
import { cn } from "@/lib/utils";
const Input = React.forwardRef<HTMLInputElement, React.ComponentProps<"input">>(
({ className, type, ...props }, ref) => {
return (
<input
type={type}
className={cn(
"flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-base ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",
className,
)}
ref={ref}
{...props}
/>
);
},
);
Input.displayName = "Input";
export { Input };

View File

@@ -0,0 +1,24 @@
import * as LabelPrimitive from "@radix-ui/react-label";
import { type VariantProps, cva } from "class-variance-authority";
import * as React from "react";
import { cn } from "@/lib/utils";
const labelVariants = cva(
"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",
);
const Label = React.forwardRef<
React.ElementRef<typeof LabelPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof LabelPrimitive.Root> &
VariantProps<typeof labelVariants>
>(({ className, ...props }, ref) => (
<LabelPrimitive.Root
ref={ref}
className={cn(labelVariants(), className)}
{...props}
/>
));
Label.displayName = LabelPrimitive.Root.displayName;
export { Label };

View File

@@ -0,0 +1,30 @@
"use client";
import * as TooltipPrimitive from "@radix-ui/react-tooltip";
import * as React from "react";
import { cn } from "@/lib/utils";
const TooltipProvider = TooltipPrimitive.Provider;
const Tooltip = TooltipPrimitive.Root;
const TooltipTrigger = TooltipPrimitive.Trigger;
const TooltipContent = React.forwardRef<
React.ElementRef<typeof TooltipPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof TooltipPrimitive.Content>
>(({ className, sideOffset = 4, ...props }, ref) => (
<TooltipPrimitive.Content
ref={ref}
sideOffset={sideOffset}
className={cn(
"z-50 overflow-hidden rounded-md border bg-popover px-3 py-1.5 text-sm text-popover-foreground shadow-md animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",
className,
)}
{...props}
/>
));
TooltipContent.displayName = TooltipPrimitive.Content.displayName;
export { Tooltip, TooltipTrigger, TooltipContent, TooltipProvider };

View File

@@ -1,11 +1,14 @@
import { MusicaAccount } from "@/1_schema";
import { useAccount } from "jazz-react";
import { useEffect } from "react";
import { uploadMusicTracks } from "../4_actions";
export function useUploadExampleData() {
const { me } = useAccount();
useEffect(() => {
uploadOnboardingData();
}, []);
}, [me.id]);
}
async function uploadOnboardingData() {

View File

@@ -1,44 +1,84 @@
import { test } from "@playwright/test";
import { BrowserContext, test } from "@playwright/test";
import { HomePage } from "./pages/HomePage";
import { LoginPage } from "./pages/LoginPage";
const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
test("create a new playlist and share", async ({ page }) => {
const loginPage = new LoginPage(page);
async function mockAuthenticator(context: BrowserContext) {
await context.addInitScript(() => {
Object.defineProperty(window.navigator, "credentials", {
value: {
...window.navigator.credentials,
create: async () => ({
type: "public-key",
id: new Uint8Array([1, 2, 3, 4]),
rawId: new Uint8Array([1, 2, 3, 4]),
response: {
clientDataJSON: new Uint8Array([1]),
attestationObject: new Uint8Array([2]),
},
}),
get: async () => ({
type: "public-key",
id: new Uint8Array([1, 2, 3, 4]),
rawId: new Uint8Array([1, 2, 3, 4]),
response: {
authenticatorData: new Uint8Array([1]),
clientDataJSON: new Uint8Array([2]),
signature: new Uint8Array([3]),
},
}),
},
configurable: true,
});
});
}
await loginPage.goto();
await loginPage.fillUsername("S. Mario");
await loginPage.signup();
// Configure the authenticator
test.beforeEach(async ({ context }) => {
// Enable virtual authenticator environment
await mockAuthenticator(context);
});
const homePage = new HomePage(page);
test("create a new playlist and share", async ({
page: marioPage,
browser,
}) => {
await marioPage.goto("/");
const marioHome = new HomePage(marioPage);
// The example song should be loaded
await homePage.expectMusicTrack("Example song");
await homePage.editTrackTitle("Example song", "Super Mario World");
await marioHome.expectMusicTrack("Example song");
await marioHome.editTrackTitle("Example song", "Super Mario World");
await homePage.createPlaylist();
await homePage.editPlaylistTitle("Save the princess");
await marioHome.createPlaylist();
await marioHome.editPlaylistTitle("Save the princess");
await homePage.navigateToPlaylist("All tracks");
await homePage.addTrackToPlaylist("Super Mario World", "Save the princess");
await marioHome.navigateToPlaylist("All tracks");
await marioHome.addTrackToPlaylist("Super Mario World", "Save the princess");
await homePage.navigateToPlaylist("Save the princess");
await homePage.expectMusicTrack("Super Mario World");
await marioHome.navigateToPlaylist("Save the princess");
await marioHome.expectMusicTrack("Super Mario World");
const url = await homePage.getShareLink();
await marioHome.signUp("Mario");
const url = await marioHome.getShareLink();
await sleep(4000); // Wait for the sync to complete
await homePage.logout();
const luigiContext = await browser.newContext();
await mockAuthenticator(luigiContext);
await loginPage.goto();
await loginPage.fillUsername("Luigi");
await loginPage.signup();
const luigiPage = await luigiContext.newPage();
await luigiPage.goto("/");
await page.goto(url);
const luigiHome = new HomePage(luigiPage);
await homePage.expectMusicTrack("Super Mario World");
await homePage.playMusicTrack("Super Mario World");
await homePage.expectActiveTrackPlaying();
await luigiHome.signUp("Luigi");
await luigiPage.goto(url);
await luigiHome.expectMusicTrack("Super Mario World");
await luigiHome.playMusicTrack("Super Mario World");
await luigiHome.expectActiveTrackPlaying();
});

View File

@@ -95,6 +95,17 @@ export class HomePage {
.click();
}
async signUp(name: string) {
await this.page.getByRole("button", { name: "Sign up" }).click();
await this.page.getByRole("textbox", { name: "Username" }).fill(name);
await this.page
.getByRole("button", { name: "Sign up with passkey" })
.click();
await expect(
this.page.getByRole("button", { name: "Sign out" }),
).toBeVisible();
}
async logout() {
await this.logoutButton.click();
}

View File

@@ -1,40 +0,0 @@
import { Locator, Page, expect } from "@playwright/test";
export class LoginPage {
readonly page: Page;
readonly usernameInput: Locator;
readonly signupButton: Locator;
constructor(page: Page) {
this.page = page;
this.usernameInput = page.getByRole("textbox");
this.signupButton = page.getByRole("button", {
name: "Sign up",
});
}
async goto() {
this.page.goto("/");
}
async fillUsername(value: string) {
await this.usernameInput.clear();
await this.usernameInput.fill(value);
}
async loginAs(value: string) {
await this.page
.getByRole("button", {
name: value,
})
.click();
}
async signup() {
await this.signupButton.click();
}
async expectLoaded() {
await expect(this.signupButton).toBeVisible();
}
}

View File

@@ -1,5 +1,22 @@
# jazz-example-onboarding
## 0.0.42
### Patch Changes
- Updated dependencies [b01cc1f]
- jazz-tools@0.9.20
- jazz-browser-media-images@0.9.20
- jazz-react@0.9.20
## 0.0.41
### Patch Changes
- jazz-react@0.9.19
- jazz-tools@0.9.19
- jazz-browser-media-images@0.9.19
## 0.0.40
### Patch Changes

View File

@@ -1,7 +1,7 @@
{
"name": "jazz-example-onboarding",
"private": true,
"version": "0.0.40",
"version": "0.0.42",
"type": "module",
"scripts": {
"dev": "vite",

View File

@@ -1,7 +1,7 @@
import App from "@/App.tsx";
import "@/index.css";
import { HRAccount } from "@/schema.ts";
import { DemoAuthBasicUI, JazzProvider, useDemoAuth } from "jazz-react";
import { JazzProvider } from "jazz-react";
import React from "react";
import ReactDOM from "react-dom/client";
@@ -12,16 +12,10 @@ const peer =
"wss://cloud.jazz.tools/?key=onboarding-example-jazz@garden.co";
function JazzAndAuth({ children }: { children: React.ReactNode }) {
const [auth, authState] = useDemoAuth();
return (
<>
<JazzProvider AccountSchema={HRAccount} auth={auth} peer={peer}>
{children}
</JazzProvider>
{authState.state !== "signedIn" && (
<DemoAuthBasicUI appName="Jazz Onboarding" state={authState} />
)}
</>
<JazzProvider AccountSchema={HRAccount} peer={peer}>
{children}
</JazzProvider>
);
}

View File

@@ -0,0 +1,20 @@
// vite.config.ts
import path from "path";
import react from "file:///Users/brad/dev/jazz/node_modules/@vitejs/plugin-react-swc/index.mjs";
import topLevelAwait from "file:///Users/brad/dev/jazz/node_modules/vite-plugin-top-level-await/exports/import.mjs";
import { defineConfig } from "file:///Users/brad/dev/jazz/node_modules/vite/dist/node/index.js";
var __vite_injected_original_dirname =
"/Users/brad/dev/jazz/examples/onboarding";
var vite_config_default = defineConfig({
plugins: [react(), topLevelAwait()],
resolve: {
alias: {
"@": path.resolve(__vite_injected_original_dirname, "./src"),
},
},
build: {
minify: false,
},
});
export { vite_config_default as default };
//# sourceMappingURL=data:application/json;base64,ewogICJ2ZXJzaW9uIjogMywKICAic291cmNlcyI6IFsidml0ZS5jb25maWcudHMiXSwKICAic291cmNlc0NvbnRlbnQiOiBbImNvbnN0IF9fdml0ZV9pbmplY3RlZF9vcmlnaW5hbF9kaXJuYW1lID0gXCIvVXNlcnMvYnJhZC9kZXYvamF6ei9leGFtcGxlcy9vbmJvYXJkaW5nXCI7Y29uc3QgX192aXRlX2luamVjdGVkX29yaWdpbmFsX2ZpbGVuYW1lID0gXCIvVXNlcnMvYnJhZC9kZXYvamF6ei9leGFtcGxlcy9vbmJvYXJkaW5nL3ZpdGUuY29uZmlnLnRzXCI7Y29uc3QgX192aXRlX2luamVjdGVkX29yaWdpbmFsX2ltcG9ydF9tZXRhX3VybCA9IFwiZmlsZTovLy9Vc2Vycy9icmFkL2Rldi9qYXp6L2V4YW1wbGVzL29uYm9hcmRpbmcvdml0ZS5jb25maWcudHNcIjtpbXBvcnQgcGF0aCBmcm9tIFwicGF0aFwiO1xuaW1wb3J0IHJlYWN0IGZyb20gXCJAdml0ZWpzL3BsdWdpbi1yZWFjdC1zd2NcIjtcbmltcG9ydCB7IGRlZmluZUNvbmZpZyB9IGZyb20gXCJ2aXRlXCI7XG5pbXBvcnQgdG9wTGV2ZWxBd2FpdCBmcm9tIFwidml0ZS1wbHVnaW4tdG9wLWxldmVsLWF3YWl0XCI7XG5cbi8vIGh0dHBzOi8vdml0ZWpzLmRldi9jb25maWcvXG5leHBvcnQgZGVmYXVsdCBkZWZpbmVDb25maWcoe1xuICBwbHVnaW5zOiBbcmVhY3QoKSwgdG9wTGV2ZWxBd2FpdCgpXSxcbiAgcmVzb2x2ZToge1xuICAgIGFsaWFzOiB7XG4gICAgICBcIkBcIjogcGF0aC5yZXNvbHZlKF9fZGlybmFtZSwgXCIuL3NyY1wiKSxcbiAgICB9LFxuICB9LFxuICBidWlsZDoge1xuICAgIG1pbmlmeTogZmFsc2UsXG4gIH0sXG59KTtcbiJdLAogICJtYXBwaW5ncyI6ICI7QUFBMFMsT0FBTyxVQUFVO0FBQzNULE9BQU8sV0FBVztBQUNsQixTQUFTLG9CQUFvQjtBQUM3QixPQUFPLG1CQUFtQjtBQUgxQixJQUFNLG1DQUFtQztBQU16QyxJQUFPLHNCQUFRLGFBQWE7QUFBQSxFQUMxQixTQUFTLENBQUMsTUFBTSxHQUFHLGNBQWMsQ0FBQztBQUFBLEVBQ2xDLFNBQVM7QUFBQSxJQUNQLE9BQU87QUFBQSxNQUNMLEtBQUssS0FBSyxRQUFRLGtDQUFXLE9BQU87QUFBQSxJQUN0QztBQUFBLEVBQ0Y7QUFBQSxFQUNBLE9BQU87QUFBQSxJQUNMLFFBQVE7QUFBQSxFQUNWO0FBQ0YsQ0FBQzsiLAogICJuYW1lcyI6IFtdCn0K

View File

@@ -1,5 +1,20 @@
# organization
## 0.0.34
### Patch Changes
- Updated dependencies [b01cc1f]
- jazz-tools@0.9.20
- jazz-react@0.9.20
## 0.0.33
### Patch Changes
- jazz-react@0.9.19
- jazz-tools@0.9.19
## 0.0.32
### Patch Changes

View File

@@ -1,7 +1,7 @@
{
"name": "organization",
"private": true,
"version": "0.0.32",
"version": "0.0.34",
"type": "module",
"scripts": {
"dev": "vite",

View File

@@ -1,4 +1,4 @@
import { DemoAuthBasicUI, JazzProvider, useDemoAuth } from "jazz-react";
import { JazzProvider } from "jazz-react";
import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import "./index.css";
@@ -28,22 +28,13 @@ function Router() {
}
function JazzAndAuth({ children }: { children: React.ReactNode }) {
const [auth, authState] = useDemoAuth();
return (
<>
<JazzProvider
AccountSchema={JazzAccount}
auth={auth}
peer="wss://cloud.jazz.tools/?key=organization-example@garden.co"
>
{children}
</JazzProvider>
{authState.state !== "signedIn" && (
<DemoAuthBasicUI appName="Organization" state={authState} />
)}
</>
<JazzProvider
AccountSchema={JazzAccount}
peer="wss://cloud.jazz.tools/?key=organization-example@garden.co"
>
{children}
</JazzProvider>
);
}

View File

@@ -1,5 +1,17 @@
# passkey-svelte
## 0.0.29
### Patch Changes
- jazz-svelte@0.9.20
## 0.0.28
### Patch Changes
- jazz-svelte@0.9.19
## 0.0.27
### Patch Changes

View File

@@ -1,6 +1,6 @@
{
"name": "passkey-svelte",
"version": "0.0.27",
"version": "0.0.29",
"type": "module",
"private": true,
"scripts": {

View File

@@ -2,26 +2,13 @@
import { JazzProvider, PasskeyAuthBasicUI, usePasskeyAuth } from 'jazz-svelte';
let { children } = $props();
let auth = usePasskeyAuth({ appName: 'minimal-svelte-auth-passkey' });
$inspect(auth.state);
</script>
<div
style="width: 100vw; height: 100vh; display: flex; align-items: center; justify-content: center;"
>
<PasskeyAuthBasicUI state={auth.state} />
{#if auth.current}
<JazzProvider
auth={auth.current}
peer="wss://cloud.jazz.tools/?key=minimal-svelte-auth-passkey@garden.co"
>
{@render children?.()}
</JazzProvider>
{/if}
</div>
<JazzProvider peer="wss://cloud.jazz.tools/?key=minimal-svelte-auth-passkey@garden.co">
<PasskeyAuthBasicUI auth={usePasskeyAuth({ appName: 'minimal-svelte-auth-passkey' })}>
{@render children?.()}
</PasskeyAuthBasicUI>
</JazzProvider>
<style>
:global(html, body) {

View File

@@ -1,5 +1,20 @@
# minimal-auth-passkey
## 0.0.39
### Patch Changes
- Updated dependencies [b01cc1f]
- jazz-tools@0.9.20
- jazz-react@0.9.20
## 0.0.38
### Patch Changes
- jazz-react@0.9.19
- jazz-tools@0.9.19
## 0.0.37
### Patch Changes

View File

@@ -1,7 +1,7 @@
{
"name": "passkey",
"private": true,
"version": "0.0.37",
"version": "0.0.39",
"type": "module",
"scripts": {
"dev": "vite",

View File

@@ -5,20 +5,15 @@ import App from "./App.tsx";
import "./index.css";
function JazzAndAuth({ children }: { children: React.ReactNode }) {
const [auth, state] = usePasskeyAuth({
const auth = usePasskeyAuth({
appName: "Jazz Minimal Auth Passkey Example",
});
return (
<>
<JazzProvider
auth={auth}
peer="wss://cloud.jazz.tools/?key=minimal-auth-passkey-example@garden.co"
>
{children}
</JazzProvider>
<PasskeyAuthBasicUI state={state} />
</>
<JazzProvider peer="wss://cloud.jazz.tools/?key=minimal-auth-passkey-example@garden.co">
<PasskeyAuthBasicUI {...auth} />
{children}
</JazzProvider>
);
}

View File

@@ -1,5 +1,20 @@
# jazz-password-manager
## 0.0.60
### Patch Changes
- Updated dependencies [b01cc1f]
- jazz-tools@0.9.20
- jazz-react@0.9.20
## 0.0.59
### Patch Changes
- jazz-react@0.9.19
- jazz-tools@0.9.19
## 0.0.58
### Patch Changes

View File

@@ -1,7 +1,7 @@
{
"name": "jazz-password-manager",
"private": true,
"version": "0.0.58",
"version": "0.0.60",
"type": "module",
"scripts": {
"dev": "vite",
@@ -12,8 +12,8 @@
"clean-install": "rm -rf node_modules pnpm-lock.yaml && pnpm install"
},
"dependencies": {
"jazz-react": "workspace:0.9.18",
"jazz-tools": "workspace:0.9.18",
"jazz-react": "workspace:0.9.20",
"jazz-tools": "workspace:0.9.20",
"react": "^18.3.1",
"react-dom": "^18.3.1",
"react-hook-form": "^7.41.5",

View File

@@ -6,21 +6,18 @@ import App from "./5_App.tsx";
import "./index.css";
function JazzAndAuth({ children }: { children: React.ReactNode }) {
const [auth, state] = usePasskeyAuth({
const auth = usePasskeyAuth({
appName: "Jazz Password Manager",
});
return (
<>
<JazzProvider
AccountSchema={PasswordManagerAccount}
auth={auth}
peer="wss://cloud.jazz.tools/?key=password-manager-example-jazz@garden.co"
>
{children}
</JazzProvider>
<PasskeyAuthBasicUI state={state} />
</>
<JazzProvider
AccountSchema={PasswordManagerAccount}
peer="wss://cloud.jazz.tools/?key=password-manager-example-jazz@garden.co"
>
<PasskeyAuthBasicUI {...auth} />
{children}
</JazzProvider>
);
}

View File

@@ -1,5 +1,22 @@
# jazz-example-pets
## 0.0.158
### Patch Changes
- Updated dependencies [b01cc1f]
- jazz-tools@0.9.20
- jazz-browser-media-images@0.9.20
- jazz-react@0.9.20
## 0.0.157
### Patch Changes
- jazz-react@0.9.19
- jazz-tools@0.9.19
- jazz-browser-media-images@0.9.19
## 0.0.156
### Patch Changes

View File

@@ -1,7 +1,7 @@
{
"name": "jazz-example-pets",
"private": true,
"version": "0.0.156",
"version": "0.0.158",
"type": "module",
"scripts": {
"dev": "vite",
@@ -19,9 +19,9 @@
"@radix-ui/react-toast": "^1.1.4",
"class-variance-authority": "^0.7.0",
"clsx": "^2.0.0",
"jazz-browser-media-images": "workspace:0.9.18",
"jazz-react": "workspace:0.9.18",
"jazz-tools": "workspace:0.9.18",
"jazz-browser-media-images": "workspace:0.9.20",
"jazz-react": "workspace:0.9.20",
"jazz-tools": "workspace:0.9.20",
"lucide-react": "^0.274.0",
"qrcode": "^1.5.3",
"react": "^18.3.1",
@@ -41,7 +41,7 @@
"@vitejs/plugin-react-swc": "^3.3.2",
"autoprefixer": "^10.4.20",
"is-ci": "^3.0.1",
"jazz-run": "workspace:0.9.18",
"jazz-run": "workspace:0.9.20",
"postcss": "^8.4.27",
"tailwindcss": "^3.4.15",
"typescript": "~5.6.2",

View File

@@ -8,13 +8,7 @@ import {
} from "react-router-dom";
import "./index.css";
import {
DemoAuthBasicUI,
JazzProvider,
useAcceptInvite,
useAccount,
useDemoAuth,
} from "jazz-react";
import { JazzProvider, useAcceptInvite, useAccount } from "jazz-react";
import { PetAccount, PetPost } from "./1_schema.ts";
import { NewPetPostForm } from "./3_NewPetPostForm.tsx";
@@ -41,14 +35,15 @@ const peer =
const appName = "Jazz Rate My Pet Example";
function JazzAndAuth({ children }: { children: React.ReactNode }) {
const [auth, authState] = useDemoAuth();
return (
<>
<JazzProvider auth={auth} peer={peer} AccountSchema={PetAccount}>
<JazzProvider
peer={peer}
AccountSchema={PetAccount}
localOnly="anonymous"
>
{children}
</JazzProvider>
<DemoAuthBasicUI appName={appName} state={authState} />
</>
);
}

View File

@@ -1,5 +1,22 @@
# reactions
## 0.0.38
### Patch Changes
- Updated dependencies [b01cc1f]
- jazz-tools@0.9.20
- jazz-browser-media-images@0.9.20
- jazz-react@0.9.20
## 0.0.37
### Patch Changes
- jazz-react@0.9.19
- jazz-tools@0.9.19
- jazz-browser-media-images@0.9.19
## 0.0.36
### Patch Changes

View File

@@ -1,7 +1,7 @@
{
"name": "reactions",
"private": true,
"version": "0.0.36",
"version": "0.0.38",
"type": "module",
"scripts": {
"dev": "vite",

View File

@@ -1,24 +1,18 @@
import { DemoAuthBasicUI, JazzProvider, useDemoAuth } from "jazz-react";
import { JazzProvider } from "jazz-react";
import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import App from "./App.tsx";
import "./index.css";
function JazzAndAuth({ children }: { children: React.ReactNode }) {
const [auth, authState] = useDemoAuth();
return (
<>
<JazzProvider
auth={auth}
localOnly="anonymous"
peer="wss://cloud.jazz.tools/?key=reactions-example@garden.co"
>
{children}
</JazzProvider>
{authState.state !== "signedIn" && (
<DemoAuthBasicUI appName="Reactions" state={authState} />
)}
</>
);
}

View File

@@ -1,5 +1,22 @@
# todo-vue
## 0.0.43
### Patch Changes
- Updated dependencies [b01cc1f]
- jazz-tools@0.9.20
- jazz-browser@0.9.20
- jazz-vue@0.9.20
## 0.0.42
### Patch Changes
- jazz-browser@0.9.19
- jazz-tools@0.9.19
- jazz-vue@0.9.19
## 0.0.41
### Patch Changes

View File

@@ -1,6 +1,6 @@
{
"name": "todo-vue",
"version": "0.0.41",
"version": "0.0.43",
"private": true,
"type": "module",
"scripts": {

View File

@@ -11,30 +11,36 @@ declare module "jazz-vue" {
}
}
const AuthScreen = defineComponent({
name: "AuthScreen",
setup() {
const auth = useDemoAuth();
return () => [
auth.value.state === "anonymous"
? h(DemoAuthBasicUI, {
appName: "Jazz Vue Todo",
auth,
})
: h(App),
];
},
});
const RootComponent = defineComponent({
name: "RootComponent",
setup() {
const { authMethod, state } = useDemoAuth();
return () => [
return () =>
h(
JazzProvider,
{
AccountSchema: ToDoAccount,
auth: authMethod.value,
peer: "wss://cloud.jazz.tools/?key=vue-todo-example-jazz@garden.co",
},
{
default: () => h(App),
default: () => h(AuthScreen),
},
),
state.state !== "signedIn" &&
h(DemoAuthBasicUI, {
appName: "Jazz Vue Todo",
state,
}),
];
);
},
});

View File

@@ -1,5 +1,20 @@
# jazz-example-todo
## 0.0.157
### Patch Changes
- Updated dependencies [b01cc1f]
- jazz-tools@0.9.20
- jazz-react@0.9.20
## 0.0.156
### Patch Changes
- jazz-react@0.9.19
- jazz-tools@0.9.19
## 0.0.155
### Patch Changes

View File

@@ -1,7 +1,7 @@
{
"name": "jazz-example-todo",
"private": true,
"version": "0.0.155",
"version": "0.0.157",
"type": "module",
"scripts": {
"dev": "vite",
@@ -16,8 +16,8 @@
"@radix-ui/react-toast": "^1.1.4",
"class-variance-authority": "^0.7.0",
"clsx": "^2.0.0",
"jazz-react": "workspace:0.9.18",
"jazz-tools": "workspace:0.9.18",
"jazz-react": "workspace:0.9.20",
"jazz-tools": "workspace:0.9.20",
"lucide-react": "^0.274.0",
"qrcode": "^1.5.3",
"react": "^18.3.1",

View File

@@ -38,18 +38,17 @@ import {
const appName = "Jazz Todo List Example";
function JazzAndAuth({ children }: { children: React.ReactNode }) {
const [passkeyAuth, passKeyState] = usePasskeyAuth({ appName });
const auth = usePasskeyAuth({ appName });
return (
<>
<JazzProvider
AccountSchema={TodoAccount}
auth={passkeyAuth}
peer="wss://cloud.jazz.tools/?key=todo-example-jazz@garden.co"
>
<PasskeyAuthBasicUI {...auth} />
{children}
</JazzProvider>
<PasskeyAuthBasicUI state={passKeyState} />
</>
);
}

View File

@@ -1,5 +1,20 @@
# version-history
## 0.0.35
### Patch Changes
- Updated dependencies [b01cc1f]
- jazz-tools@0.9.20
- jazz-react@0.9.20
## 0.0.34
### Patch Changes
- jazz-react@0.9.19
- jazz-tools@0.9.19
## 0.0.33
### Patch Changes

View File

@@ -1,7 +1,7 @@
{
"name": "version-history",
"private": true,
"version": "0.0.33",
"version": "0.0.35",
"type": "module",
"scripts": {
"dev": "vite",

View File

@@ -1,25 +1,17 @@
import { DemoAuthBasicUI, JazzProvider, useDemoAuth } from "jazz-react";
import { JazzProvider } from "jazz-react";
import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import App from "./App.tsx";
import "./index.css";
function JazzAndAuth({ children }: { children: React.ReactNode }) {
const [auth, authState] = useDemoAuth();
return (
<>
<JazzProvider
auth={auth}
peer="wss://cloud.jazz.tools/?key=version-history@garden.co"
>
{children}
</JazzProvider>
{authState.state !== "signedIn" && (
<DemoAuthBasicUI appName="React + Demo Auth" state={authState} />
)}
</>
<JazzProvider
localOnly="anonymous"
peer="wss://cloud.jazz.tools/?key=version-history@garden.co"
>
{children}
</JazzProvider>
);
}

View File

@@ -1,5 +1,13 @@
# cojson-storage-indexeddb
## 0.9.19
### Patch Changes
- Updated dependencies [6ad0a9f]
- cojson@0.9.19
- cojson-storage@0.9.19
## 0.9.18
### Patch Changes

View File

@@ -1,6 +1,6 @@
{
"name": "cojson-storage-indexeddb",
"version": "0.9.18",
"version": "0.9.19",
"main": "dist/index.js",
"type": "module",
"types": "src/index.ts",

View File

@@ -1,5 +1,13 @@
# cojson-storage-sqlite
## 0.8.58
### Patch Changes
- Updated dependencies [6ad0a9f]
- cojson@0.9.19
- cojson-storage@0.9.19
## 0.8.57
### Patch Changes

View File

@@ -1,7 +1,7 @@
{
"name": "cojson-storage-rn-sqlite",
"type": "module",
"version": "0.8.57",
"version": "0.8.58",
"main": "dist/index.js",
"types": "src/index.ts",
"license": "MIT",

View File

@@ -1,5 +1,13 @@
# cojson-storage-sqlite
## 0.9.19
### Patch Changes
- Updated dependencies [6ad0a9f]
- cojson@0.9.19
- cojson-storage@0.9.19
## 0.9.18
### Patch Changes

View File

@@ -1,13 +1,13 @@
{
"name": "cojson-storage-sqlite",
"type": "module",
"version": "0.9.18",
"version": "0.9.19",
"main": "dist/index.js",
"types": "src/index.ts",
"license": "MIT",
"dependencies": {
"better-sqlite3": "^11.7.0",
"cojson": "workspace:0.9.18",
"cojson": "workspace:0.9.19",
"cojson-storage": "workspace:*"
},
"devDependencies": {

View File

@@ -1,5 +1,12 @@
# cojson-storage
## 0.9.19
### Patch Changes
- Updated dependencies [6ad0a9f]
- cojson@0.9.19
## 0.9.18
### Patch Changes

View File

@@ -1,6 +1,6 @@
{
"name": "cojson-storage",
"version": "0.9.18",
"version": "0.9.19",
"main": "dist/index.js",
"type": "module",
"types": "src/index.ts",

View File

@@ -1,5 +1,12 @@
# cojson-transport-nodejs-ws
## 0.9.19
### Patch Changes
- Updated dependencies [6ad0a9f]
- cojson@0.9.19
## 0.9.18
### Patch Changes

View File

@@ -1,12 +1,12 @@
{
"name": "cojson-transport-ws",
"type": "module",
"version": "0.9.18",
"version": "0.9.19",
"main": "dist/index.js",
"types": "src/index.ts",
"license": "MIT",
"dependencies": {
"cojson": "workspace:0.9.18",
"cojson": "workspace:*",
"typescript": "~5.6.2"
},
"scripts": {
@@ -19,6 +19,7 @@
"prepublishOnly": "npm run build"
},
"devDependencies": {
"@types/ws": "8.5.10"
"@types/ws": "8.5.10",
"ws": "^8.14.2"
}
}

View File

@@ -21,6 +21,7 @@ export type CreateWebSocketPeerOpts = {
batchingByDefault?: boolean;
deletePeerStateOnClose?: boolean;
onClose?: () => void;
onSuccess?: () => void;
};
function createPingTimeoutListener(enabled: boolean, callback: () => void) {
@@ -127,6 +128,7 @@ export function createWebSocketPeer({
expectPings = true,
batchingByDefault = true,
deletePeerStateOnClose = false,
onSuccess,
onClose,
}: CreateWebSocketPeerOpts): Peer {
const incoming = new cojsonInternals.Channel<
@@ -142,6 +144,7 @@ export function createWebSocketPeer({
}
websocket.addEventListener("close", handleClose);
websocket.addEventListener("error" as any, handleClose);
const pingTimeout = createPingTimeoutListener(expectPings, () => {
incoming
@@ -154,6 +157,7 @@ export function createWebSocketPeer({
websocket,
batchingByDefault,
);
let isFirstMessage = true;
function handleIncomingMsg(event: { data: unknown }) {
if (event.data === "") {
@@ -169,6 +173,13 @@ export function createWebSocketPeer({
return;
}
if (isFirstMessage) {
// The only way to know that the connection has been correctly established with our sync server
// is to track that we got a message from the server.
onSuccess?.();
isFirstMessage = false;
}
const { messages } = result;
if (messages.length > 1) {

View File

@@ -170,6 +170,31 @@ describe("createWebSocketPeer", () => {
);
});
test("should call onSuccess handler after receiving first message", () => {
const onSuccess = vi.fn();
const { listeners } = setup({ onSuccess });
const messageHandler = listeners.get("message");
const message: SyncMessage = {
action: "known",
id: "co_ztest",
header: false,
sessions: {},
};
// First message should trigger onSuccess
messageHandler?.(
new MessageEvent("message", { data: JSON.stringify(message) }),
);
expect(onSuccess).toHaveBeenCalledTimes(1);
// Subsequent messages should not trigger onSuccess again
messageHandler?.(
new MessageEvent("message", { data: JSON.stringify(message) }),
);
expect(onSuccess).toHaveBeenCalledTimes(1);
});
describe("batchingByDefault = true", () => {
test("should batch outgoing messages", async () => {
const { peer, mockWebSocket } = setup();

View File

@@ -0,0 +1,132 @@
import { ControlledAgent, LocalNode, WasmCrypto } from "cojson";
import { afterEach, beforeEach, describe, expect, test } from "vitest";
import { WebSocket } from "ws";
import { createWebSocketPeer } from "../index";
import { startSyncServer } from "./syncServer";
describe("WebSocket Peer Integration", () => {
let server: any;
let syncServerUrl: string;
let crypto: WasmCrypto;
beforeEach(async () => {
crypto = await WasmCrypto.create();
const result = await startSyncServer();
server = result;
syncServerUrl = result.syncServer;
});
afterEach(() => {
server.close();
});
test("should establish connection between client and server nodes", async () => {
// Create client node
const clientAgent = crypto.newRandomAgentSecret();
const clientNode = new LocalNode(
new ControlledAgent(clientAgent, crypto),
crypto.newRandomSessionID(crypto.getAgentID(clientAgent)),
crypto,
);
// Create WebSocket connection
const ws = new WebSocket(syncServerUrl);
// Track connection success
let connectionEstablished = false;
// Create peer and add to client node
const peer = createWebSocketPeer({
id: "test-client",
websocket: ws,
role: "server",
onSuccess: () => {
connectionEstablished = true;
},
});
clientNode.syncManager.addPeer(peer);
// Wait for connection to establish
await new Promise<void>((resolve) => {
const checkConnection = setInterval(() => {
if (connectionEstablished) {
clearInterval(checkConnection);
resolve();
}
}, 100);
});
expect(connectionEstablished).toBe(true);
expect(clientNode.syncManager.getPeers()).toHaveLength(1);
});
test("should sync data between nodes through WebSocket connection", async () => {
const clientAgent = crypto.newRandomAgentSecret();
const clientNode = new LocalNode(
new ControlledAgent(clientAgent, crypto),
crypto.newRandomSessionID(crypto.getAgentID(clientAgent)),
crypto,
);
const ws = new WebSocket(syncServerUrl);
const peer = createWebSocketPeer({
id: "test-client",
websocket: ws,
role: "server",
});
clientNode.syncManager.addPeer(peer);
// Create a test group
const group = clientNode.createGroup();
const map = group.createMap();
map.set("testKey", "testValue", "trusting");
// Wait for sync
await map.core.waitForSync();
console.log("synced");
// Verify data reached the server
const serverNode = server.localNode;
const serverMap = await serverNode.load(map.id);
expect(serverMap.get("testKey")).toBe("testValue");
});
test("should handle disconnection and cleanup", async () => {
const clientAgent = crypto.newRandomAgentSecret();
const clientNode = new LocalNode(
new ControlledAgent(clientAgent, crypto),
crypto.newRandomSessionID(crypto.getAgentID(clientAgent)),
crypto,
);
const ws = new WebSocket(syncServerUrl);
let disconnectCalled = false;
const peer = createWebSocketPeer({
id: "test-client",
websocket: ws,
role: "server",
onClose: () => {
disconnectCalled = true;
},
});
clientNode.syncManager.addPeer(peer);
// Wait for connection to establish
await new Promise((resolve) => setTimeout(resolve, 200));
// Close the server
server.close();
// Wait for disconnect handling
await new Promise((resolve) => setTimeout(resolve, 200));
expect(disconnectCalled).toBe(true);
expect(ws.readyState).toBe(WebSocket.CLOSED);
});
});

View File

@@ -0,0 +1,89 @@
import { createServer } from "http";
import { ControlledAgent, LocalNode, WasmCrypto } from "cojson";
import { WebSocket, WebSocketServer } from "ws";
import { createWebSocketPeer } from "../index";
export const startSyncServer = async (port?: number) => {
const crypto = await WasmCrypto.create();
const server = createServer((req, res) => {
if (req.url === "/health") {
res.writeHead(200);
res.end("ok");
}
});
const wss = new WebSocketServer({ noServer: true });
const agentSecret = crypto.newRandomAgentSecret();
const agentID = crypto.getAgentID(agentSecret);
const localNode = new LocalNode(
new ControlledAgent(agentSecret, crypto),
crypto.newRandomSessionID(agentID),
crypto,
);
const connections = new Set<WebSocket>();
wss.on("connection", function connection(ws, req) {
connections.add(ws);
const sendPing = () => {
ws.send(
JSON.stringify({
type: "ping",
time: Date.now(),
dc: "unknown",
}),
);
};
// ping/pong for the connection liveness
const pinging = setInterval(sendPing, 100);
sendPing(); // Immediately send a ping to the client to signal that the connection is established
ws.on("close", () => {
clearInterval(pinging);
connections.delete(ws);
});
const clientId = new Date().toISOString();
localNode.syncManager.addPeer(
createWebSocketPeer({
id: clientId,
role: "client",
websocket: ws,
expectPings: false,
batchingByDefault: false,
deletePeerStateOnClose: true,
}),
);
ws.on("error", (e) => console.error(`Error on connection ${clientId}:`, e));
});
server.on("upgrade", function upgrade(req, socket, head) {
if (req.url !== "/health") {
wss.handleUpgrade(req, socket, head, function done(ws) {
wss.emit("connection", ws, req);
});
}
});
server.listen(port ?? 0);
port = (server.address() as { port: number }).port;
const syncServer = `ws://localhost:${port}`;
return {
close: () => {
connections.forEach((ws) => ws.close());
server.close();
},
syncServer,
port,
localNode,
};
};

View File

@@ -1,5 +1,11 @@
# cojson
## 0.9.19
### Patch Changes
- 6ad0a9f: Export Json types
## 0.9.18
### Patch Changes

View File

@@ -24,7 +24,7 @@
},
"type": "module",
"license": "MIT",
"version": "0.9.18",
"version": "0.9.19",
"devDependencies": {
"@opentelemetry/sdk-metrics": "^1.29.0",
"@types/jest": "^29.5.3",

View File

@@ -1,43 +1,36 @@
import { describe, expect, onTestFinished, test, vi } from "vitest";
import { beforeEach, describe, expect, onTestFinished, test, vi } from "vitest";
import {
GlobalSyncStateListenerCallback,
PeerSyncStateListenerCallback,
} from "../SyncStateManager.js";
import { accountHeaderForInitialAgentSecret } from "../coValues/account.js";
import { connectedPeers } from "../streamUtils.js";
import { emptyKnownState } from "../sync.js";
import {
blockMessageTypeOnOutgoingPeer,
connectNodeToSyncServer,
createTestNode,
createTwoConnectedNodes,
loadCoValueOrFail,
setupSyncServer,
waitFor,
} from "./testUtils.js";
let jazzCloud = setupSyncServer();
beforeEach(async () => {
jazzCloud = setupSyncServer();
});
describe("SyncStateManager", () => {
test("subscribeToUpdates receives updates when peer state changes", async () => {
// Setup nodes
const client = createTestNode();
const jazzCloud = createTestNode();
const { nodeToServerPeer } = connectNodeToSyncServer(client);
// Create test data
const group = client.createGroup();
const map = group.createMap();
map.set("key1", "value1", "trusting");
// Connect nodes
const [clientAsPeer, jazzCloudAsPeer] = connectedPeers(
"clientConnection",
"jazzCloudConnection",
{
peer1role: "client",
peer2role: "server",
},
);
client.syncManager.addPeer(jazzCloudAsPeer);
jazzCloud.syncManager.addPeer(clientAsPeer);
const subscriptionManager = client.syncManager.syncState;
const updateSpy: GlobalSyncStateListenerCallback = vi.fn();
@@ -46,21 +39,21 @@ describe("SyncStateManager", () => {
await client.syncManager.actuallySyncCoValue(map.core);
expect(updateSpy).toHaveBeenCalledWith(
"jazzCloudConnection",
nodeToServerPeer.id,
emptyKnownState(map.core.id),
{ uploaded: false },
);
await waitFor(() => {
return subscriptionManager.getCurrentSyncState(
"jazzCloudConnection",
nodeToServerPeer.id,
map.core.id,
).uploaded;
});
expect(updateSpy).toHaveBeenCalledWith(
"jazzCloudConnection",
client.syncManager.peers["jazzCloudConnection"]!.knownStates.get(
nodeToServerPeer.id,
client.syncManager.peers[nodeToServerPeer.id]!.knownStates.get(
map.core.id,
)!,
{ uploaded: true },
@@ -73,42 +66,30 @@ describe("SyncStateManager", () => {
test("subscribeToPeerUpdates receives updates only for specific peer", async () => {
// Setup nodes
const client = createTestNode();
const jazzCloud = createTestNode();
const { nodeToServerPeer } = connectNodeToSyncServer(client);
// Create test data
const group = client.createGroup();
const map = group.createMap();
map.set("key1", "value1", "trusting");
// Connect nodes
const [clientAsPeer, jazzCloudAsPeer] = connectedPeers(
"clientConnection",
"jazzCloudConnection",
{
peer1role: "client",
peer2role: "server",
},
);
const [clientStoragePeer] = connectedPeers("clientStorage", "unusedPeer", {
peer1role: "client",
peer2role: "server",
});
client.syncManager.addPeer(jazzCloudAsPeer);
client.syncManager.addPeer(clientStoragePeer);
jazzCloud.syncManager.addPeer(clientAsPeer);
const subscriptionManager = client.syncManager.syncState;
const updateToJazzCloudSpy: PeerSyncStateListenerCallback = vi.fn();
const updateToStorageSpy: PeerSyncStateListenerCallback = vi.fn();
const unsubscribe1 = subscriptionManager.subscribeToPeerUpdates(
"jazzCloudConnection",
nodeToServerPeer.id,
updateToJazzCloudSpy,
);
const unsubscribe2 = subscriptionManager.subscribeToPeerUpdates(
"clientStorage",
clientStoragePeer.id,
updateToStorageSpy,
);
@@ -126,13 +107,13 @@ describe("SyncStateManager", () => {
await waitFor(() => {
return subscriptionManager.getCurrentSyncState(
"jazzCloudConnection",
nodeToServerPeer.id,
map.core.id,
).uploaded;
});
expect(updateToJazzCloudSpy).toHaveBeenLastCalledWith(
client.syncManager.peers["jazzCloudConnection"]!.knownStates.get(
client.syncManager.peers[nodeToServerPeer.id]!.knownStates.get(
map.core.id,
)!,
{ uploaded: true },
@@ -147,80 +128,50 @@ describe("SyncStateManager", () => {
test("getIsCoValueFullyUploadedIntoPeer returns correct status", async () => {
// Setup nodes
const client = createTestNode();
const jazzCloud = createTestNode();
const { nodeToServerPeer } = connectNodeToSyncServer(client);
// Create test data
const group = client.createGroup();
const map = group.createMap();
map.set("key1", "value1", "trusting");
// Connect nodes
const [clientAsPeer, jazzCloudAsPeer] = connectedPeers(
"clientConnection",
"jazzCloudConnection",
{
peer1role: "client",
peer2role: "server",
},
);
client.syncManager.addPeer(jazzCloudAsPeer);
jazzCloud.syncManager.addPeer(clientAsPeer);
await client.syncManager.actuallySyncCoValue(map.core);
const subscriptionManager = client.syncManager.syncState;
expect(
subscriptionManager.getCurrentSyncState(
"jazzCloudConnection",
map.core.id,
).uploaded,
subscriptionManager.getCurrentSyncState(nodeToServerPeer.id, map.core.id)
.uploaded,
).toBe(false);
await waitFor(() => {
return subscriptionManager.getCurrentSyncState(
"jazzCloudConnection",
nodeToServerPeer.id,
map.core.id,
).uploaded;
});
expect(
subscriptionManager.getCurrentSyncState(
"jazzCloudConnection",
map.core.id,
).uploaded,
subscriptionManager.getCurrentSyncState(nodeToServerPeer.id, map.core.id)
.uploaded,
).toBe(true);
});
test("unsubscribe stops receiving updates", async () => {
// Setup nodes
const client = createTestNode();
const jazzCloud = createTestNode();
const { nodeToServerPeer } = connectNodeToSyncServer(client);
// Create test data
const group = client.createGroup();
const map = group.createMap();
map.set("key1", "value1", "trusting");
// Connect nodes
const [clientAsPeer, jazzCloudAsPeer] = connectedPeers(
"clientConnection",
"jazzCloudConnection",
{
peer1role: "client",
peer2role: "server",
},
);
client.syncManager.addPeer(jazzCloudAsPeer);
jazzCloud.syncManager.addPeer(clientAsPeer);
const subscriptionManager = client.syncManager.syncState;
const anyUpdateSpy = vi.fn();
const unsubscribe1 = subscriptionManager.subscribeToUpdates(anyUpdateSpy);
const unsubscribe2 = subscriptionManager.subscribeToPeerUpdates(
"jazzCloudConnection",
nodeToServerPeer.id,
anyUpdateSpy,
);
@@ -233,7 +184,7 @@ describe("SyncStateManager", () => {
await waitFor(() => {
return subscriptionManager.getCurrentSyncState(
"jazzCloudConnection",
nodeToServerPeer.id,
map.core.id,
).uploaded;
});
@@ -243,22 +194,21 @@ describe("SyncStateManager", () => {
test("getCurrentSyncState should return the correct state", async () => {
// Setup nodes
const clientNode = createTestNode();
const serverNode = jazzCloud;
const {
node1: clientNode,
node2: serverNode,
node1ToNode2Peer: clientToServerPeer,
node2ToNode1Peer: serverToClientPeer,
} = await createTwoConnectedNodes("client", "server");
nodeToServerPeer: clientToServerPeer,
serverToNodePeer: serverToClientPeer,
} = connectNodeToSyncServer(clientNode);
// Create test data
const group = clientNode.node.createGroup();
const group = clientNode.createGroup();
const map = group.createMap();
map.set("key1", "value1", "trusting");
group.addMember("everyone", "writer");
// Initially should not be synced
expect(
clientNode.node.syncManager.syncState.getCurrentSyncState(
clientNode.syncManager.syncState.getCurrentSyncState(
clientToServerPeer.id,
map.core.id,
),
@@ -268,13 +218,13 @@ describe("SyncStateManager", () => {
await map.core.waitForSync();
expect(
clientNode.node.syncManager.syncState.getCurrentSyncState(
clientNode.syncManager.syncState.getCurrentSyncState(
clientToServerPeer.id,
map.core.id,
),
).toEqual({ uploaded: true });
const mapOnServer = await loadCoValueOrFail(serverNode.node, map.id);
const mapOnServer = await loadCoValueOrFail(serverNode, map.id);
// Block the content messages so the client won't fully sync immediately
const outgoing = blockMessageTypeOnOutgoingPeer(
@@ -285,14 +235,14 @@ describe("SyncStateManager", () => {
mapOnServer.set("key2", "value2", "trusting");
expect(
clientNode.node.syncManager.syncState.getCurrentSyncState(
clientNode.syncManager.syncState.getCurrentSyncState(
clientToServerPeer.id,
map.core.id,
),
).toEqual({ uploaded: true });
expect(
serverNode.node.syncManager.syncState.getCurrentSyncState(
serverNode.syncManager.syncState.getCurrentSyncState(
serverToClientPeer.id,
map.core.id,
),
@@ -304,14 +254,14 @@ describe("SyncStateManager", () => {
await mapOnServer.core.waitForSync();
expect(
clientNode.node.syncManager.syncState.getCurrentSyncState(
clientNode.syncManager.syncState.getCurrentSyncState(
clientToServerPeer.id,
map.core.id,
),
).toEqual({ uploaded: true });
expect(
serverNode.node.syncManager.syncState.getCurrentSyncState(
serverNode.syncManager.syncState.getCurrentSyncState(
serverToClientPeer.id,
map.core.id,
),

Some files were not shown because too many files have changed in this diff Show More