Compare commits

..

3 Commits

Author SHA1 Message Date
pax-k
849c2b9ffc fix(useCoState): requested changes 2025-03-10 16:30:07 +02:00
pax-k
56860d406b chore: changeset 2025-02-28 13:12:48 +02:00
pax-k
357d1b4c8d fix: useCoState stale data 2025-02-28 13:11:47 +02:00
94 changed files with 134 additions and 2273 deletions

View File

@@ -0,0 +1,5 @@
---
"jazz-react-core": patch
---
Fix useCoState stale data

View File

@@ -0,0 +1,5 @@
---
"create-jazz-app": patch
---
Added Cursor docs to create-jazz-app

View File

@@ -1,15 +1,5 @@
# chat-rn-clerk
## 1.0.79
### Patch Changes
- Updated dependencies [75211e3]
- jazz-tools@0.10.14
- jazz-react-native@0.10.14
- jazz-react-native-auth-clerk@0.10.14
- jazz-react-native-media-images@0.10.14
## 1.0.78
### Patch Changes

View File

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

View File

@@ -1,13 +1,5 @@
# chat-rn
## 1.0.75
### Patch Changes
- Updated dependencies [75211e3]
- jazz-tools@0.10.14
- jazz-react-native@0.10.14
## 1.0.74
### Patch Changes

View File

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

View File

@@ -1,14 +1,5 @@
# chat-vue
## 0.0.61
### Patch Changes
- Updated dependencies [75211e3]
- jazz-tools@0.10.14
- jazz-browser@0.10.14
- jazz-vue@0.10.14
## 0.0.60
### Patch Changes

View File

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

View File

@@ -1,14 +1,5 @@
# jazz-example-chat
## 0.0.157
### Patch Changes
- Updated dependencies [75211e3]
- jazz-tools@0.10.14
- jazz-react@0.10.14
- jazz-browser-media-images@0.10.14
## 0.0.156
### Patch Changes

View File

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

View File

@@ -1,14 +1,5 @@
# minimal-auth-clerk
## 0.0.56
### Patch Changes
- Updated dependencies [75211e3]
- jazz-tools@0.10.14
- jazz-react@0.10.14
- jazz-react-auth-clerk@0.10.14
## 0.0.55
### Patch Changes

View File

@@ -1,7 +1,7 @@
{
"name": "clerk",
"private": true,
"version": "0.0.56",
"version": "0.0.55",
"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.10.14",
"jazz-react-auth-clerk": "workspace:0.10.13",
"jazz-tools": "workspace:*",
"react": "^18.3.1",
"react-dom": "^18.3.1"

View File

@@ -1,13 +1,5 @@
# file-share-svelte
## 0.0.41
### Patch Changes
- Updated dependencies [75211e3]
- jazz-tools@0.10.14
- jazz-svelte@0.10.14
## 0.0.40
### Patch Changes

View File

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

View File

@@ -1,14 +1,5 @@
# form
## 0.0.52
### Patch Changes
- Updated dependencies [75211e3]
- jazz-tools@0.10.14
- jazz-react@0.10.14
- jazz-browser-media-images@0.10.14
## 0.0.51
### Patch Changes

View File

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

View File

@@ -1,14 +1,5 @@
# image-upload
## 0.0.54
### Patch Changes
- Updated dependencies [75211e3]
- jazz-tools@0.10.14
- jazz-react@0.10.14
- jazz-browser-media-images@0.10.14
## 0.0.53
### Patch Changes

View File

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

View File

@@ -83,10 +83,7 @@ export default function CoJsonViewerApp() {
const addAccount = (id: RawAccountID, secret: AgentSecret) => {
const newAccount = { id, secret };
const accountExists = accounts.some((account) => account.id === id);
if (!accountExists) {
setAccounts([...accounts, newAccount]);
}
setAccounts([...accounts, newAccount]);
setCurrentAccount(newAccount);
};

View File

@@ -1,14 +1,5 @@
# jazz-example-musicplayer
## 0.0.78
### Patch Changes
- Updated dependencies [75211e3]
- jazz-tools@0.10.14
- jazz-inspector@0.10.11
- jazz-react@0.10.14
## 0.0.77
### Patch Changes

View File

@@ -1,7 +1,7 @@
{
"name": "jazz-example-music-player",
"private": true,
"version": "0.0.78",
"version": "0.0.77",
"type": "module",
"scripts": {
"dev": "vite",
@@ -22,8 +22,8 @@
"class-variance-authority": "^0.7.0",
"clsx": "^2.0.0",
"jazz-inspector": "workspace:*",
"jazz-react": "workspace:0.10.14",
"jazz-tools": "workspace:0.10.14",
"jazz-react": "workspace:0.10.13",
"jazz-tools": "workspace:0.10.13",
"lucide-react": "^0.274.0",
"react": "^18.3.1",
"react-dom": "^18.3.1",

View File

@@ -1,13 +1,5 @@
# organization
## 0.0.50
### Patch Changes
- Updated dependencies [75211e3]
- jazz-tools@0.10.14
- jazz-react@0.10.14
## 0.0.49
### Patch Changes

View File

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

View File

@@ -1,11 +1,5 @@
# passkey-svelte
## 0.0.45
### Patch Changes
- jazz-svelte@0.10.14
## 0.0.44
### Patch Changes

View File

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

View File

@@ -1,13 +1,5 @@
# minimal-auth-passkey
## 0.0.55
### Patch Changes
- Updated dependencies [75211e3]
- jazz-tools@0.10.14
- jazz-react@0.10.14
## 0.0.54
### Patch Changes

View File

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

View File

@@ -1,13 +1,5 @@
# passphrase
## 0.0.52
### Patch Changes
- Updated dependencies [75211e3]
- jazz-tools@0.10.14
- jazz-react@0.10.14
## 0.0.51
### Patch Changes

View File

@@ -1,7 +1,7 @@
{
"name": "passphrase",
"private": true,
"version": "0.0.52",
"version": "0.0.51",
"type": "module",
"scripts": {
"dev": "vite",

View File

@@ -1,13 +1,5 @@
# jazz-password-manager
## 0.0.76
### Patch Changes
- Updated dependencies [75211e3]
- jazz-tools@0.10.14
- jazz-react@0.10.14
## 0.0.75
### Patch Changes

View File

@@ -1,7 +1,7 @@
{
"name": "jazz-password-manager",
"private": true,
"version": "0.0.76",
"version": "0.0.75",
"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.10.14",
"jazz-tools": "workspace:0.10.14",
"jazz-react": "workspace:0.10.13",
"jazz-tools": "workspace:0.10.13",
"react": "^18.3.1",
"react-dom": "^18.3.1",
"react-hook-form": "^7.41.5",

View File

@@ -1,14 +1,5 @@
# jazz-example-pets
## 0.0.174
### Patch Changes
- Updated dependencies [75211e3]
- jazz-tools@0.10.14
- jazz-react@0.10.14
- jazz-browser-media-images@0.10.14
## 0.0.173
### Patch Changes

View File

@@ -1,7 +1,7 @@
{
"name": "jazz-example-pets",
"private": true,
"version": "0.0.174",
"version": "0.0.173",
"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.10.14",
"jazz-react": "workspace:0.10.14",
"jazz-tools": "workspace:0.10.14",
"jazz-browser-media-images": "workspace:0.10.13",
"jazz-react": "workspace:0.10.13",
"jazz-tools": "workspace:0.10.13",
"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.10.14",
"jazz-run": "workspace:0.10.13",
"postcss": "^8.4.27",
"tailwindcss": "^3.4.17",
"typescript": "~5.6.2",

View File

@@ -1,14 +1,5 @@
# reactions
## 0.0.54
### Patch Changes
- Updated dependencies [75211e3]
- jazz-tools@0.10.14
- jazz-react@0.10.14
- jazz-browser-media-images@0.10.14
## 0.0.53
### Patch Changes

View File

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

View File

@@ -1,14 +1,5 @@
# todo-vue
## 0.0.59
### Patch Changes
- Updated dependencies [75211e3]
- jazz-tools@0.10.14
- jazz-browser@0.10.14
- jazz-vue@0.10.14
## 0.0.58
### Patch Changes

View File

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

View File

@@ -1,13 +1,5 @@
# jazz-example-todo
## 0.0.173
### Patch Changes
- Updated dependencies [75211e3]
- jazz-tools@0.10.14
- jazz-react@0.10.14
## 0.0.172
### Patch Changes

View File

@@ -1,7 +1,7 @@
{
"name": "jazz-example-todo",
"private": true,
"version": "0.0.173",
"version": "0.0.172",
"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.10.14",
"jazz-tools": "workspace:0.10.14",
"jazz-react": "workspace:0.10.13",
"jazz-tools": "workspace:0.10.13",
"lucide-react": "^0.274.0",
"qrcode": "^1.5.3",
"react": "^18.3.1",

View File

@@ -1,13 +1,5 @@
# version-history
## 0.0.51
### Patch Changes
- Updated dependencies [75211e3]
- jazz-tools@0.10.14
- jazz-react@0.10.14
## 0.0.50
### Patch Changes

View File

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

View File

@@ -665,7 +665,7 @@ export function ProjectComponent({ projectID }: { projectID: ID<Project> }) {//
The loading-depth spec `{ issues: [{}] }` means "in `Project`, load `issues` and load each item in `issues` shallowly". (Since an `Issue` doesn't have any further references, "shallowly" actually means all its properties will be available).
- Now, we can get rid of a lot of conditional accesses because we know that once `project` is loaded, `project.issues` and each `Issue` in it will be loaded as well.
- Now, we can get rid of a lot of coniditional accesses because we know that once `project` is loaded, `project.issues` and each `Issue` in it will be loaded as well.
- This also results in only one rerender and visual update when everything is loaded, which is faster (especially for long lists) and gives you more control over the loading UX.
{/* TODO: explain about not loaded vs not set/defined and `_refs` basics */}

View File

@@ -1,225 +0,0 @@
export const metadata = { title: "CoFeeds" };
import { CodeGroup, ComingSoon, ContentByFramework } from "@/components/forMdx";
# CoFeeds
CoFeeds are append-only data structures that track entries from different user sessions and accounts. Unlike other CoValues where everyone edits the same data, CoFeeds maintain separate streams for each session.
Each account can have multiple sessions (different browser tabs, devices, or app instances), making CoFeeds ideal for building features like activity logs, presence indicators, and notification systems.
The [Reactions example](https://github.com/garden-co/jazz/tree/main/examples/reactions) demonstrates a practical use of CoFeeds.
## Creating CoFeeds
CoFeeds are defined by specifying the type of items they'll contain, similar to how you define CoLists:
<CodeGroup>
```ts
// Define a schema for feed items
class Activity extends CoMap {
timestamp = co.Date;
action = co.literal("watering", "planting", "harvesting", "maintenance");
notes = co.optional.string;
}
// Define a feed of garden activities
class ActivityFeed extends CoFeed.Of(co.ref(Activity)) {}
// Create a feed instance
const activityFeed = ActivityFeed.create([]);
```
</CodeGroup>
Like other CoValues, you can specify [ownership](/docs/using-covalues/ownership) when creating CoFeeds.
## Reading from CoFeeds
Since CoFeeds are made of entries from users over multiple sessions, you can access entries in different ways - from a specific user's session or from their account as a whole.
### Per-Session Access
To retrieve entries from a session:
<CodeGroup>
```ts
// Get the feed for a specific session
const sessionFeed = activityFeed.perSession[sessionId];
// Latest entry from a session
console.log(sessionFeed.value.action); // "watering"
```
</CodeGroup>
For convenience, you can also access the latest entry from the current session with `inCurrentSession`:
<CodeGroup>
```ts
// Get the feed for the current session
const currentSessionFeed = activityFeed.inCurrentSession;
// Latest entry from the current session
console.log(currentSessionFeed.value.action); // "harvesting"
```
</CodeGroup>
### Per-Account Access
To retrieve entries from a specific account you can use bracket notation with the account ID:
<CodeGroup>
```ts
// Get the feed for a specific account
const accountFeed = activityFeed[accountId];
// Latest entry from the account
console.log(accountFeed.value.action); // "watering"
```
</CodeGroup>
For convenience, you can also access the latest entry from the current account with `byMe`:
<CodeGroup>
```ts
// Get the feed for the current account
const myLatestEntry = activityFeed.byMe;
// Latest entry from the current account
console.log(myLatestEntry.value.action); // "harvesting"
```
</CodeGroup>
### Feed Entries
#### All Entries
To retrieve all entries from a CoFeed:
<CodeGroup>
```ts
// Get the feeds for a specific account and session
const accountFeed = activityFeed[accountId];
const sessionFeed = activityFeed.perSession[sessionId];
// Iterate over all entries from the account
for (const entry of accountFeed.all) {
console.log(entry.value);
}
// Iterate over all entries from the session
for (const entry of sessionFeed.all) {
console.log(entry.value);
}
```
</CodeGroup>
#### Latest Entry
To retrieve the latest entry from a CoFeed, ie. the last update:
<CodeGroup>
```ts
// Get the latest entry from the current account
const latestEntry = activityFeed.byMe;
console.log(`My last action was ${latestEntry.value.action}`);
// "My last action was harvesting"
// Get the latest entry from each account
const latestEntriesByAccount = Object.values(activityFeed).map(entry => ({
accountName: entry.by?.profile?.name,
value: entry.value,
}));
```
</CodeGroup>
## Writing to CoFeeds
CoFeeds are append-only; you can add new items, but not modify existing ones. This creates a chronological record of events or activities.
### Adding Items
<CodeGroup>
```ts
// Log a new activity
activityFeed.push(Activity.create({
timestamp: new Date(),
action: "watering",
notes: "Extra water for new seedlings"
}));
```
</CodeGroup>
Each item is automatically associated with the current user's session. You don't need to specify which session the item belongs to - Jazz handles this automatically.
### Understanding Session Context
Each entry is automatically added to the current session's feed. When a user has multiple open sessions (like both a mobile app and web browser), each session creates its own separate entries:
<CodeGroup>
```ts
// On mobile device:
fromMobileFeed.push(Activity.create({
timestamp: new Date(),
action: "harvesting",
location: "Vegetable patch"
}));
// On web browser (same user):
fromBrowserFeed.push(Activity.create({
timestamp: new Date(),
action: "planting",
location: "Flower bed"
}));
// These are separate entries in the same feed, from the same account
```
</CodeGroup>
## Metadata
CoFeeds support metadata, which is useful for tracking information about the feed itself.
### By
The `by` property is the account that made the entry.
<CodeGroup>
```ts
const accountFeed = activityFeed[accountId];
// Get the account that made the last entry
console.log(accountFeed?.by);
```
</CodeGroup>
### MadeAt
The `madeAt` property is a timestamp of when the entry was added to the feed.
<CodeGroup>
```ts
const accountFeed = activityFeed[accountId];
// Get the timestamp of the last update
console.log(accountFeed?.madeAt);
// Get the timestamp of each entry
for (const entry of accountFeed.all) {
console.log(entry.madeAt);
}
```
</CodeGroup>
## Best Practices
### When to Use CoFeeds
- **Use CoFeeds when**:
- You need to track per-user/per-session data
- Time-based information matters (activity logs, presence)
- **Consider alternatives when**:
- Data needs to be collaboratively edited (use CoMaps or CoLists)
- You need structured relationships (use CoMaps/CoLists with references)

View File

@@ -1,192 +0,0 @@
import { CodeGroup, ContentByFramework } from "@/components/forMdx";
export const metadata = { title: "CoLists" };
# CoLists
CoLists are ordered collections that work like JavaScript arrays. They provide indexed access, iteration methods, and length properties, making them perfect for managing sequences of items.
## Creating CoLists
CoLists are defined by specifying the type of items they contain:
<CodeGroup>
```ts
class ListOfResources extends CoList.Of(co.string) {}
class ListOfTasks extends CoList.Of(co.ref(Task)) {}
```
</CodeGroup>
To instantiate a CoList:
<CodeGroup>
```ts
// Create an empty list
const resources = ListOfResources.create([]);
// Create a list with initial items
const tasks = ListOfTasks.create([
Task.create({ title: "Prepare soil beds", status: "in-progress" }),
Task.create({ title: "Order compost", status: "todo" })
]);
```
</CodeGroup>
Like other CoValues, you can specify [ownership](/docs/using-covalues/ownership) when creating CoLists.
## Reading from CoLists
CoLists support standard array access patterns:
<CodeGroup>
```ts
// Access by index
const firstTask = tasks[0];
console.log(firstTask.title); // "Prepare soil beds"
// Get list length
console.log(tasks.length); // 2
// Iteration
tasks.forEach(task => {
console.log(task.title);
// "Prepare soil beds"
// "Order compost"
});
// Array methods
const todoTasks = tasks.filter(task => task.status === "todo");
console.log(todoTasks.length); // 1
```
</CodeGroup>
## Writing to CoLists
CoLists support all the standard JavaScript array mutation methods:
<CodeGroup>
```ts
// Add items
resources.push("Courgette"); // Add to end
resources.unshift("Lettuce"); // Add to beginning
console.log(resources);
// ["Lettuce", "Tomatoes", "Basil", "Peppers", "Courgette"]
// Add complex items to lists of references
tasks.push(Task.create({
title: "Install irrigation system",
status: "todo"
}));
// Remove items
resources.pop(); // Remove last item
resources.shift(); // Remove first item
resources.splice(1, 2); // Remove items at index 1 and 2
// Replace items
resources[0] = "Cucumber"; // Replace first item
console.log(resources); // ["Cucumber"]
// Modify items in a list of references
tasks[0].status = "in-progress"; // Modify a property of an item
```
</CodeGroup>
### Type Safety
CoLists maintain type safety for their items:
<CodeGroup>
```ts
// TypeScript knows each item's type
resources.push("Carrots"); // ✓ Valid string
resources.push(42); // ✗ Type error: expected string
// For lists of references, TypeScript knows the referenced type
tasks.forEach(task => {
console.log(task.title); // TypeScript knows 'task' has a 'title'
});
```
</CodeGroup>
### Array Methods
CoLists support many standard JavaScript array methods:
<CodeGroup>
```ts
resources.push("Tomatoes", "Basil", "Peppers");
// Filter
const springResources = resources.filter(resource => resource.includes("Tomato"));
console.log(springResources); // ["Tomatoes"]
// Map (creates a regular array, not a CoList)
const resourceNames = resources.map(resource => resource.toUpperCase());
console.log(resourceNames); // ["TOMATOES", "BASIL", "PEPPERS"]
// Find
const basil = resources.find(resource => resource === "Basil");
// Sort (modifies the CoList in-place)
resources.sort();
console.log(resources); // ["Basil", "Cucumber", "Peppers", "Tomatoes"]
```
</CodeGroup>
## Best Practices
### Common Patterns
#### List Rendering
CoLists work well with UI rendering libraries:
<CodeGroup>
```tsx
// React example
function TaskList({ tasks }) {
return (
<ul>
{tasks.map(task => (
<li key={task.id}>
{task.title} - {task.status}
</li>
))}
</ul>
);
}
```
</CodeGroup>
#### Managing Relations
CoLists can be used to create one-to-many relationships:
<CodeGroup>
```ts
class Project extends CoMap {
name = co.string;
tasks = co.ref(ListOfTasks);
}
// ...
const task = Task.create({
title: "Plant seedlings",
status: "todo",
project: project, // Add a reference to the project
});
// Add a task to a garden project
project.tasks.push(task);
// Access the project from the task
console.log(task.project); // { name: "Garden Project", tasks: [task] }
```
</CodeGroup>

View File

@@ -1,199 +0,0 @@
import { CodeGroup, ContentByFramework } from "@/components/forMdx";
export const metadata = { title: "CoMaps" };
# CoMaps
CoMaps are key-value objects that work like JavaScript objects. You can access properties with dot notation and define typed fields that provide TypeScript safety. They're ideal for structured data that needs type validation.
## Creating CoMaps
CoMaps are typically defined by extending the `CoMap` class and specifying primitive fields using the `co` declarer (see [Defining schemas: CoValues](/docs/schemas/covalues) for more details on primitive fields):
<CodeGroup>
```ts
class Project extends CoMap {
name = co.string;
startDate = co.Date;
status = co.literal("planning", "active", "completed");
coordinator = co.optional.ref(Member);
}
```
</CodeGroup>
You can create either struct-like CoMaps with fixed fields (as above) or record-like CoMaps for key-value pairs:
<CodeGroup>
```ts
class Inventory extends CoMap.Record(co.number) {}
```
</CodeGroup>
To instantiate a CoMap:
<CodeGroup>
```ts
const project = Project.create({
name: "Spring Planting",
startDate: new Date("2025-03-15"),
status: "planning",
});
const inventory = Inventory.create({
tomatoes: 48,
basil: 12,
});
```
</CodeGroup>
### Ownership
When creating CoMaps, you can specify ownership to control access:
<CodeGroup>
```ts
// Create with default owner (current user)
const privateProject = Project.create({
name: "My Herb Garden",
startDate: new Date("2025-04-01"),
status: "planning",
});
// Create with shared ownership
const gardenGroup = Group.create();
gardenGroup.addMember(memberAccount, "writer");
const communityProject = Project.create(
{
name: "Community Vegetable Plot",
startDate: new Date("2025-03-20"),
status: "planning",
},
{ owner: gardenGroup },
);
```
</CodeGroup>
## Reading from CoMaps
CoMaps can be accessed using familiar JavaScript object notation:
<CodeGroup>
```ts
console.log(project.name); // "Spring Planting"
console.log(project.status); // "planning"
```
</CodeGroup>
### Handling Optional Fields
Optional fields require checks before access:
<CodeGroup>
```ts
if (project.coordinator) {
console.log(project.coordinator.name); // Safe access
}
```
</CodeGroup>
### Working with Record CoMaps
For record-type CoMaps, you can access values using bracket notation:
<CodeGroup>
```ts
const inventory = Inventory.create({
tomatoes: 48,
peppers: 24,
basil: 12
});
console.log(inventory["tomatoes"]); // 48
```
</CodeGroup>
## Updating CoMaps
Updating CoMap properties uses standard JavaScript assignment:
<CodeGroup>
```ts
project.name = "Spring Vegetable Garden"; // Update name
project.startDate = new Date("2025-03-20"); // Update date
```
</CodeGroup>
### Type Safety
CoMaps are fully typed in TypeScript, giving you autocomplete and error checking:
<CodeGroup>
```ts
project.name = "Spring Vegetable Planting"; // ✓ Valid string
project.startDate = "2025-03-15"; // ✗ Type error: expected Date
```
</CodeGroup>
### Deleting Properties
You can delete properties from CoMaps:
<CodeGroup>
```ts
delete inventory["basil"]; // Remove a key-value pair
// For optional fields in struct-like CoMaps
project.coordinator = null; // Remove the reference
```
</CodeGroup>
## Best Practices
### Structuring Data
- Use struct-like CoMaps for entities with fixed, known properties
- Use record-like CoMaps for dynamic key-value collections
- Group related properties into nested CoMaps for better organization
### Common Patterns
#### Using Computed Properties
CoMaps support computed properties and methods:
<CodeGroup>
```ts
class ComputedProject extends CoMap {
name = co.string;
startDate = co.Date;
endDate = co.optional.Date;
get isActive() {
const now = new Date();
return now >= this.startDate && (!this.endDate || now <= this.endDate);
}
formatDuration(format: "short" | "full") {
const start = this.startDate.toLocaleDateString();
if (!this.endDate) {
return format === "full"
? `Started on ${start}, ongoing`
: `From ${start}`;
}
const end = this.endDate.toLocaleDateString();
return format === "full"
? `From ${start} to ${end}`
: `${(this.endDate.getTime() - this.startDate.getTime()) / 86400000} days`;
}
}
// ...
console.log(computedProject.isActive); // false
console.log(computedProject.formatDuration("short")); // "3 days"
```
</CodeGroup>

View File

@@ -1,107 +0,0 @@
import { CodeGroup, ComingSoon, ContentByFramework } from "@/components/forMdx";
export const metadata = { title: "Creation & ownership" };
# Creation & Ownership
CoValues are collaborative by nature - anything you create can be shared and synced with others. Who gets to read or change each CoValue is controlled by its owner - either an individual `Account` or a shared `Group`. This foundation of ownership is what enables Jazz applications to support real-time collaboration while maintaining proper access control. Understanding how to create and manage ownership of CoValues is essential for building effectively with Jazz.
## Creating CoValues
Every CoValue starts with a [schema](/docs/schemas/covalues#start-your-app-with-a-schema). From there you can create CoValues with the `create` method. Creating CoValues is straightforward - you define the structure in your schema and then instantiate instances with initial values. These newly created CoValues automatically sync across devices and users who have access to them.
Here's a simple example:
<CodeGroup>
```ts
class Task extends CoMap {
title = co.string;
description = co.string;
status = co.literal("todo", "in-progress", "completed");
}
// Create a new task
const task = Task.create({
title: "Plant spring vegetables",
description: "Plant peas, carrots, and lettuce",
status: "todo",
});
```
</CodeGroup>
When you create a CoValue, you provide its initial data and optionally specify who owns it. The data must match the schema you defined - TypeScript will help ensure you get this right.
For more examples of creating different types of CoValues:
<CodeGroup>
```ts
// Creating a CoFeed for activity notifications
class ActivityNotification extends CoMap {
message = co.string;
type = co.literal("info", "warning", "success");
timestamp = co.Date;
}
class ActivityFeed extends CoFeed.Of(co.ref(ActivityNotification)) {}
const feed = ActivityFeed.create();
// Adding an item to the feed
feed.addItem(ActivityNotification.create({
message: "New task created",
type: "info",
timestamp: new Date()
}));
```
</CodeGroup>
## Ownership & Access Control
Every CoValue needs an owner to control who can access it. An owner can be an individual `Account`, but it's usually a `Group` since that lets you share with multiple people. The ownership model in Jazz provides fine-grained control over who can read, write, or administer your collaborative data. This system makes it easy to implement common patterns like shared workspaces, personal data, or public resources.
### Groups & Roles
Groups have members with different roles that control what they can do. These roles provide a permission system that's both simple to understand and powerful enough for complex collaboration scenarios. By assigning appropriate roles, you can control exactly who can view, edit, or manage access to your data.
<CodeGroup>
```ts
// Create a group
const gardenTeam = Group.create();
// Add garden members with different roles
gardenTeam.addMember(coordinator, "admin"); // Garden coordinator manages everything
gardenTeam.addMember(gardener, "writer"); // Gardeners can update tasks
gardenTeam.addMember(visitor, "reader"); // Visitors can view progress
// Create a list of tasks with the same owner
const taskList = ListOfTasks.create([]);
// Create a garden project with nested tasks, all with the same ownership
const springProject = Project.create({
name: "Spring Planting",
description: "Preparing the community garden for spring vegetables",
tasks: taskList
});
// Add tasks to the list
taskList.push(Task.create({
title: "Start tomato seedlings",
description: "Plant Roma and Cherry varieties in seed trays",
status: "todo"
});
taskList.push(Task.create({
title: "Prepare herb garden",
description: "Clear old growth and add fresh compost",
status: "todo"
});
```
</CodeGroup>
Each role has specific permissions:
- `admin`: Full control including managing members
- `writer`: Can modify content
- `reader`: Can only read content
- `writerOnly`: Can only write to the CoValue, not read it
For more information on groups and roles, see the [Groups](/docs/groups/intro) documentation.

View File

@@ -1,269 +0,0 @@
import { CodeGroup } from "@/components/forMdx";
export const metadata = { title: "Metadata & time-travel" };
# Metadata & time-travel
One of Jazz's most powerful features is that every CoValue automatically tracks its complete edit history. This means you can see who changed what and when, examine the state of your data at any point in time, and build features like audit logs, activity feeds, and undo/redo functionality. This page explores how to access and work with the rich metadata that comes with every CoValue.
## Understanding Edit History
Every CoValue in Jazz maintains a full history of all changes made to it. This edit history is accessible through two main APIs:
`CoValue._edits` provides a structured, field-by-field view of a CoValue's edit history. It organizes edits by property name and makes them easily accessible. For each field:
- `_edits.fieldName` gives you the most recent edit
- `_edits.fieldName.all` provides all historical edits as an array
- `_edits.fieldName.madeAt` gives you the timestamp of the last edit
- Each edit contains the value, who made the change, and when it happened
`CoValue._raw` gives you access to the internal state and lower-level operations on a CoValue. As this is an internal API, it should be used with caution. If you find yourself using `_raw`, consider letting us know so we can consider adding a public API for your use case.
## Working with Edit History Metadata
CoValues track who made each change and when. Every edit has metadata attached to it, including the author, timestamp, value, and transaction ID. This metadata enables you to build powerful audit and history features without having to implement your own tracking system.
<CodeGroup>
```ts
class Task extends CoMap {
title = co.string;
description = co.string;
status = co.literal("todo", "in-progress", "completed");
priority = co.literal("low", "medium", "high");
subtasks = co.optional.ref(ListOfTasks);
}
class ListOfTasks extends CoList.Of(co.ref(Task)) {}
const task = Task.create({
title: "Plant spring vegetables",
description: "Plant peas, carrots, and lettuce in the south garden bed",
status: "todo",
priority: "medium",
});
// Change the status
task.status = "in-progress";
// Get the latest edit for a field
console.log("Latest edit:", task._edits.status);
// { value: "in-progress", by: Account, madeAt: Date, ... }
// Get when a field was last edited (timestamp)
const lastEditTime = task._edits.status.madeAt;
console.log(`Status was last changed at: ${lastEditTime?.toLocaleString()}`);
// Get the full edit history for a field
for (const edit of task._edits.status.all) {
console.log({
author: edit.by, // Account that made the change
timestamp: edit.madeAt, // When the change happened
value: edit.value, // Value of the change
});
}
```
</CodeGroup>
### Common Patterns
With knowledge of the edit history, you can build all sorts of useful features that enhance your application's user experience and administrative capabilities. Here are some common patterns that leverage CoValue metadata.
#### Audit Log
Getting all the changes to a CoValue in order allows you to build an audit log. This is especially useful for tracking important changes in collaborative environments or for compliance purposes:
<CodeGroup>
```ts
function getAuditLog(task: Task) {
const changes = [];
for (const field of Object.keys(task)) {
// Check if the field has edits to avoid accessing non-existent properties
if (task._edits[field as keyof typeof task._edits]) {
for (const edit of task._edits[field as keyof typeof task._edits].all) {
changes.push({
field,
...edit,
timestamp: edit.madeAt,
at: edit.madeAt,
by: edit.by,
});
}
}
}
// Sort by timestamp
return changes.sort((a, b) => b.at.getTime() - a.at.getTime());
}
// Example usage
const auditLog = getAuditLog(task);
auditLog.forEach((entry) => {
console.log(
`${entry.timestamp} - ${entry.field} changed to "${entry.value}" by ${entry.by?.id}`,
);
});
```
</CodeGroup>
#### Activity Feeds
Activity feeds are a great way to see recent changes to a CoValue, helping users understand what's happening in a collaborative workspace. They can show who did what and when, creating transparency in team environments:
<CodeGroup>
```ts
function getRecentActivity(project: Project) {
const activity = [];
const hourAgo = new Date(Date.now() - 3600000);
for (const field of Object.keys(project)) {
// Skip if the field doesn't have edits
if (!project._edits[field as keyof typeof project._edits]) continue;
for (const edit of project._edits[field as keyof typeof project._edits].all) {
if (edit.madeAt > hourAgo) {
activity.push({
field,
value: edit.value,
by: edit.by,
at: edit.madeAt
});
}
}
}
return activity.sort((a, b) => b.at.getTime() - a.at.getTime());
}
// Example usage
const recentActivity = getRecentActivity(gardenProject);
console.log("Recent Garden Activity:");
recentActivity.forEach(activity => {
console.log(`${activity.at.toLocaleString()} - ${activity.field} updated by ${activity.by?.id}`);
});
```
</CodeGroup>
## Edit History & Time Travel
CoValues track their entire history of changes, creating a timeline you can explore. You can see who changed what and when, or even view past states of the data. This capability enables powerful debugging tools and user-facing features like history browsing and restoration of previous versions:
<CodeGroup>
```ts
class Task extends CoMap {
title = co.string;
description = co.string;
status = co.literal("todo", "in-progress", "completed");
priority = co.literal("low", "medium", "high");
}
// Create a new task
const task = Task.create({
title: "Plant spring vegetables",
description: "Plant peas, carrots, and lettuce in the south garden bed",
status: "todo",
priority: "medium",
});
// Make some changes
task.status = "in-progress";
task.priority = "high";
// See all edits for a field
for (const edit of task._edits.status.all) {
console.log(
`${edit.madeAt.toISOString()}: Status changed to "${edit.value}" by ${edit.by?.id}`,
);
}
// Get the initial value
const initialStatus = task._edits.status.all[0]?.value;
console.log(`Original status: ${initialStatus}`);
// Get a specific edit by index
const previousEdit = task._edits.status.all[1]; // Second edit
console.log(`Previous status: ${previousEdit?.value}`);
// Check who made the most recent change
const latestEdit = task._edits.status;
console.log(`Latest change made by: ${latestEdit?.by?.id}`);
```
</CodeGroup>
## Time Travel
The ability to view a CoValue as it existed at any point in time is one of Jazz's most powerful features. Looking into the past can help you understand how things changed - perfect for audit logs, debugging, or showing user activity. You can reconstruct the exact state of any CoValue at any moment in its history:
<CodeGroup>
```ts
class Project extends CoMap {
name = co.string;
status = co.literal("planning", "active", "completed");
lastUpdate = co.Date;
}
// See when a project was started
function findStatusChange(project: Project, targetStatus: string) {
// Get all the edits for the status field
const statusEdits = project._edits.status.all;
for (const edit of statusEdits) {
if (edit.value === targetStatus) {
console.log({
changeTime: edit.madeAt,
lastUpdate: project.lastUpdate,
changedBy: edit.by,
});
}
}
}
// Example usage
findStatusChange(gardenProject, "active");
```
</CodeGroup>
### Common Use Cases
The time travel capabilities of CoValues enable several practical use cases that would otherwise require complex custom implementations. Here are some examples of how you can use time travel in your applications:
<CodeGroup>
```ts
// Track task progress over time
function getTaskStatusHistory(task: Task, days: number = 7) {
const statusHistory = [];
const dayInMs = 86400000;
// Check every day for the past week
for (let day = 0; day < days; day++) {
const timePoint = new Date(Date.now() - day * dayInMs);
// Using the internal _raw API to get state at a specific point in time
const state = task._raw.atTime(timePoint);
statusHistory.push({
date: timePoint.toLocaleDateString(),
status: state.status,
priority: state.priority
});
}
return statusHistory;
}
// Example usage
const history = getTaskStatusHistory(plantingTask);
history.forEach(entry => {
console.log(`${entry.date}: Status was "${entry.status}" with ${entry.priority} priority`);
});
```
</CodeGroup>
### Best Practices
- Check field existence before accessing edits (`if (task._edits.fieldName)`)
- Access the most recent edit directly with `_edits.fieldName` instead of using any `.latest` property
- Cache historical queries if you're displaying them in UI
- Be specific about time ranges you care about
- Remember that accessing history requires loading the CoValue
- Consider using timestamps from your data rather than scanning all edits
Time travel is great for understanding how you got here, but keep queries focused on the range of time that matters to your use case.

View File

@@ -1,272 +0,0 @@
import { CodeGroup, ComingSoon, ContentByFramework } from "@/components/forMdx";
export const metadata = { title: "Reading from CoValues" };
# Reading from CoValues
Jazz lets you access your collaborative data with familiar JavaScript patterns while providing TypeScript type safety. Once you have a CoValue, you can read its values, traverse references, and iterate through collections using the same syntax you'd use with regular objects and arrays. This page covers how to read from different types of CoValues and handle loading states effectively.
<CodeGroup>
```ts
class Project extends CoMap {
name = co.string;
tasks = co.ref(ListOfTasks);
lead = co.optional.ref(TeamMember);
status = co.literal("planning", "active", "completed");
}
// Reading basic fields
console.log(project.name); // "Spring Garden Planning"
console.log(project.status); // "active"
// Reading from lists
for (const task of project.tasks) {
console.log(task.title); // "Plant tomato seedlings"
}
// Checking if an optional field exists
if (project.lead) {
console.log(project.lead.name); // "Maria Chen"
}
```
</CodeGroup>
## Different Types of CoValues
Jazz provides several CoValue types to represent different kinds of data. Each type has its own access patterns, but they all maintain the familiar JavaScript syntax you already know.
### CoMaps
`CoMap`s work like JavaScript objects, providing named properties you can access with dot notation. These are the most common CoValue type and form the foundation of most Jazz data models:
<CodeGroup>
```ts
class TeamMember extends CoMap {
name = co.string;
role = co.string;
active = co.boolean;
}
console.log(member.name); // "Maria Chen"
console.log(member.role); // "Garden Coordinator"
console.log(member.active); // true
```
</CodeGroup>
### CoLists
`CoList`s work like JavaScript arrays, supporting indexed access, iteration methods, and length properties. They're perfect for ordered collections of items where the order matters:
<CodeGroup>
```ts
class ListOfTasks extends CoList.Of(co.ref(Task)) {}
// Access items by index
console.log(tasks[0].title); // "Plant tomato seedlings"
// Use array methods
tasks.forEach(task => {
console.log(task.title); // "Plant tomato seedlings"
});
// Get list length
console.log(tasks.length); // 3
```
</CodeGroup>
### CoFeeds
`CoFeed`s provide a specialized way to track data from different sessions (tabs, devices, app instances). They're ideal for activity logs, presence indicators, or other session-specific streams of information. Each account can have multiple sessions, and each session maintains its own append-only log.
## Type Safety with CoValues
CoValues are fully typed in TypeScript, giving you the same autocomplete and error checking you'd expect from regular objects. This type safety helps catch errors at compile time rather than runtime, making your application more robust. Here's how the type system works with CoValues:
<CodeGroup>
```ts
class Project extends CoMap {
name = co.string;
memberCount = co.number;
priority = co.literal("low", "medium", "high");
lead = co.optional.ref(TeamMember);
tasks = co.ref(ListOfTasks);
}
// TypeScript knows exactly what fields exist
const project = await Project.load(gardenProjectId);
project.name = "Community Garden"; // ✓ string
project.memberCount = "few"; // ✗ Type error: expected number
project.priority = "urgent"; // ✗ Type error: must be low/medium/high
// Optional fields are handled safely
if (project.lead) {
console.log(project.lead.name); // Type safe
}
// Lists with specific item types
project.tasks.forEach(task => {
// TypeScript knows each task's structure
console.log(`${task.title}: ${task.status}`); // "Plant herbs: in-progress"
});
```
</CodeGroup>
## Loading States
When you load a CoValue, it might not be immediately available due to network latency or data size. Jazz provides patterns to handle these loading states gracefully, and TypeScript helps ensure you check for availability before accessing properties:
<CodeGroup>
```ts
const project = await Project.load(gardenProjectId);
if (!project) {
return "Data still loading";
}
```
</CodeGroup>
<ContentByFramework framework="react">
And in React, `useCoState` provides a similar pattern to allow you to wait for a CoValue to be loaded before accessing it:
<CodeGroup>
```tsx
// Type shows this might be `undefined` while loading
const project = useCoState(Project, gardenProjectId, {
tasks: [{}]
});
if (!project) {
return <div>Loading project data...</div>;
}
// TypeScript now knows project exists and has tasks loaded
return <div>{project.tasks.length}</div>;
```
</CodeGroup>
</ContentByFramework>
### Accessing Nested CoValues
Nested CoValues need special handling for loading and access. Since each reference might need to be loaded separately, you need patterns to manage these dependencies and handle loading states appropriately throughout your object graph.
<CodeGroup>
```ts
class Project extends CoMap {
name = co.string;
tasks = co.ref(ListOfTasks);
resources = co.optional.ref(ResourceList);
}
class Task extends CoMap {
title = co.string;
status = co.literal("todo", "in-progress", "completed");
subtasks = co.ref(ListOfSubtasks);
}
```
</CodeGroup>
### Loading
Loading nested data efficiently is important for performance. Jazz provides depth specifications to control exactly how much of your object graph is loaded, from shallow loading of just the top-level object to deep loading of complex nested structures:
<CodeGroup>
```ts
// Basic load - tasks won't be loaded yet
const project = await Project.load(gardenProjectId);
// Load with nested data
const projectWithTasks = await Project.load(gardenProjectId, { tasks: {} });
// Deep load pattern
const fullyLoaded = await Project.load(gardenProjectId, {
tasks: {
subtasks: {}
}
});
```
</CodeGroup>
More details on loading and subscribing to CoValues can be found in [Subscribing](/docs/using-covalues/subscribing-and-deep-loading).
### Handling Loading States
Unloaded references return `undefined`. This means you need to check for undefined values before trying to access properties of nested CoValues.
For general JavaScript/TypeScript usage, here's a pattern that works across any context:
<CodeGroup>
```ts
// Generic pattern for handling nested data
function processTaskData(project) {
// Check if project and its tasks are loaded
if (!project || !project.tasks) {
return "Data still loading";
}
// Safe to process tasks
const completedTasks = project.tasks.filter(task =>
task && task.status === "completed"
);
// Check for subtasks before accessing them
const subtaskCount = completedTasks.reduce((count, task) => {
if (!(task && task.subtasks)) return count
return count + task.subtasks.length;
}, 0);
return {
completedCount: completedTasks.length,
subtaskCount: subtaskCount
};
}
```
</CodeGroup>
<ContentByFramework framework="react">
Handle these loading states in your components:
<CodeGroup>
```tsx
// React pattern for handling nested data
function TaskList({ project }: { project: Project }) {
if (!project.tasks) {
return <div>Loading tasks...</div>;
}
return (
<div>
{project.tasks.map(task => {
// Handle potentially missing nested data
if (!task.subtasks) {
return <div key={task.id}>Loading subtasks...</div>;
}
return (
<div key={task.id}>
{task.title}: {task.subtasks.length} subtasks
</div>
);
})}
</div>
);
}
```
</CodeGroup>
</ContentByFramework>
Note: We're working on making these patterns more explicit and robust. We'll provide clearer loading states and better error handling patterns. For now, be defensive with your checks for `undefined`.
<CodeGroup>
```ts
// Current safest pattern for deep access
function getSubtasks(project: Project, taskTitle: string) {
const task = project.tasks?.find(t => t.title === taskTitle);
const subtasks = task?.subtasks;
if (!subtasks) {
return null; // Could mean loading or error
}
return subtasks.map(st => st.title);
}
```
</CodeGroup>
Stay tuned for updates to this API - we're working on making these patterns more robust and explicit.

View File

@@ -1,340 +0,0 @@
import { CodeGroup, ContentByFramework } from "@/components/forMdx";
export const metadata = { title: "Subscriptions & Deep Loading" };
# Subscriptions & Deep Loading
When working with collaborative applications, you need to know when data changes and ensure you have all the necessary related data. Jazz provides powerful subscription and deep loading capabilities that make it easy to keep your UI in sync with the underlying data and efficiently load complex object graphs.
## Understanding Subscriptions
Subscriptions in Jazz allow you to react to changes in CoValues. When a CoValue changes, all subscribers are notified with the updated value. This is essential for building reactive UIs that stay in sync with collaborative data.
<CodeGroup>
```ts
class Task extends CoMap {
title = co.string;
description = co.string;
status = co.literal("todo", "in-progress", "completed");
assignedTo = co.optional.string;
}
// ...
// Subscribe to a Task by ID
const unsubscribe = Task.subscribe(taskId, { /* loading depth */ }, (updatedTask) => {
console.log("Task updated:", updatedTask.title);
console.log("New status:", updatedTask.status);
});
// Later, when you're done:
unsubscribe();
```
</CodeGroup>
### Static vs. Instance Subscriptions
There are two main ways to subscribe to CoValues:
1. **Static Subscription** - When you have an ID but don't have the CoValue loaded yet:
<CodeGroup>
```ts
// Subscribe by ID (static method)
const unsubscribe = Task.subscribe(taskId, { /* loading depth */ }, (task) => {
if (task) {
console.log("Task loaded/updated:", task.title);
}
});
```
</CodeGroup>
2. **Instance Subscription** - When you already have a CoValue instance:
<CodeGroup>
```ts
// Subscribe to an instance (instance method)
const task = Task.create({
status: "todo",
title: "Cut the grass",
});
if (task) {
const unsubscribe = task.subscribe({ /* loading depth */ }, (updatedTask) => {
console.log("Task updated:", updatedTask.title);
});
}
```
</CodeGroup>
## Deep Loading
When working with related CoValues (like tasks in a project), you often need to load not just the top-level object but also its nested references. Jazz provides a flexible mechanism for specifying exactly how much of the object graph to load.
### Loading Depth Specifications
Loading depth specifications let you declare exactly which references to load and how deep to go:
<CodeGroup>
```ts
class Project extends CoMap {
name = co.string;
tasks = co.ref(ListOfTasks);
owner = co.ref(TeamMember);
}
class Task extends CoMap {
title = co.string;
subtasks = co.ref(ListOfSubtasks);
assignee = co.optional.ref(TeamMember);
}
// Load just the project, not its tasks
const project = await Project.load(projectId, {});
// Load the project and its tasks (but not subtasks)
const projectWithTasks = await Project.load(projectId, {
tasks: {}
});
// Load the project, its tasks, and their subtasks
const projectDeep = await Project.load(projectId, {
tasks: {
subtasks: {}
}
});
// Load the project, its tasks, and task assignees
const projectWithAssignees = await Project.load(projectId, {
tasks: {
assignee: {}
}
});
// Complex loading pattern: load project, tasks with their subtasks, and the project owner
const fullyLoaded = await Project.load(projectId, {
tasks: {
subtasks: {}
},
owner: {}
});
```
</CodeGroup>
The depth specification object mirrors the structure of your data model, making it intuitive to express which parts of the graph you want to load.
### Array Notation for Lists
For lists, you can use array notation to specify how to load the items:
<CodeGroup>
```ts
// Load project with all tasks but load each task shallowly
const project = await Project.load(projectId, {
tasks: [{}]
});
// Load project with tasks and load subtasks for each task
const project = await Project.load(projectId, {
tasks: [{
subtasks: [{}]
}]
});
```
</CodeGroup>
## Framework Integration
<ContentByFramework framework="react">
### React Integration with useCoState
In React applications, the `useCoState` hook provides a convenient way to subscribe to CoValues and handle loading states:
<CodeGroup>
```tsx
function GardenPlanner({ projectId }: { projectId: ID<Project> }) {
// Subscribe to a project and its tasks
const project = useCoState(Project, projectId, {
tasks: [{}]
});
// Handle loading state
if (!project) {
return <div>Loading garden project...</div>;
}
return (
<div>
<h1>{project.name}</h1>
<TaskList tasks={project.tasks} />
</div>
);
}
function TaskList({ tasks }: { tasks: Task[] }) {
return (
<ul>
{tasks.map(task => (
<li key={task.id}>
<span>{task.title}</span>
<span>{task.status}</span>
</li>
))}
</ul>
);
}
```
</CodeGroup>
The `useCoState` hook handles subscribing when the component mounts and unsubscribing when it unmounts, making it easy to keep your UI in sync with the underlying data.
</ContentByFramework>
<ContentByFramework framework="vue">
### Vue Integration
In Vue applications, you can use the `useCoState` composable to subscribe to CoValues:
<CodeGroup>
```vue
<script setup>
import { useCoState } from 'jazz-vue';
const props = defineProps({
projectId: String
});
// Subscribe to a project and its tasks
const project = useCoState(Project, props.projectId, {
tasks: [{}]
});
</script>
<template>
<div v-if="project">
<h1>{{ project.name }}</h1>
<ul>
<li v-for="task in project.tasks" :key="task.id">
{{ task.title }} - {{ task.status }}
</li>
</ul>
</div>
<div v-else>
Loading garden project...
</div>
</template>
```
</CodeGroup>
</ContentByFramework>
<ContentByFramework framework="svelte">
### Svelte Integration
In Svelte applications, you can use the `useCoState` function to subscribe to CoValues:
<CodeGroup>
```svelte
<script>
import { useCoState } from 'jazz-svelte';
export let projectId;
// Subscribe to a project and its tasks
const project = useCoState(Project, projectId, {
tasks: [{}]
});
</script>
{#if $project}
<h1>{$project.name}</h1>
<ul>
{#each $project.tasks as task (task.id)}
<li>{task.title} - {task.status}</li>
{/each}
</ul>
{:else}
<div>Loading garden project...</div>
{/if}
```
</CodeGroup>
</ContentByFramework>
## Ensuring Data is Loaded
Sometimes you need to make sure data is loaded before proceeding with an operation. The `ensureLoaded` method lets you guarantee that a CoValue and its referenced data are loaded to a specific depth:
<CodeGroup>
```ts
async function completeAllTasks(projectId: ID<Project>) {
// Ensure the project and its tasks are loaded
const project = await Project.load(projectId, {});
if (!project) return;
const loadedProject = await project.ensureLoaded({
tasks: [{}]
});
// Now we can safely access and modify tasks
loadedProject.tasks.forEach(task => {
task.status = "completed";
});
}
```
</CodeGroup>
## Performance Considerations
Loading depth is directly related to performance. Loading too much data can slow down your application, while loading too little can lead to "undefined" references. Here are some guidelines:
- **Load only what you need** for the current view or operation
- **Preload data** that will be needed soon to improve perceived performance
- Use **caching** to avoid reloading data that hasn't changed
{/* TODO: Add a note about supporting pagination */}
<CodeGroup>
```ts
// Bad: Loading everything deeply
const project = await Project.load(projectId, {
tasks: [{
subtasks: [{
comments: [{}]
}]
}],
members: [{}],
resources: [{}]
});
// Better: Loading only what's needed for the current view
const project = await Project.load(projectId, {
tasks: [{}] // Just load the tasks shallowly
});
// Later, when a task is selected:
const task = await Task.load(selectedTaskId, {
subtasks: [{}] // Now load its subtasks
});
```
</CodeGroup>
## Using a Loading Cache
By default, Jazz maintains a cache of loaded CoValues to avoid unnecessary network requests. This means that if you've already loaded a CoValue, subsequent load requests will use the cached version unless you explicitly request a refresh.
<CodeGroup>
```ts
// First load: fetches from network or local storage
const project = await Project.load(projectId, {});
// Later loads: uses cached version if available
const sameProject = await Project.load(projectId, {});
```
</CodeGroup>
## Best Practices
1. **Be explicit about loading depths**: Always specify exactly what you need
2. **Clean up subscriptions**: Always store and call the unsubscribe function when you're done
3. **Handle loading states**: Check for undefined/null before accessing properties
4. **Use framework integrations**: They handle subscription lifecycle automatically
5. **Balance depth and performance**: Load only what you need for the current view
By effectively using subscriptions and deep loading, you can build responsive, collaborative applications that handle complex data relationships while maintaining good performance.

View File

@@ -1,175 +0,0 @@
export const metadata = { title: "Writing & deleting CoValues" };
import { CodeGroup } from "@/components/forMdx";
# Writing & deleting CoValues
Collaborative applications need ways to update and remove data. Jazz makes this simple by treating CoValues like regular JavaScript objects while handling all the complexity of syncing changes in the background. This page covers how to modify CoValues, work with collections, handle concurrent edits, and properly remove data when needed.
## Writing to CoValues
Once you have a CoValue, modifying it is straightforward. You can update fields like regular JavaScript properties. Changes are applied locally first for immediate feedback, then synchronized to other users with access to the same CoValues. This approach provides a natural programming model while handling all the distributed systems complexity behind the scenes.
<CodeGroup>
```ts
class Task extends CoMap {
title = co.string;
status = co.literal("todo", "in-progress", "completed");
assignee = co.optional.string;
}
//...
// Update fields
task.status = "in-progress"; // Direct assignment
task.assignee = "Alex"; // Optional field
```
</CodeGroup>
### Working with Lists
CoLists support familiar array operations, making it easy to work with collections of data. You can add, remove, and modify items using the standard JavaScript array methods, while Jazz handles the collaborative aspects automatically. These operations work correctly even when multiple users are making changes simultaneously.
<CodeGroup>
```ts
class Project extends CoMap {
name = co.string;
tasks = co.ref(ListOfTasks);
}
//...
// Add items
project.tasks.push(Task.create({
title: "Build raised beds",
status: "todo"
}));
// Remove items
project.tasks.splice(2, 1); // Remove third task
// Update items
project.tasks[0].status = "in-progress";
// Bulk updates
project.tasks.forEach(task => {
if (task.status === "todo") {
task.status = "in-progress";
}
});
```
</CodeGroup>
Changes sync automatically to everyone with access. Any edits you make are immediately visible in your local view and propagate to other users as they sync.
## Concurrent Edits
CoValues use [CRDTs](/docs/schemas/covalues#defining-schemas-covalues) to handle concurrent edits smoothly. In most cases, you don't need to think about conflicts - Jazz handles them automatically. This conflict resolution happens transparently, allowing multiple users to make changes simultaneously without disruption or data loss.
<CodeGroup>
```ts
class Dashboard extends CoMap {
activeProjects = co.number;
status = co.literal("active", "maintenance");
notifications = co.ref(ListOfNotifications);
}
//...
// Multiple users can edit simultaneously
// Last-write-wins for simple fields
dashboard.status = "maintenance"; // Local change is immediate
dashboard.activeProjects = 5; // Syncs automatically
// Lists handle concurrent edits too
dashboard.notifications.push(Notification.create({
timestamp: new Date(),
message: "System update scheduled"
}));
```
</CodeGroup>
## Deleting CoValues
There are a few ways to delete CoValues, from simple field removal to full cleanup. Jazz provides flexible options for removing data depending on your needs. You can remove references while keeping the underlying data, remove items from lists, or completely delete CoValues when they're no longer needed.
<CodeGroup>
```ts
class Project extends CoMap {
tasks = co.ref(ListOfTasks);
resources = co.optional.ref(ListOfResources);
}
//...
// Remove a reference
project.resources = null; // Removes the reference but resources still exist
// Remove from a list
project.tasks.splice(2, 1); // Removes third team member from list
```
</CodeGroup>
### Best Practices
- Load everything you plan to delete
- Check permissions before attempting deletes
- Consider soft deletes for recoverable data
## Removing Data in CoValues
You can delete fields from any `CoMap` to remove specific properties while keeping the CoValue itself. This is useful when you need to clear certain data without affecting the rest of your object structure. The deletion operations are also synchronized to all users with access.
<CodeGroup>
```ts
class Project extends CoMap {
name = co.string;
team = co.ref(ListOfMembers);
budget = co.optional.ref(Budget);
}
//...
// Delete fields from a regular CoMap
delete project.budget; // Removes the budget reference
// Delete from a record-type CoMap
class ProjectTags extends CoMap.Record(co.string) {}
const projectTags = ProjectTags.create({
"priority-high": "High priority tasks",
});
delete projectTags["priority-high"]; // Removes specific tag
```
</CodeGroup>
For `CoList`s, use array methods:
<CodeGroup>
```ts
// Remove from lists using splice
project.team.splice(2, 1); // Removes third team member
```
</CodeGroup>
### Restoring Data
For data you might want to restore later, consider using status fields instead of permanent deletion. This "soft delete" pattern is common in applications where users might need to recover previously removed items. By using a boolean field to mark items as archived or deleted, you maintain the ability to restore them later.
<CodeGroup>
```ts
class Task extends CoMap {
title = co.string;
archived = co.boolean;
}
// Mark as archived
task.archived = true;
// Restore later
task.archived = false; // Task is back in the active list!
```
</CodeGroup>
Removed data remains in the edit history. If you need to handle sensitive information, plan your data model accordingly.

View File

@@ -111,43 +111,28 @@ export const docNavigationItems = [
name: "Using CoValues",
items: [
{
name: "CoMaps",
href: "/docs/using-covalues/comaps",
done: 80,
},
{
name: "CoLists",
href: "/docs/using-covalues/colists",
done: 80,
},
{
name: "CoFeeds",
href: "/docs/using-covalues/cofeeds",
done: 80,
},
{
name: "FileStreams",
href: "/docs/using-covalues/filestreams",
name: "Creation & ownership",
href: "/docs/using-covalues/creation",
done: 0,
},
{
name: "SchemaUnions",
href: "/docs/using-covalues/schemaunions",
name: "Reading",
href: "/docs/using-covalues/reading",
done: 0,
},
{
name: "Loading & subscribing",
href: "/docs/using-covalues/loading-and-subscribing",
name: "Subscribing & deep loading",
href: "/docs/using-covalues/subscription-and-loading",
done: 0,
},
{
name: "History & time travel",
href: "/docs/using-covalues/history-and-time-travel",
name: "Writing & deleting",
href: "/docs/using-covalues/writing",
done: 0,
},
{
name: "Access control",
href: "/docs/using-covalues/access-control",
name: "Metadata & time-travel",
href: "/docs/using-covalues/metadata",
done: 0,
},
],

View File

@@ -37,7 +37,7 @@ const config = {
function highlightPlugin() {
return async function transformer(tree) {
const highlighter = await getHighlighter({
langs: ["typescript", "bash", "tsx", "json", "svelte", "vue"],
langs: ["typescript", "bash", "tsx", "json", "svelte"],
theme: "css-variables", // use css variables in shiki.css
});

View File

@@ -1,11 +1,5 @@
# create-jazz-app
## 0.1.13
### Patch Changes
- b063ccc: Added Cursor docs to create-jazz-app
## 0.1.12
### Patch Changes

View File

@@ -5,7 +5,7 @@
"types": "src/index.ts",
"type": "module",
"license": "MIT",
"version": "0.1.13",
"version": "0.1.12",
"bin": {
"create-jazz-app": "./dist/index.js"
},

View File

@@ -1,13 +1,5 @@
# jazz-browser-media-images
## 0.10.14
### Patch Changes
- Updated dependencies [75211e3]
- jazz-tools@0.10.14
- jazz-browser@0.10.14
## 0.10.13
### Patch Changes

View File

@@ -1,14 +1,14 @@
{
"name": "jazz-auth-clerk",
"version": "0.10.14",
"version": "0.10.13",
"type": "module",
"main": "dist/index.js",
"types": "src/index.ts",
"license": "MIT",
"dependencies": {
"cojson": "workspace:0.10.8",
"jazz-browser": "workspace:0.10.14",
"jazz-tools": "workspace:0.10.14"
"jazz-browser": "workspace:0.10.13",
"jazz-tools": "workspace:0.10.13"
},
"scripts": {
"format-and-lint": "biome check .",

View File

@@ -1,13 +1,5 @@
# jazz-browser-media-images
## 0.10.14
### Patch Changes
- Updated dependencies [75211e3]
- jazz-tools@0.10.14
- jazz-browser@0.10.14
## 0.10.13
### Patch Changes

View File

@@ -1,6 +1,6 @@
{
"name": "jazz-browser-media-images",
"version": "0.10.14",
"version": "0.10.13",
"type": "module",
"main": "dist/index.js",
"types": "src/index.ts",
@@ -8,8 +8,8 @@
"dependencies": {
"@types/image-blob-reduce": "^4.1.1",
"image-blob-reduce": "^4.1.0",
"jazz-browser": "workspace:0.10.14",
"jazz-tools": "workspace:0.10.14",
"jazz-browser": "workspace:0.10.13",
"jazz-tools": "workspace:0.10.13",
"pica": "^9.0.1",
"typescript": "~5.6.2"
},

View File

@@ -1,12 +1,5 @@
# jazz-browser
## 0.10.14
### Patch Changes
- Updated dependencies [75211e3]
- jazz-tools@0.10.14
## 0.10.13
### Patch Changes

View File

@@ -1,6 +1,6 @@
{
"name": "jazz-browser",
"version": "0.10.14",
"version": "0.10.13",
"type": "module",
"main": "dist/index.js",
"types": "src/index.ts",

View File

@@ -1,13 +1,5 @@
# jazz-inspector
## 0.10.11
### Patch Changes
- Updated dependencies [75211e3]
- jazz-react-core@0.10.11
- jazz-tools@0.10.14
## 0.10.10
### Patch Changes

View File

@@ -1,6 +1,6 @@
{
"name": "jazz-inspector",
"version": "0.10.11",
"version": "0.10.10",
"type": "module",
"main": "./dist/app.js",
"types": "./dist/app.d.ts",

View File

@@ -1,12 +1,5 @@
# jazz-autosub
## 0.10.14
### Patch Changes
- Updated dependencies [75211e3]
- jazz-tools@0.10.14
## 0.10.13
### Patch Changes

View File

@@ -5,7 +5,7 @@
"types": "src/index.ts",
"type": "module",
"license": "MIT",
"version": "0.10.14",
"version": "0.10.13",
"dependencies": {
"cojson": "workspace:*",
"cojson-transport-ws": "workspace:*",

View File

@@ -1,15 +1,5 @@
# jazz-browser-media-images
## 0.10.14
### Patch Changes
- Updated dependencies [75211e3]
- jazz-tools@0.10.14
- jazz-react@0.10.14
- jazz-auth-clerk@0.10.14
- jazz-browser@0.10.14
## 0.10.13
### Patch Changes

View File

@@ -1,6 +1,6 @@
{
"name": "jazz-react-auth-clerk",
"version": "0.10.14",
"version": "0.10.13",
"type": "module",
"main": "dist/index.js",
"types": "src/index.tsx",

View File

@@ -1,13 +1,5 @@
# jazz-react-core
## 0.10.11
### Patch Changes
- 75211e3: Fixes invalid authentication state when logging out after signUp
- Updated dependencies [75211e3]
- jazz-tools@0.10.14
## 0.10.10
### Patch Changes

View File

@@ -1,6 +1,6 @@
{
"name": "jazz-react-core",
"version": "0.10.11",
"version": "0.10.10",
"type": "module",
"main": "dist/index.js",
"types": "src/index.ts",

View File

@@ -135,7 +135,14 @@ export function useCoState<V extends CoValue, D>(
() => observable.getCurrentValue(),
);
return value;
return React.useMemo(() => {
if (!id) {
observable.reset();
return undefined;
}
return value;
}, [id, value]);
}
export function createUseAccountHooks<Acc extends Account>() {

View File

@@ -1,10 +1,9 @@
// @vitest-environment happy-dom
import { mnemonicToEntropy } from "@scure/bip39";
import { Account, AuthSecretStorage, KvStoreContext } from "jazz-tools";
import { AuthSecretStorage, KvStoreContext } from "jazz-tools";
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import { usePassphraseAuth } from "../auth/PassphraseAuth";
import { createUseAccountHooks } from "../hooks";
import {
createJazzTestAccount,
createJazzTestGuest,
@@ -13,8 +12,6 @@ import {
import { testWordlist } from "./fixtures.js";
import { act, renderHook, waitFor } from "./testUtils";
const { useAccount } = createUseAccountHooks<Account>();
describe("usePassphraseAuth", () => {
beforeEach(async () => {
await setupJazzTestSync();
@@ -108,73 +105,4 @@ describe("usePassphraseAuth", () => {
expect(await result.current.signUp()).toBe(passphrase);
});
it("should be able to logout after sign up", async () => {
const account = await createJazzTestAccount({});
const accounts: string[] = [];
const updates: { state: string; accountIndex: number }[] = [];
const { result } = renderHook(
() => {
const passphraseAuth = usePassphraseAuth({ wordlist: testWordlist });
const account = useAccount();
if (!accounts.includes(account.me.id)) {
accounts.push(account.me.id);
}
updates.push({
state: passphraseAuth.state,
accountIndex: accounts.indexOf(account.me.id),
});
return { passphraseAuth, account };
},
{
account,
isAuthenticated: false,
},
);
expect(result.current?.passphraseAuth.state).toBe("anonymous");
expect(result.current?.account?.me).toBeDefined();
const id = result.current?.account?.me?.id;
await act(async () => {
await result.current?.passphraseAuth.signUp();
});
expect(result.current?.passphraseAuth.state).toBe("signedIn");
expect(result.current?.account?.me.id).toBe(id);
await act(async () => {
await result.current?.account?.logOut();
});
expect(result.current?.passphraseAuth.state).toBe("anonymous");
expect(result.current?.account?.me.id).not.toBe(id);
expect(updates).toMatchInlineSnapshot(`
[
{
"accountIndex": 0,
"state": "anonymous",
},
{
"accountIndex": 0,
"state": "anonymous",
},
{
"accountIndex": 0,
"state": "signedIn",
},
{
"accountIndex": 1,
"state": "anonymous",
},
]
`);
});
});

View File

@@ -1,14 +1,5 @@
# jazz-react-native-auth-clerk
## 0.10.14
### Patch Changes
- Updated dependencies [75211e3]
- jazz-tools@0.10.14
- jazz-react-native@0.10.14
- jazz-auth-clerk@0.10.14
## 0.10.13
### Patch Changes

View File

@@ -1,6 +1,6 @@
{
"name": "jazz-react-native-auth-clerk",
"version": "0.10.14",
"version": "0.10.13",
"type": "module",
"main": "dist/index.js",
"types": "src/index.tsx",

View File

@@ -1,12 +1,5 @@
# jazz-browser-media-images
## 0.10.14
### Patch Changes
- Updated dependencies [75211e3]
- jazz-tools@0.10.14
## 0.10.13
### Patch Changes

View File

@@ -1,6 +1,6 @@
{
"name": "jazz-react-native-media-images",
"version": "0.10.14",
"version": "0.10.13",
"type": "module",
"main": "dist/index.js",
"types": "src/index.ts",

View File

@@ -1,13 +1,5 @@
# jazz-browser
## 0.10.14
### Patch Changes
- Updated dependencies [75211e3]
- jazz-react-core@0.10.11
- jazz-tools@0.10.14
## 0.10.13
### Patch Changes

View File

@@ -1,6 +1,6 @@
{
"name": "jazz-react-native",
"version": "0.10.14",
"version": "0.10.13",
"type": "module",
"main": "./dist/index.js",
"module": "./dist/index.js",

View File

@@ -1,14 +1,5 @@
# jazz-react
## 0.10.14
### Patch Changes
- Updated dependencies [75211e3]
- jazz-react-core@0.10.11
- jazz-tools@0.10.14
- jazz-browser@0.10.14
## 0.10.13
### Patch Changes

View File

@@ -1,6 +1,6 @@
{
"name": "jazz-react",
"version": "0.10.14",
"version": "0.10.13",
"type": "module",
"main": "dist/index.js",
"types": "src/index.ts",
@@ -18,9 +18,9 @@
"dependencies": {
"@scure/bip39": "^1.3.0",
"cojson": "workspace:0.10.8",
"jazz-browser": "workspace:0.10.14",
"jazz-browser": "workspace:0.10.13",
"jazz-react-core": "workspace:*",
"jazz-tools": "workspace:0.10.14"
"jazz-tools": "workspace:0.10.13"
},
"devDependencies": {
"@testing-library/dom": "^10.4.0",

View File

@@ -1,12 +1,5 @@
# jazz-run
## 0.10.14
### Patch Changes
- Updated dependencies [75211e3]
- jazz-tools@0.10.14
## 0.10.13
### Patch Changes

View File

@@ -3,7 +3,7 @@
"bin": "./dist/index.js",
"type": "module",
"license": "MIT",
"version": "0.10.14",
"version": "0.10.13",
"exports": {
"./startSyncServer": {
"import": "./dist/startSyncServer.js",
@@ -32,7 +32,7 @@
"cojson-storage-sqlite": "workspace:0.10.8",
"cojson-transport-ws": "workspace:0.10.8",
"effect": "^3.6.5",
"jazz-tools": "workspace:0.10.14",
"jazz-tools": "workspace:0.10.13",
"ws": "^8.14.2"
},
"devDependencies": {

View File

@@ -1,13 +1,5 @@
# jazz-svelte
## 0.10.14
### Patch Changes
- Updated dependencies [75211e3]
- jazz-tools@0.10.14
- jazz-browser@0.10.14
## 0.10.13
### Patch Changes

View File

@@ -1,6 +1,6 @@
{
"name": "jazz-svelte",
"version": "0.10.14",
"version": "0.10.13",
"scripts": {
"dev": "vite dev",
"build": "vite build && npm run package",

View File

@@ -1,11 +1,5 @@
# jazz-tools
## 0.10.14
### Patch Changes
- 75211e3: Fixes invalid authentication state when logging out after signUp
## 0.10.13
### Patch Changes

View File

@@ -17,7 +17,7 @@
},
"type": "module",
"license": "MIT",
"version": "0.10.14",
"version": "0.10.13",
"dependencies": {
"@scure/bip39": "^1.3.0",
"cojson": "workspace:*"

View File

@@ -16,6 +16,7 @@ export type AuthSetPayload = {
export class AuthSecretStorage {
private listeners: Set<(isAuthenticated: boolean) => void>;
public isAuthenticated: boolean;
notify = false;
constructor() {
this.listeners = new Set();
@@ -96,7 +97,7 @@ export class AuthSecretStorage {
};
}
async setWithoutNotify(payload: AuthSetPayload) {
async set(payload: AuthSetPayload) {
const kvStore = KvStoreContext.getInstance().getStorage();
await kvStore.set(
STORAGE_KEY,
@@ -109,11 +110,10 @@ export class AuthSecretStorage {
provider: payload.provider,
}),
);
}
async set(payload: AuthSetPayload) {
this.setWithoutNotify(payload);
this.emitUpdate(payload);
if (this.notify) {
this.emitUpdate(payload);
}
}
getIsAuthenticated(data: AuthCredentials | null): boolean {
@@ -139,13 +139,12 @@ export class AuthSecretStorage {
}
}
async clearWithoutNotify() {
async clear() {
const kvStore = KvStoreContext.getInstance().getStorage();
await kvStore.delete(STORAGE_KEY);
}
async clear() {
await this.clearWithoutNotify();
this.emitUpdate(null);
if (this.notify) {
this.emitUpdate(null);
}
}
}

View File

@@ -43,6 +43,10 @@ export class JazzContextManager<
protected context: PlatformSpecificContext<Acc> | undefined;
protected props: P | undefined;
protected authSecretStorage = new AuthSecretStorage();
protected authSecretStorageWithNotify = Object.assign(
Object.create(this.authSecretStorage),
{ notify: true },
);
protected authenticating = false;
constructor() {
@@ -99,7 +103,9 @@ export class JazzContextManager<
}
getAuthSecretStorage() {
return this.authSecretStorage;
// External updates of the auth secret storage are notified by default (e.g. when registering a new Auth provider)
// We skip internal notify to ensure that the isAuthenticated changes are notified along with the context updates
return this.authSecretStorageWithNotify;
}
logOut = async () => {

View File

@@ -219,7 +219,7 @@ export async function createJazzContext<Acc extends Account>(options: {
AccountSchema: options.AccountSchema,
sessionProvider: options.sessionProvider,
onLogOut: () => {
authSecretStorage.clearWithoutNotify();
authSecretStorage.clear();
},
});
} else {
@@ -240,12 +240,12 @@ export async function createJazzContext<Acc extends Account>(options: {
crypto,
AccountSchema: options.AccountSchema,
onLogOut: async () => {
await authSecretStorage.clearWithoutNotify();
await authSecretStorage.clear();
},
});
if (!options.newAccountProps) {
await authSecretStorage.setWithoutNotify({
await authSecretStorage.set({
accountID: context.account.id,
secretSeed,
accountSecret: context.node.account.agentSecret,

View File

@@ -257,10 +257,11 @@ describe("AuthSecretStorage", () => {
});
});
describe("notify", () => {
describe("notify=true", () => {
beforeEach(() => {
kvStore.clearAll();
authSecretStorage = new AuthSecretStorage();
authSecretStorage.notify = true;
});
describe("set", () => {
@@ -336,7 +337,7 @@ describe("AuthSecretStorage", () => {
});
});
describe("without notify", () => {
describe("notify=false", () => {
beforeEach(() => {
kvStore.clearAll();
authSecretStorage = new AuthSecretStorage();
@@ -347,7 +348,7 @@ describe("AuthSecretStorage", () => {
const handler = vi.fn();
authSecretStorage.onUpdate(handler);
await authSecretStorage.setWithoutNotify({
await authSecretStorage.set({
accountID: "test123" as ID<Account>,
accountSecret:
"secret123" as `sealerSecret_z${string}/signerSecret_z${string}`,
@@ -364,7 +365,7 @@ describe("AuthSecretStorage", () => {
});
it("should return false for anonymous credentials", async () => {
await authSecretStorage.setWithoutNotify({
await authSecretStorage.set({
accountID: "test123" as ID<Account>,
accountSecret:
"secret123" as `sealerSecret_z${string}/signerSecret_z${string}`,
@@ -375,7 +376,7 @@ describe("AuthSecretStorage", () => {
});
it("should return true for non-anonymous credentials", async () => {
await authSecretStorage.setWithoutNotify({
await authSecretStorage.set({
accountID: "test123" as ID<Account>,
accountSecret:
"secret123" as `sealerSecret_z${string}/signerSecret_z${string}`,
@@ -394,7 +395,7 @@ describe("AuthSecretStorage", () => {
});
it("should return true when the provider is missing", async () => {
await authSecretStorage.setWithoutNotify({
await authSecretStorage.set({
accountID: "test123" as ID<Account>,
accountSecret:
"secret123" as `sealerSecret_z${string}/signerSecret_z${string}`,
@@ -413,7 +414,7 @@ describe("AuthSecretStorage", () => {
describe("clear", () => {
it("should not emit update event when clearing", async () => {
await authSecretStorage.setWithoutNotify({
await authSecretStorage.set({
accountID: "test123" as ID<Account>,
accountSecret:
"secret123" as `sealerSecret_z${string}/signerSecret_z${string}`,
@@ -423,7 +424,7 @@ describe("AuthSecretStorage", () => {
const handler = vi.fn();
authSecretStorage.onUpdate(handler);
await authSecretStorage.clearWithoutNotify();
await authSecretStorage.clear();
expect(handler).not.toHaveBeenCalled();
});

View File

@@ -1,7 +1,8 @@
// @vitest-environment happy-dom
import { mnemonicToEntropy } from "@scure/bip39";
import { AgentSecret } from "cojson";
import { PureJSCrypto } from "cojson/crypto/PureJSCrypto";
import { PureJSCrypto } from "cojson/src/crypto/PureJSCrypto";
import {
Account,
AuthSecretStorage,

View File

@@ -1,13 +1,5 @@
# jazz-react
## 0.10.14
### Patch Changes
- Updated dependencies [75211e3]
- jazz-tools@0.10.14
- jazz-browser@0.10.14
## 0.10.13
### Patch Changes

View File

@@ -1,6 +1,6 @@
{
"name": "jazz-vue",
"version": "0.10.14",
"version": "0.10.13",
"type": "module",
"main": "dist/index.js",
"types": "src/index.ts",

37
pnpm-lock.yaml generated
View File

@@ -444,7 +444,7 @@ importers:
specifier: workspace:*
version: link:../../packages/jazz-react
jazz-react-auth-clerk:
specifier: workspace:0.10.14
specifier: workspace:0.10.13
version: link:../../packages/jazz-react-auth-clerk
jazz-tools:
specifier: workspace:*
@@ -770,10 +770,10 @@ importers:
specifier: workspace:*
version: link:../../packages/jazz-inspector
jazz-react:
specifier: workspace:0.10.14
specifier: workspace:0.10.13
version: link:../../packages/jazz-react
jazz-tools:
specifier: workspace:0.10.14
specifier: workspace:0.10.13
version: link:../../packages/jazz-tools
lucide-react:
specifier: ^0.274.0
@@ -1012,10 +1012,10 @@ importers:
examples/password-manager:
dependencies:
jazz-react:
specifier: workspace:0.10.14
specifier: workspace:0.10.13
version: link:../../packages/jazz-react
jazz-tools:
specifier: workspace:0.10.14
specifier: workspace:0.10.13
version: link:../../packages/jazz-tools
react:
specifier: 18.3.1
@@ -1076,13 +1076,13 @@ importers:
specifier: ^2.0.0
version: 2.1.1
jazz-browser-media-images:
specifier: workspace:0.10.14
specifier: workspace:0.10.13
version: link:../../packages/jazz-browser-media-images
jazz-react:
specifier: workspace:0.10.14
specifier: workspace:0.10.13
version: link:../../packages/jazz-react
jazz-tools:
specifier: workspace:0.10.14
specifier: workspace:0.10.13
version: link:../../packages/jazz-tools
lucide-react:
specifier: ^0.274.0
@@ -1137,7 +1137,7 @@ importers:
specifier: ^3.0.1
version: 3.0.1
jazz-run:
specifier: workspace:0.10.14
specifier: workspace:0.10.13
version: link:../../packages/jazz-run
postcss:
specifier: ^8.4.27
@@ -1216,10 +1216,10 @@ importers:
specifier: ^2.0.0
version: 2.1.1
jazz-react:
specifier: workspace:0.10.14
specifier: workspace:0.10.13
version: link:../../packages/jazz-react
jazz-tools:
specifier: workspace:0.10.14
specifier: workspace:0.10.13
version: link:../../packages/jazz-tools
lucide-react:
specifier: ^0.274.0
@@ -1558,10 +1558,10 @@ importers:
specifier: workspace:0.10.8
version: link:../cojson
jazz-browser:
specifier: workspace:0.10.14
specifier: workspace:0.10.13
version: link:../jazz-browser
jazz-tools:
specifier: workspace:0.10.14
specifier: workspace:0.10.13
version: link:../jazz-tools
devDependencies:
typescript:
@@ -1599,10 +1599,10 @@ importers:
specifier: ^4.1.0
version: 4.1.0
jazz-browser:
specifier: workspace:0.10.14
specifier: workspace:0.10.13
version: link:../jazz-browser
jazz-tools:
specifier: workspace:0.10.14
specifier: workspace:0.10.13
version: link:../jazz-tools
pica:
specifier: ^9.0.1
@@ -1677,13 +1677,13 @@ importers:
specifier: workspace:0.10.8
version: link:../cojson
jazz-browser:
specifier: workspace:0.10.14
specifier: workspace:0.10.13
version: link:../jazz-browser
jazz-react-core:
specifier: workspace:*
version: link:../jazz-react-core
jazz-tools:
specifier: workspace:0.10.14
specifier: workspace:0.10.13
version: link:../jazz-tools
devDependencies:
'@testing-library/dom':
@@ -1884,7 +1884,7 @@ importers:
specifier: ^3.6.5
version: 3.11.9
jazz-tools:
specifier: workspace:0.10.14
specifier: workspace:0.10.13
version: link:../jazz-tools
ws:
specifier: ^8.14.2
@@ -3343,7 +3343,6 @@ packages:
'@effect/schema@0.71.4':
resolution: {integrity: sha512-iAAEusrhHQ2xVVTHbnZhSgiSuL81s8befP1Bl+AI7PEJg++HfHQSOEnU+narX/f7udJZ1EY/Ir0G+ATXSK8TZg==}
deprecated: this package has been merged into the main effect package
peerDependencies:
effect: ^3.6.8

View File

@@ -1,13 +1,5 @@
# jazz-tailwind-demo-auth-starter
## 0.0.51
### Patch Changes
- Updated dependencies [75211e3]
- jazz-tools@0.10.14
- jazz-react@0.10.14
## 0.0.50
### Patch Changes

View File

@@ -1,7 +1,7 @@
{
"name": "jazz-tailwind-demo-auth-starter",
"private": true,
"version": "0.0.51",
"version": "0.0.50",
"type": "module",
"scripts": {
"dev": "vite",