Compare commits

...

82 Commits

Author SHA1 Message Date
Guido D'Orsi
1e6da19d5e fix: The .load function now returns null on error 2025-03-27 11:48:12 +01:00
Guido D'Orsi
10de4b6fc9 docs: document loading errors 2025-03-26 11:01:35 +01:00
Guido D'Orsi
2433344778 test: fix autoload test 2025-03-26 10:56:34 +01:00
Guido D'Orsi
4c01459942 fix(vue): fix types compilation for useAccount 2025-03-26 10:38:57 +01:00
Guido D'Orsi
8dacdd6e2f Merge pull request #1681 from garden-co/1656-document-loading-and-subscription
1656 Document loading and subscriptions
2025-03-25 19:16:39 +01:00
Guido D'Orsi
5b0580bfda docs: fix a broken vanilla example 2025-03-25 19:05:07 +01:00
Guido D'Orsi
2bed7e845d docs: complete the migration of the loading docs to twoslash 2025-03-25 18:55:25 +01:00
Anselm
76976026b7 Remove incorredct / unhelpful sections 2025-03-25 18:32:48 +01:00
Anselm
10ea8fbf88 Typecheck more of the subscribe and load docs, remove history docs again for now 2025-03-25 18:32:48 +01:00
Anselm
bd86b159b9 Fully type upgrade guide 2025-03-25 18:32:48 +01:00
Anselm
c4f5241818 More typechecking in upgrade guide 2025-03-25 18:32:48 +01:00
Anselm
181f433477 Fix Highlight component 2025-03-25 18:32:48 +01:00
Anselm
3897a7e137 Fix darkmode diff colours 2025-03-25 18:32:48 +01:00
Anselm
5082ecef3f Reintroduce Jazz colors 2025-03-25 18:32:47 +01:00
Anselm
268e433870 Typing in docs working 2025-03-25 18:32:47 +01:00
Anselm
6c185160c5 First attempt to make twoslash work 2025-03-25 18:32:47 +01:00
Anselm
d18323b74a Upgrade shiki and use built-in transformers for diffs 2025-03-25 18:32:47 +01:00
Anselm
edd91791c9 More details in deep loading 2025-03-25 18:32:47 +01:00
Anselm
958b13c050 Divide upgrade guide into breaking / new features 2025-03-25 18:32:47 +01:00
Anselm
bbe140f7be Remove incorrect stuff 2025-03-25 18:32:47 +01:00
Anselm
1625f82ab7 Clean up manual subscription & hooks 2025-03-25 18:32:47 +01:00
Anselm
843f729a62 Include current version of history & time travel 2025-03-25 18:32:47 +01:00
Anselm
cc4631bb42 "loading depth" -> "resolve query" 2025-03-25 18:32:47 +01:00
Anselm
3665ef0088 Container-like -> collections 2025-03-25 18:32:47 +01:00
Trisha Lim
e13039818e fix coming soon TOC 2025-03-25 18:32:44 +01:00
Benjamin S. Leveritt
2e79487982 Change to markdown + format
Signed-off-by: Benjamin S. Leveritt <benjamin@leveritt.co.uk>
2025-03-25 18:32:10 +01:00
Benjamin S. Leveritt
fc2c045a8d Fix ‘for example’
Signed-off-by: Benjamin S. Leveritt <benjamin@leveritt.co.uk>
2025-03-25 18:31:58 +01:00
Anselm
69bb94be06 Missing green line 2025-03-25 18:31:58 +01:00
Anselm
228c8fa796 Upgrade guide improvments 2025-03-25 18:31:58 +01:00
Benjamin S. Leveritt
a34b850824 Update CoMap.Record resolve example
Signed-off-by: Benjamin S. Leveritt <benjamin@leveritt.co.uk>
2025-03-25 18:31:45 +01:00
Benjamin S. Leveritt
96d518bb97 Remove auto-loading section
Signed-off-by: Benjamin S. Leveritt <benjamin@leveritt.co.uk>
2025-03-25 18:31:45 +01:00
Benjamin S. Leveritt
8355f5674d Add Vanilla examples
Signed-off-by: Benjamin S. Leveritt <benjamin@leveritt.co.uk>
2025-03-25 18:31:44 +01:00
Benjamin S. Leveritt
5c1d04ee88 Tweak copy
Signed-off-by: Benjamin S. Leveritt <benjamin@leveritt.co.uk>
2025-03-25 18:31:44 +01:00
Benjamin S. Leveritt
2ef98d01b0 Fix permissions in lists comment
Signed-off-by: Benjamin S. Leveritt <benjamin@leveritt.co.uk>
2025-03-25 18:31:44 +01:00
Benjamin S. Leveritt
15a86a3014 Move Framework detail to just under the fold
Signed-off-by: Benjamin S. Leveritt <benjamin@leveritt.co.uk>
2025-03-25 18:31:44 +01:00
Benjamin S. Leveritt
9c49704cf9 Update Subs and Loading docs
Signed-off-by: Benjamin S. Leveritt <benjamin@leveritt.co.uk>
2025-03-25 18:31:44 +01:00
Benjamin S. Leveritt
44f0d8d5c7 Update subs doc
Signed-off-by: Benjamin S. Leveritt <benjamin@leveritt.co.uk>
2025-03-25 18:31:44 +01:00
Benjamin S. Leveritt
d7af97d63f Fix version and date
Signed-off-by: Benjamin S. Leveritt <benjamin@leveritt.co.uk>
2025-03-25 18:31:41 +01:00
Guido D'Orsi
3b189e4def Merge pull request #1725 from garden-co/feat/increase-depth-limit
feat: increase depth limit to 10
2025-03-25 12:13:48 +01:00
Guido D'Orsi
7fe50922cc docs: update the version on the 0.12 upgrade guide 2025-03-25 11:05:09 +01:00
Guido D'Orsi
b04e2be665 feat: increase depth limit to 10 2025-03-25 11:03:23 +01:00
Guido D'Orsi
80b1535cdf Merge remote-tracking branch 'origin/main' into 0-12-0 2025-03-24 18:36:48 +01:00
Guido D'Orsi
3d882f0442 fix: update resolve in the new music player action 2025-03-14 15:25:23 +01:00
Guido D'Orsi
f61d568c9d Merge remote-tracking branch 'origin/main' into 0-12-0 2025-03-14 15:21:09 +01:00
Guido D'Orsi
6dd02d289c chore: fix a type error in the tests 2025-03-11 17:22:26 +01:00
Guido D'Orsi
33a4944ba3 Merge remote-tracking branch 'origin/jazz-581-add-docs' into 0-12-0 2025-03-11 17:17:26 +01:00
Guido D'Orsi
e367b6056d Merge remote-tracking branch 'origin/main' into jazz-581-rfc-new-deep-loading-api 2025-03-11 17:14:38 +01:00
Guido D'Orsi
f3f56b9be0 docs: clarifications 2025-03-06 14:42:30 +01:00
Guido D'Orsi
4cae6bad34 Merge 2025-03-06 14:38:01 +01:00
Guido D'Orsi
17f2ef57de docs: bump the upgrade version 2025-03-06 14:37:19 +01:00
Guido D'Orsi
3a4d111a37 Merge remote-tracking branch 'origin/main' into jazz-581-rfc-new-deep-loading-api 2025-03-06 14:33:18 +01:00
Guido D'Orsi
1e18c7f5fc Merge remote-tracking branch 'origin/0-11-0' into jazz-581-rfc-new-deep-loading-api 2025-02-28 14:58:32 +01:00
Guido D'Orsi
8c7a6b27ed docs: refine the examples and align the feature descripted with the implementation 2025-02-26 18:23:02 +01:00
Guido D'Orsi
91f96e1188 Merge branch 'jazz-581-rfc-new-deep-loading-api' into jazz-581-add-docs 2025-02-26 18:12:56 +01:00
Guido D'Orsi
28dac10723 Merge pull request #1517 from garden-co/fix/optional-fields-acl
feat(deepLoading): return undefined when an optional field is not accessible
2025-02-26 14:58:27 +01:00
Guido D'Orsi
9cb11e38dd feat(deepLoading): return undefined when an optional field is not accessible 2025-02-26 12:56:06 +01:00
Guido D'Orsi
f3e4bacb33 Merge remote-tracking branch 'origin/main' into jazz-581-rfc-new-deep-loading-api 2025-02-25 17:46:22 +01:00
Guido D'Orsi
626d43f07b Merge remote-tracking branch 'origin/main' into jazz-581-rfc-new-deep-loading-api 2025-02-21 18:27:14 +01:00
Benjamin S. Leveritt
1f5d073035 Update homepage/homepage/app/(docs)/docs/[framework]/[...slug]/upgrade/0-11-0.mdx
Co-authored-by: Guido D'Orsi <guido@float.com>
2025-02-13 17:34:20 +00:00
Benjamin S. Leveritt
a3b607e799 Update homepage/homepage/app/(docs)/docs/[framework]/[...slug]/upgrade/0-11-0.mdx
Co-authored-by: Guido D'Orsi <guido@float.com>
2025-02-13 17:34:06 +00:00
Benjamin S. Leveritt
8fb93502af Update homepage/homepage/app/(docs)/docs/[framework]/[...slug]/upgrade/0-11-0.mdx
Co-authored-by: Guido D'Orsi <guido@float.com>
2025-02-13 17:33:49 +00:00
Benjamin S. Leveritt
36774122e0 Updates react guide for new resolve API
Signed-off-by: Benjamin S. Leveritt <benjamin@leveritt.co.uk>
2025-02-13 16:08:52 +00:00
Benjamin S. Leveritt
a6923128c1 Adds upgrade guide
Signed-off-by: Benjamin S. Leveritt <benjamin@leveritt.co.uk>
2025-02-13 15:56:11 +00:00
Guido D'Orsi
706ca62feb Merge pull request #1363 from garden-co/unauthorized-deep-loading
fix: check CoValue permissions when loading/subscribing
2025-02-13 09:55:16 +01:00
Guido D'Orsi
01523dcca3 fix: check CoValue permissions when loading/subscribing 2025-02-13 09:19:19 +01:00
Guido D'Orsi
77f039b561 Merge remote-tracking branch 'origin/main' into jazz-581-rfc-new-deep-loading-api 2025-02-13 09:18:47 +01:00
Guido D'Orsi
d661ba77be chore: improve pre-release comment output 2025-02-12 11:32:05 +01:00
Guido D'Orsi
f8fbc59b6f Merge remote-tracking branch 'origin/main' into jazz-581-rfc-new-deep-loading-api 2025-02-11 16:26:12 +01:00
Guido D'Orsi
cce0d22007 fix: update resolve property 2025-02-11 15:15:44 +01:00
Guido D'Orsi
e3ff76e9cb Merge remote-tracking branch 'origin/authv2' into jazz-581-rfc-new-deep-loading-api 2025-02-11 15:12:51 +01:00
Guido D'Orsi
4cbf71bff7 Merge pull request #1338 from garden-co/new-deep-loading-extra-props-fix
fix: disallow extra props in the resolve type
2025-02-11 14:38:43 +01:00
Guido D'Orsi
ceb060243a fix: disallow extra props in the resolve type 2025-02-10 20:04:32 +01:00
Anselm
a70bebb96a Clean up new deep-loading API 2025-01-29 14:39:16 +00:00
Anselm
b3b2507c35 Merge branch 'main' into jazz-581-rfc-new-deep-loading-api 2025-01-27 11:36:08 +00:00
Anselm
6a8fa16b49 Fix form and chat-rn-clerk examples 2024-12-16 15:56:48 +00:00
Anselm
1f08807701 Merge branch 'main' into jazz-581-rfc-new-deep-loading-api 2024-12-16 15:37:39 +00:00
Anselm
ba4a7f6170 Remove temp vite config 2024-12-16 15:35:06 +00:00
Anselm
a2854e3602 Upgrade to minor version change 2024-12-16 11:25:00 +00:00
Anselm
4ea87dc494 Add changeset 2024-12-16 10:55:51 +00:00
Anselm
d8c87c5314 Use $each instead of each 2024-12-16 10:54:25 +00:00
Anselm
46f624a12e Replace 'items' with 'each' 2024-12-13 16:28:40 +00:00
Anselm
86ce770f38 Implement clearer syntax for deep loading 2024-12-13 15:12:42 +00:00
119 changed files with 3836 additions and 2571 deletions

View File

@@ -0,0 +1,6 @@
---
"jazz-tools": minor
"cojson": minor
---
Check CoValue access permissions when loading

View File

@@ -0,0 +1,5 @@
---
"jazz-tools": minor
---
Implement new API for deep loading

View File

@@ -0,0 +1,5 @@
---
"jazz-tools": minor
---
The .load function now returns `null` on error

View File

@@ -0,0 +1,5 @@
---
"cojson": minor
---
Return the EVERYONE role if the account is not direct a member of the group

View File

@@ -0,0 +1,5 @@
---
"jazz-vue": patch
---
Fix types compilation for useAccount

View File

@@ -28,7 +28,7 @@ export default function Conversation() {
const { me } = useAccount();
const [chat, setChat] = useState<Chat>();
const [message, setMessage] = useState("");
const loadedChat = useCoState(Chat, chat?.id, [{}]);
const loadedChat = useCoState(Chat, chat?.id, { resolve: { $each: true } });
const navigation = useNavigation();
const [isUploading, setIsUploading] = useState(false);
@@ -71,7 +71,7 @@ export default function Conversation() {
const loadChat = async (chatId: ID<Chat>) => {
try {
const chat = await Chat.load(chatId, me, []);
const chat = await Chat.load(chatId, me);
setChat(chat);
} catch (error) {
console.log("Error loading chat", error);

View File

@@ -20,7 +20,7 @@ import { Chat, Message } from "./schema";
export default function ChatScreen({ navigation }: { navigation: any }) {
const { me, logOut } = useAccount();
const [chatId, setChatId] = useState<ID<Chat>>();
const loadedChat = useCoState(Chat, chatId, [{}]);
const loadedChat = useCoState(Chat, chatId, { resolve: { $each: true } });
const [message, setMessage] = useState("");
const profile = useCoState(Profile, me._refs.profile?.id, {});

View File

@@ -49,7 +49,7 @@ export default defineComponent({
},
},
setup(props) {
const chat = useCoState(Chat, props.chatId, [{}]);
const chat = useCoState(Chat, props.chatId, { resolve: { $each: true } });
const showNLastMessages = ref(30);
const displayedMessages = computed(() => {

View File

@@ -17,8 +17,8 @@ import {
} from "./ui.tsx";
export function ChatScreen(props: { chatID: ID<Chat> }) {
const chat = useCoState(Chat, props.chatID, { resolve: { $each: true } });
const account = useAccount();
const chat = useCoState(Chat, props.chatID, [{}]);
const [showNLastMessages, setShowNLastMessages] = useState(30);
if (!chat)

View File

@@ -12,7 +12,9 @@ import {
} from "./schema.ts";
export function CreateOrder() {
const { me } = useAccount({ root: { draft: {}, orders: [] } });
const { me } = useAccount({
resolve: { root: { draft: true, orders: true } },
});
const router = useIframeHashRouter();
const [errors, setErrors] = useState<string[]>([]);
@@ -60,7 +62,7 @@ function CreateOrderForm({
onSave: (draft: DraftBubbleTeaOrder) => void;
}) {
const draft = useCoState(DraftBubbleTeaOrder, id, {
addOns: [],
resolve: { addOns: true },
});
if (!draft) return;

View File

@@ -2,7 +2,7 @@ import { useAccount } from "jazz-react";
export function DraftIndicator() {
const { me } = useAccount({
root: { draft: {} },
resolve: { root: { draft: true } },
});
if (me?.root.draft?.hasChanges) {

View File

@@ -6,7 +6,7 @@ import { OrderThumbnail } from "./OrderThumbnail.tsx";
import { BubbleTeaOrder } from "./schema.ts";
export function EditOrder(props: { id: ID<BubbleTeaOrder> }) {
const order = useCoState(BubbleTeaOrder, props.id, []);
const order = useCoState(BubbleTeaOrder, props.id);
if (!order) return;

View File

@@ -4,7 +4,7 @@ import { OrderThumbnail } from "./OrderThumbnail.tsx";
export function Orders() {
const { me } = useAccount({
root: { orders: [] },
resolve: { root: { orders: true } },
});
return (

View File

@@ -24,10 +24,7 @@ export function HomePage({ mediaPlayer }: { mediaPlayer: MediaPlayer }) {
* access rights to CoValues. We get it from the top-level provider `<WithJazz/>`.
*/
const { me } = useAccount({
root: {
rootPlaylist: {},
playlists: [],
},
resolve: { root: { rootPlaylist: true, playlists: true } },
});
const navigate = useNavigate();
@@ -51,8 +48,9 @@ export function HomePage({ mediaPlayer }: { mediaPlayer: MediaPlayer }) {
const params = useParams<{ playlistId: ID<Playlist> }>();
const playlistId = params.playlistId ?? me?.root._refs.rootPlaylist.id;
const playlist = useCoState(Playlist, playlistId, {
tracks: [],
resolve: { tracks: true },
});
const isRootPlaylist = !params.playlistId;

View File

@@ -27,9 +27,11 @@ export async function uploadMusicTracks(
isExampleTrack: boolean = false,
) {
const { root } = await MusicaAccount.getMe().ensureLoaded({
root: {
rootPlaylist: {
tracks: [],
resolve: {
root: {
rootPlaylist: {
tracks: true,
},
},
},
});
@@ -65,8 +67,10 @@ export async function uploadMusicTracks(
export async function createNewPlaylist() {
const { root } = await MusicaAccount.getMe().ensureLoaded({
root: {
playlists: [],
resolve: {
root: {
playlists: true,
},
},
});
@@ -149,9 +153,11 @@ export async function updateMusicTrackTitle(track: MusicTrack, title: string) {
export async function updateActivePlaylist(playlist?: Playlist) {
const { root } = await MusicaAccount.getMe().ensureLoaded({
root: {
activePlaylist: {},
rootPlaylist: {},
resolve: {
root: {
activePlaylist: true,
rootPlaylist: true,
},
},
});
@@ -160,7 +166,9 @@ export async function updateActivePlaylist(playlist?: Playlist) {
export async function updateActiveTrack(track: MusicTrack) {
const { root } = await MusicaAccount.getMe().ensureLoaded({
root: {},
resolve: {
root: {},
},
});
root.activeTrack = track;
@@ -170,17 +178,23 @@ export async function onAnonymousAccountDiscarded(
anonymousAccount: MusicaAccount,
) {
const { root: anonymousAccountRoot } = await anonymousAccount.ensureLoaded({
root: {
rootPlaylist: {
tracks: [{}],
resolve: {
root: {
rootPlaylist: {
tracks: {
$each: true,
},
},
},
},
});
const me = await MusicaAccount.getMe().ensureLoaded({
root: {
rootPlaylist: {
tracks: [],
resolve: {
root: {
rootPlaylist: {
tracks: true,
},
},
},
});
@@ -197,8 +211,10 @@ export async function onAnonymousAccountDiscarded(
export async function deletePlaylist(playlistId: string) {
const { root } = await MusicaAccount.getMe().ensureLoaded({
root: {
playlists: [],
resolve: {
root: {
playlists: true,
},
},
});

View File

@@ -9,7 +9,7 @@ import { getNextTrack, getPrevTrack } from "./lib/getters";
export function useMediaPlayer() {
const { me } = useAccount({
root: {},
resolve: { root: true },
});
const playState = usePlayState();

View File

@@ -16,8 +16,10 @@ export function InvitePage() {
const playlist = await Playlist.load(playlistId, {});
const me = await MusicaAccount.getMe().ensureLoaded({
root: {
playlists: [],
resolve: {
root: {
playlists: true,
},
},
});

View File

@@ -22,9 +22,13 @@ export function AuthModal({ open, onOpenChange }: AuthModalProps) {
const [error, setError] = useState<string | null>(null);
const { me } = useAccount({
root: {
rootPlaylist: {
tracks: [{}],
resolve: {
root: {
rootPlaylist: {
tracks: {
$each: true,
},
},
},
},
});

View File

@@ -30,9 +30,7 @@ export function MusicTrackRow({
const track = useCoState(MusicTrack, trackId);
const { me } = useAccount({
root: {
playlists: [{}],
},
resolve: { root: { playlists: { $each: true } } },
});
const playlists = me?.root.playlists ?? [];

View File

@@ -12,9 +12,7 @@ export function PlayerControls({ mediaPlayer }: { mediaPlayer: MediaPlayer }) {
const isPlaying = playState.value === "play";
const activePlaylist = useAccount({
root: {
activePlaylist: {},
},
resolve: { root: { activePlaylist: true } },
}).me?.root.activePlaylist;
useMediaEndListener(mediaPlayer.playNextTrack);
@@ -25,7 +23,7 @@ export function PlayerControls({ mediaPlayer }: { mediaPlayer: MediaPlayer }) {
});
const activeTrack = useCoState(MusicTrack, mediaPlayer.activeTrackId, {
waveform: {},
resolve: { waveform: true },
});
if (!activeTrack) return null;

View File

@@ -8,9 +8,7 @@ export function SidePanel() {
const { playlistId } = useParams();
const navigate = useNavigate();
const { me } = useAccount({
root: {
playlists: [{}],
},
resolve: { root: { playlists: { $each: true } } },
});
function handleAllTracksClick(evt: React.MouseEvent<HTMLAnchorElement>) {

View File

@@ -8,7 +8,6 @@ export function Waveform(props: { track: MusicTrack; height: number }) {
const waveformData = useCoState(
MusicTrackWaveform,
track._refs.waveform.id,
{},
)?.data;
const duration = track.duration;

View File

@@ -2,9 +2,11 @@ import { MusicaAccount } from "../1_schema";
export async function getNextTrack() {
const me = await MusicaAccount.getMe().ensureLoaded({
root: {
activePlaylist: {
tracks: [],
resolve: {
root: {
activePlaylist: {
tracks: true,
},
},
},
});
@@ -21,9 +23,11 @@ export async function getNextTrack() {
export async function getPrevTrack() {
const me = await MusicaAccount.getMe().ensureLoaded({
root: {
activePlaylist: {
tracks: [],
resolve: {
root: {
activePlaylist: {
tracks: true,
},
},
},
});

View File

@@ -13,7 +13,7 @@ export function useUploadExampleData() {
async function uploadOnboardingData() {
const me = await MusicaAccount.getMe().ensureLoaded({
root: {},
resolve: { root: true },
});
if (me.root.exampleDataLoaded) return;

View File

@@ -5,11 +5,11 @@ import { Organization } from "./schema.ts";
export function AcceptInvitePage() {
const navigate = useNavigate();
const { me } = useAccount({ root: { organizations: [] } });
const { me } = useAccount({ resolve: { root: { organizations: true } } });
const onAccept = (organizationId: ID<Organization>) => {
if (me?.root?.organizations) {
Organization.load(organizationId, me, []).then((organization) => {
Organization.load(organizationId).then((organization) => {
if (organization) {
// avoid duplicates
const ids = me.root.organizations.map(

View File

@@ -5,7 +5,7 @@ import { Heading } from "./components/Heading.tsx";
export function HomePage() {
const { me } = useAccount({
root: { organizations: [{}] },
resolve: { root: { organizations: true } },
});
if (!me?.root.organizations) return;

View File

@@ -3,7 +3,7 @@ import { UserIcon } from "lucide-react";
export function Layout({ children }: { children: React.ReactNode }) {
const { me, logOut } = useAccount({
root: { draftOrganization: {} },
resolve: { root: { draftOrganization: true } },
});
return (

View File

@@ -13,7 +13,7 @@ export function OrganizationPage() {
.organizationId;
const organization = useCoState(Organization, paramOrganizationId, {
projects: [],
resolve: { projects: true },
});
if (!organization) return <p>Loading organization...</p>;

View File

@@ -8,7 +8,7 @@ import { OrganizationForm } from "./OrganizationForm.tsx";
export function CreateOrganization() {
const { me } = useAccount({
root: { draftOrganization: {}, organizations: [] },
resolve: { root: { draftOrganization: true, organizations: true } },
});
const [errors, setErrors] = useState<string[]>([]);
const navigate = useNavigate();

View File

@@ -7,7 +7,7 @@ import { Organization } from "../schema.ts";
export function OrganizationSelector({ className }: { className?: string }) {
const { me } = useAccount({
root: { organizations: [{}] },
resolve: { root: { organizations: { $each: true } } },
});
const navigate = useNavigate();

View File

@@ -43,9 +43,11 @@ const VaultPage: React.FC = () => {
(item): item is Exclude<typeof item, null> => !!item,
) || [],
);
const folders = useCoState(FolderList, me.root?._refs.folders?.id, [
{ items: [{}] },
]);
const folders = useCoState(FolderList, me.root?._refs.folders?.id, {
resolve: {
$each: { items: { $each: true } },
},
});
const [selectedFolder, setSelectedFolder] = useState<Folder | undefined>();
const [isNewItemModalOpen, setIsNewItemModalOpen] = useState(false);

View File

@@ -60,11 +60,9 @@ export async function addSharedFolder(
me: PasswordManagerAccount,
) {
const [sharedFolder, account] = await Promise.all([
Folder.load(sharedFolderId, me, {}),
PasswordManagerAccount.load(me.id, me, {
root: {
folders: [],
},
Folder.load(sharedFolderId),
PasswordManagerAccount.load(me.id, {
resolve: { root: { folders: true } },
}),
]);

View File

@@ -14,7 +14,7 @@ const reactionEmojiMap: {
};
export function ReactionsScreen(props: { id: ID<Reactions> }) {
const reactions = useCoState(Reactions, props.id, []);
const reactions = useCoState(Reactions, props.id);
if (!reactions) return;

View File

@@ -4,15 +4,15 @@
<div class="section-header">
<h2>Folders</h2>
<div class="new-folder">
<input
v-model="newFolderName"
placeholder="New folder name"
<input
v-model="newFolderName"
placeholder="New folder name"
class="input"
/>
<button class="btn btn-primary" @click="createFolder">Create</button>
</div>
</div>
<div class="folder-list">
<div
v-for="folder in folders"
@@ -32,9 +32,9 @@
<div class="section-header">
<h2>{{ selectedFolder?.name }}</h2>
<div class="new-todo">
<input
v-model="newTodoTitle"
placeholder="Add a new task"
<input
v-model="newTodoTitle"
placeholder="Add a new task"
class="input"
/>
<button class="btn btn-primary" @click="createTodo">Add</button>
@@ -72,7 +72,9 @@ import { Folder, FolderList, ToDoItem, ToDoList } from "../schema";
const { me } = useAccount();
const computedFoldersId = computed(() => me.value?.root?.folders?.id);
const folders = useCoState(FolderList, computedFoldersId, [{ items: [{}] }]);
const folders = useCoState(FolderList, computedFoldersId, {
resolve: { $each: { items: true } },
});
const selectedFolder = ref<Folder>();
const newFolderName = ref("");

View File

@@ -121,7 +121,7 @@ export default function App() {
function HomeScreen() {
const { me } = useAccount({
root: { projects: [{}] },
resolve: { root: { projects: { $each: true } } },
});
const navigate = useNavigate();

View File

@@ -4,7 +4,9 @@ import { ID } from "jazz-tools";
import { IssueComponent } from "./Issue.tsx";
import { Issue, Project } from "./schema.ts";
export function ProjectComponent({ projectID }: { projectID: ID<Project> }) {
const project = useCoState(Project, projectID, { issues: [{}] });
const project = useCoState(Project, projectID, {
resolve: { issues: { $each: true } },
});
if (!project) return;

View File

@@ -49,7 +49,7 @@ function highlightPlugin() {
token.content.includes("// old"),
);
const isBinnedLine = line.some((token) =>
token.content.includes("// *bin*"),
token.content.includes("// [!code --]"),
);
const isHighlighted = line.some((token) =>
token.content.includes("// *highlight*"),
@@ -70,7 +70,7 @@ function highlightPlugin() {
line
.map((token) => {
let color = isHighlighted ? "currentColor" : token.color;
return `<span style="color: ${color};${isSubduedLine ? "opacity: 0.4;" : ""}">${escape(token.content.replace("// old", "").replace("// *bin*", "").replace("// *highlight*", ""))}</span>`;
return `<span style="color: ${color};${isSubduedLine ? "opacity: 0.4;" : ""}">${escape(token.content.replace("// old", "").replace("// [!code --]", "").replace("// *highlight*", ""))}</span>`;
})
.join("") +
"</span>"

View File

@@ -331,7 +331,7 @@ This works because CoValues
<CodeGroup>
```ts
const unsub = issue.subscribe([], (updatedIssue) => console.log(updatedIssue));
const unsub = issue.subscribe({ resolve: true }, (updatedIssue) => console.log(updatedIssue));
```
</CodeGroup>
@@ -339,7 +339,7 @@ This works because CoValues
<CodeGroup>
```ts
const unsub = Issue.subscribe(issueID, me, [], (updatedIssue) => {
const unsub = Issue.subscribe(issueID, me, { resolve: true }, (updatedIssue) => {
console.log(updatedIssue);
});
```
@@ -358,7 +358,7 @@ This works because CoValues
function useCoState<V extends CoValue>(Schema: CoValueClass<V>, id?: ID<V>): V | undefined {
const [value, setValue] = useState<V>();
useEffect(() => Schema.subscribe(id, [], setValue), [id]);
useEffect(() => Schema.subscribe(id, { resolve: true }, setValue), [id]);
return value;
}
@@ -454,7 +454,7 @@ function App() { // old
const issue = useCoState(Issue, issueID); // old
// old
const createIssue = () => { // old
const group = Group.create({ owner: me });
const group = Group.create();
group.addMember("everyone", "writer");
// old
const newIssue = Issue.create( // old
@@ -543,7 +543,7 @@ function App() { // old
(window.location.search?.replace("?project=", "") || undefined) as ID<Project> | undefined
);
// old
const issue = useCoState(Issue, issueID); // *bin*
const issue = useCoState(Issue, issueID); // [!code --]
// old
const createProject = () => {
const group = Group.create();
@@ -605,6 +605,8 @@ export function ProjectComponent({ projectID }: { projectID: ID<Project> }) {
<button onClick={createAndAddIssue}>Create Issue</button>
</div>
</div>
) : project === null ? (
<div>Project not found or access denied</div>
) : (
<div>Loading project...</div>
);
@@ -620,7 +622,7 @@ Two things to note here:
- We only need to use `useCoState` on the Project, and the nested `ListOfIssues` and each `Issue` will be **automatically loaded and subscribed to when we access them.**
- However, because either the `Project`, `ListOfIssues`, or each `Issue` might not be loaded yet, we have to check for them being defined.
### Precise loading depths
### Precise resolve queries
The load-and-subscribe-on-access is a convenient way to have your rendering drive data loading (including in nested components!) and lets you quickly chuck UIs together without worrying too much about the shape of all data you'll need.
@@ -635,7 +637,7 @@ import { IssueComponent } from "./Issue.tsx"; // old
import { useCoState } from "jazz-react"; // old
// old
export function ProjectComponent({ projectID }: { projectID: ID<Project> }) {// old
const project = useCoState(Project, projectID, { issues: [{}] });
const project = useCoState(Project, projectID, { resolve: { issues: { $each: true } } });
const createAndAddIssue = () => {// old
project?.issues.push(Issue.create({
@@ -663,7 +665,7 @@ export function ProjectComponent({ projectID }: { projectID: ID<Project> }) {//
```
</CodeGroup>
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).
The resolve query `{ resolve: { issues: { $each: true } } }` means "in `Project`, load `issues` and load each item in `issues` deeply". (Since an `Issue` doesn't have any further references, "deeply" 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.
- 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.
@@ -710,7 +712,7 @@ function App() { // old
// old
const createProject = () => { // old
const group = Group.create(); // old
group.addMember("everyone", "writer"); // *bin*
group.addMember("everyone", "writer"); // [!code --]
// old
const newProject = Project.create( // old
{ // old
@@ -747,7 +749,7 @@ import { createInviteLink } from "jazz-react";
// old
export function ProjectComponent({ projectID }: { projectID: ID<Project> }) {// old
const project = useCoState(Project, projectID, { issues: [{}] }); // old
const project = useCoState(Project, projectID, { resolve: { issues: { $each: true } } }); // old
const { me } = useAccount();

View File

@@ -112,7 +112,7 @@ declare module "jazz-react" {// old
## Resolving CoValues starting at `profile` or `root`
<ContentByFramework framework="react">
To use per-user data in your app, you typically use `useAccount` somewhere in a high-level component, specifying which references to resolve using a depth-spec (see [Subscribing & deep loading](/docs/using-covalues/subscription-and-loading)).
To use per-user data in your app, you typically use `useAccount` somewhere in a high-level component, specifying which references to resolve using a resolve query (see [Subscribing & deep loading](/docs/using-covalues/subscription-and-loading)).
<CodeGroup>
{/* prettier-ignore */}
@@ -163,12 +163,12 @@ export class MyAppAccount extends Account {
profile = co.ref(MyAppProfile);
async migrate(this: MyAppAccount, creationProps?: { name: string }) {
// we specifically need to check for undefined,
// we specifically need to check for undefined,
// because the root might simply be not loaded (`null`) yet
if (this.root === undefined) {
this.root = MyAppRoot.create({
// Using a group to set the owner is always a good idea.
// This way if in the future we want to share
// This way if in the future we want to share
// this coValue we can do so easily.
myChats: ListOfChats.create([], Group.create()),
myContacts: ListOfAccounts.create([], Group.create())
@@ -218,8 +218,8 @@ export class MyAppAccount extends Account {
root: {},
});
// we specifically need to check for undefined,
// because myBookmarks might simply be not loaded (`null`) yet
// we specifically need to check for undefined,
// because myBookmarks might simply be not loaded (`null`) yet
if (root.myBookmarks === undefined) {
root.myBookmarks = ListOfBookmarks.create([], Group.create());
}
@@ -228,9 +228,9 @@ export class MyAppAccount extends Account {
```
</CodeGroup>
{/*
TODO: Add best practice: only ever add fields
{/*
TODO: Add best practice: only ever add fields
Note: explain and reassure that there will be more guardrails in the future
Note: explain and reassure that there will be more guardrails in the future
https://github.com/garden-co/jazz/issues/1160
*/}

View File

@@ -29,9 +29,9 @@ Here is what's changed in this release:
{/* prettier-ignore */}
```tsx
<JazzProvider
auth={authMethod} // removed // *bin*
peer="wss://cloud.jazz.tools/?key=you@example.com" // moved into sync // *bin*
sync={{ peer: "wss://cloud.jazz.tools/?key=you@example.com" }} // *add*
auth={authMethod} // removed // [!code --]
peer="wss://cloud.jazz.tools/?key=you@example.com" // moved into sync // [!code --]
sync={{ peer: "wss://cloud.jazz.tools/?key=you@example.com" }} // [!code ++]
>
<App />
</JazzProvider>

View File

@@ -0,0 +1,299 @@
import { CodeGroup } from '@/components/forMdx'
export const metadata = { title: "Jazz 0.12.0 - Deeply resolved data" };
# Jazz 0.12.0 - Deeply resolved data
Jazz 0.12.0 makes it easier and safer to load nested data. You can now specify exactly which nested data you want to load, and Jazz will check permissions and handle missing data gracefully. This helps catch errors earlier during development and makes your code more reliable.
## What's new?
- New resolve API for a more type-safe deep loading
- A single, consistent load option for all loading methods
- Improved permission checks on deep loading
- Easier type safety with the `Resolved` type helper
## Breaking changes
### New Resolve API
We're introducing a new resolve API for deep loading, more friendly to TypeScript, IDE autocompletion and LLMs.
**Major changes:**
1. Functions and hooks for loading now take the resolve query as an explicit nested `resolve` prop
2. Shallowly loading a collection is now done with `true` instead of `[]` or `{}`
<CodeGroup>
```tsx twoslash
// @noErrors: 2451
import { CoMap, CoList, co, Account } from "jazz-tools";
import { useAccount } from "jazz-react";
class AccountRoot extends CoMap { friends = co.ref(ListOfAccounts); }
class ListOfAccounts extends CoList.Of(co.ref(Account)) {}
class MyAppAccount extends Account { root = co.ref(AccountRoot);}
declare module "jazz-react" { interface Register { Account: MyAppAccount; } }
// ---cut-before---
// Before
// @ts-expect-error
const { me } = useAccount({ root: { friends: [] } }); // [!code --]
// After
const { me } = useAccount({ // [!code ++]
resolve: { root: { friends: true } } // [!code ++]
}); // [!code ++]
```
</CodeGroup>
3. For collections, resolving items deeply is now done with a special `$each` key.
For a `CoList`:
<CodeGroup>
```tsx twoslash
// @noErrors: 2451
import { CoList, co, ID, CoMap } from "jazz-tools";
import { useCoState } from "jazz-react";
// ---cut-before---
class Task extends CoMap { }
class ListOfTasks extends CoList.Of(co.ref(Task)) {}
const id = "co_123" as ID<Task>;
// Before
// @ts-expect-error
const tasks = useCoState(ListOfTasks, id, [{}]); // [!code --]
// After
const tasks = useCoState(ListOfTasks, id, { resolve: { $each: true } }); // [!code ++]
```
</CodeGroup>
For a `CoMap.Record`:
<CodeGroup>
```tsx twoslash
// @noErrors: 2451
import { CoMap, co, Account, ID } from "jazz-tools";
import { useCoState } from "jazz-react";
class MyAppAccount extends Account {}
const id = "co_123" as ID<UsersByUsername>;
// ---cut-before---
class UsersByUsername extends CoMap.Record(co.ref(MyAppAccount)) {}
// Before
// @ts-expect-error
const usersByUsername = useCoState(UsersByUsername, id, [{}]); // [!code --]
// After
const usersByUsername = useCoState(UsersByUsername, id, { // [!code ++]
resolve: { $each: true } // [!code ++]
}); // [!code ++]
```
</CodeGroup>
Nested loading &mdash; note how it's now less terse, but more readable:
<CodeGroup>
```tsx twoslash
// @noErrors: 2451
import { CoList, CoMap, co, Account, ID } from "jazz-tools";
import { useCoState } from "jazz-react";
const id = "co_123" as ID<ListOfTasks>;
// ---cut-before---
class Org extends CoMap {
name = co.string;
}
class Assignee extends CoMap {
name = co.string;
org = co.ref(Org);
}
class ListOfAssignees extends CoList.Of(co.ref(Assignee)) {}
class Task extends CoMap {
content = co.string;
assignees = co.ref(ListOfAssignees);
}
class ListOfTasks extends CoList.Of(co.ref(Task)) {}
// Before
// @ts-expect-error
const tasksWithAssigneesAndTheirOrgs = useCoState(ListOfTasks, id, [{ // [!code --]
assignees: [{ org: {}}]} // [!code --]
]); // [!code --]
// After
const tasksWithAssigneesAndTheirOrgs = useCoState(ListOfTasks, id, { // [!code ++]
resolve: { // [!code ++]
$each: { // [!code ++]
assignees: { // [!code ++]
$each: { org: true } // [!code ++]
} // [!code ++]
} // [!code ++]
} // [!code ++]
}); // [!code ++]
```
</CodeGroup>
It's also a lot more auto-complete friendly:
<CodeGroup>
```tsx twoslash
// @noErrors: 2451 2353 2581
import { CoList, CoMap, co, ID } from "jazz-tools";
import { useCoState } from "jazz-react";
class Org extends CoMap { name = co.string; }
class Assignee extends CoMap { org = co.ref(Org); }
class ListOfAssignees extends CoList.Of(co.ref(Assignee)) {}
class Task extends CoMap { assignees = co.ref(ListOfAssignees); }
class ListOfTasks extends CoList.Of(co.ref(Task)) {}
const id = "co_123" as ID<ListOfTasks>;
// ---cut-before---
const tasksWithAssigneesAndTheirOrgs = useCoState(ListOfTasks, id, {
resolve: {
$each: {
assignees: {
$
// ^|
}
}
}
});
```
</CodeGroup>
### A single, consistent load option
The new API works across all loading methods, and separating out the resolve query means
other options with default values are easier to manage, for example: loading a value as a specific account instead of using the implicit current account:
<CodeGroup>
```ts twoslash
// @noErrors: 2451
import { co, Account, CoMap, CoList, ID } from "jazz-tools";
class Track extends CoMap {}
class ListOfTracks extends CoList.Of(co.ref(Track)) {}
class Playlist extends CoMap { tracks = co.ref(ListOfTracks); }
const id = "co_123" as ID<Playlist>;
const otherAccount = {} as Account;
// ---cut-before---
// Before
// @ts-expect-error
Playlist.load(id, otherAccount, { // [!code --]
tracks: [], // [!code --]
}); // [!code --]
// After
Playlist.load(id, { // [!code ++]
loadAs: otherAccount, // [!code ++]
resolve: { tracks: true } // [!code ++]
}); // [!code ++]
```
</CodeGroup>
### Improved permission checks on deep loading
Now `useCoState` will return `null` when the current user lacks permissions to load requested data.
Previously, `useCoState` would return `undefined` if the current user lacked permissions, making it hard to tell if the value is loading or if it's missing.
Now `undefined` means that the value is definitely loading, and `null` means that the value is temporarily missing.
We also have implemented a more granular permission checking, where if an *optional* CoValue cannot be accessed, `useCoState` will return the data stripped of that CoValue.
**Note:** The state handling around loading and error states will become more detailed and easy-to-handle in future releases, so this is just a small step towards consistency.
<CodeGroup>
{/* prettier-ignore */}
```tsx twoslash
// @noErrors: 2451
import React from "react";
import { CoList, CoMap, co, ID } from "jazz-tools";
import { useCoState } from "jazz-react";
class Track extends CoMap {}
function TrackComponent({ track }: { track: Track }) {return ""}
// ---cut-before---
class ListOfTracks extends CoList.Of(co.optional.ref(Track)) {}
function TrackListComponent({ id }: { id: ID<ListOfTracks> }) {
// Before (ambiguous states)
// @ts-expect-error
const tracks = useCoState(ListOfTracks, id, [{}]); // [!code --]
if (tracks === undefined) return <div>Loading or access denied</div>; // [!code --]
if (tracks === null) return <div>Not found</div>; // [!code --]
// After
const tracks = useCoState(ListOfTracks, id, { resolve: { $each: true } }); // [!code ++]
if (tracks === undefined) return <div>Loading...</div>; // [!code ++]
if (tracks === null) return <div>Not found or access denied</div>; // [!code ++]
// This will only show tracks that we have access to and that are loaded.
return tracks.map(track => track && <TrackComponent track={track} />);
}
```
</CodeGroup>
The same change is applied to the load function, so now it returns `null` instead of `undefined` when the value is missing.
<CodeGroup>
```tsx twoslash
// @noErrors: 2451
import { CoMap, co, ID } from "jazz-tools";
import { useAccount } from "jazz-react";
class MyCoMap extends CoMap {}
const id = "co_123" as ID<MyCoMap>;
// ---cut-before---
// Before
// @ts-expect-error
const map = await MyCoMap.load(id);
if (map === undefined) {
throw new Error("Map not found");
}
// After
const map = await MyCoMap.load(id);
if (map === null) {
throw new Error("Map not found or access denied");
}
```
</CodeGroup>
## New Features
### The `Resolved` type helper
The new `Resolved` type can be used to define what kind of deeply loaded data you expect in your parameters, using the same resolve query syntax as the new loading APIs:
<CodeGroup>
```tsx twoslash
// @noErrors: 2451
import React from "react";
import { Resolved, CoMap, CoList, co } from "jazz-tools";
class Track extends CoMap {}
class ListOfTracks extends CoList.Of(co.ref(Track)) {}
class Playlist extends CoMap { tracks = co.ref(ListOfTracks); }
function TrackComponent({ track }: { track: Track }) {return ""}
// ---cut-before---
type PlaylistResolved = Resolved<Playlist, {
tracks: { $each: true }
}>;
function TrackListComponent({ playlist }: { playlist: PlaylistResolved }) {
// Safe access to resolved tracks
return playlist.tracks.map(track => <TrackComponent track={track} />);
}
```
</CodeGroup>

View File

@@ -25,9 +25,9 @@ So we decided to remove `createJazzRNApp` step and to provide the types through
import { JazzProvider, useDemoAuth, DemoAuthBasicUI } from "jazz-react-native";
import { MyAppAccount } from "./schema";
// Remove these lines // *bin*
const Jazz = createJazzRNApp({ AccountSchema: MyAppAccount }); // *bin*
export const { useAccount, useCoState } = Jazz; // *bin*
// Remove these lines // [!code --]
const Jazz = createJazzRNApp({ AccountSchema: MyAppAccount }); // [!code --]
export const { useAccount, useCoState } = Jazz; // [!code --]
export function JazzAndAuth({ children }: { children: React.ReactNode }) { // old
const [auth, state] = useDemoAuth(); // old
@@ -66,8 +66,8 @@ This change improves IDE intellisense support and simplifies imports:
{/* prettier-ignore */}
```tsx
// Replace local imports with "jazz-react-native" imports
import { useAccount } from "./main"; // *bin*
import { useAccount } from "jazz-react-native"; // *add*
import { useAccount } from "./main"; // [!code --]
import { useAccount } from "jazz-react-native"; // [!code ++]
export function Hello() {
const { me } = useAccount();

View File

@@ -24,9 +24,9 @@ So we decided to remove `createJazzReactApp` step and to provide the types throu
import { JazzProvider, usePasskeyAuth, PasskeyAuthBasicUI } from "jazz-react";
import { MyAppAccount } from "./schema";
// Remove these lines // *bin*
const Jazz = createJazzReactApp({ AccountSchema: MyAppAccount }); // *bin*
export const { useAccount, useCoState } = Jazz; // *bin*
// Remove these lines // [!code --]
const Jazz = createJazzReactApp({ AccountSchema: MyAppAccount }); // [!code --]
export const { useAccount, useCoState } = Jazz; // [!code --]
export function JazzAndAuth({ children }: { children: React.ReactNode }) { // old
const [passkeyAuth, passKeyState] = usePasskeyAuth({ appName }); // old
@@ -37,7 +37,7 @@ So we decided to remove `createJazzReactApp` step and to provide the types throu
<JazzProvider
auth={passkeyAuth} // old
peer="wss://cloud.jazz.tools/?key=you@example.com" // old
AccountSchema={MyAppAccount} {/* The custom Account schema is passed here */} // *add*
AccountSchema={MyAppAccount} {/* The custom Account schema is passed here */} // [!code ++]
>
{children} // old
</JazzProvider>
@@ -47,11 +47,11 @@ So we decided to remove `createJazzReactApp` step and to provide the types throu
}
// Register the Account schema so `useAccount` returns our custom `MyAppAccount`
declare module "jazz-react" { // *add*
interface Register { // *add*
Account: MyAppAccount; // *add*
} // *add*
} // *add*
declare module "jazz-react" { // [!code ++]
interface Register { // [!code ++]
Account: MyAppAccount; // [!code ++]
} // [!code ++]
} // [!code ++]
```
</CodeGroup>
@@ -65,8 +65,8 @@ This change improves IDE intellisense support and simplifies imports:
{/* prettier-ignore */}
```tsx
// Replace local imports with "jazz-react" imports
import { useAccount } from "./main"; // *bin*
import { useAccount } from "jazz-react"; // *add*
import { useAccount } from "./main"; // [!code --]
import { useAccount } from "jazz-react"; // [!code ++]
export function Hello() {
const { me } = useAccount();

View File

@@ -32,7 +32,7 @@ So we decided to remove `createJazzApp` step and to provide the types through na
</script>
<script lang="ts">
import { Provider } from '$lib/jazz'; // *bin*
import { Provider } from '$lib/jazz'; // [!code --]
import { JazzProvider } from 'jazz-svelte';
// Example configuration for authentication and peer connection
@@ -62,8 +62,8 @@ So we decided to remove `createJazzApp` step and to provide the types through na
```svelte
<script lang="ts">
import { useAccount } from '$lib/jazz'; // *bin*
import { useAccount } from 'jazz-svelte'; // *add*
import { useAccount } from '$lib/jazz'; // [!code --]
import { useAccount } from 'jazz-svelte'; // [!code ++]
const { me } = useAccount();
</script>

View File

@@ -28,10 +28,10 @@ import App from "./App.vue"; // old
import router from "./router"; // old
import { ToDoAccount } from "./schema"; // old
// Remove these lines // *bin*
const Jazz = createJazzVueApp<ToDoAccount>({ AccountSchema: ToDoAccount }); // *bin*
export const { useAccount, useCoState } = Jazz; // *bin*
const { JazzProvider } = Jazz; // *bin*
// Remove these lines // [!code --]
const Jazz = createJazzVueApp<ToDoAccount>({ AccountSchema: ToDoAccount }); // [!code --]
export const { useAccount, useCoState } = Jazz; // [!code --]
const { JazzProvider } = Jazz; // [!code --]
const RootComponent = defineComponent({ // old
name: "RootComponent", // old
@@ -86,8 +86,8 @@ This change improves IDE intellisense support and simplifies imports:
<script setup lang="ts">
// Replace local imports with "jazz-vue" imports
import { useAccount } from "./main"; // *bin*
import { useAccount } from "jazz-vue"; // *add*
import { useAccount } from "./main"; // [!code --]
import { useAccount } from "jazz-vue"; // [!code ++]
const { me, logOut } = useAccount();
</script>

View File

@@ -1,8 +1,8 @@
import { CodeGroup } from "@/components/forMdx";
export const metadata = { title: "Metadata & time-travel" };
export const metadata = { title: "History & time-travel" };
# Metadata & time-travel
# History & 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.
@@ -115,11 +115,11 @@ Activity feeds are a great way to see recent changes to a CoValue, helping users
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({
@@ -128,10 +128,10 @@ function getRecentActivity(project: Project) {
by: edit.by,
at: edit.madeAt
});
}
}
}
}
return activity.sort((a, b) => b.at.getTime() - a.at.getTime());
}
@@ -148,7 +148,7 @@ recentActivity.forEach(activity => {
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>
<CodeGroup>
```ts
class Task extends CoMap {
title = co.string;
@@ -206,7 +206,7 @@ class Project extends CoMap {
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({
@@ -233,7 +233,7 @@ The time travel capabilities of CoValues enable several practical use cases that
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);
@@ -245,7 +245,7 @@ function getTaskStatusHistory(task: Task, days: number = 7) {
priority: state.priority
});
}
return statusHistory;
}

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

@@ -4,14 +4,29 @@ 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.
Jazz's Collaborative Values (such as [CoMaps](/docs/using-covalues/comaps) or [CoLists](/docs/using-covalues/colists)) work like reactive state. By subscribing to them, you can react to both local and remote updates. This is the main way to consume data in your application.
## Understanding Subscriptions
Subscriptions also take care of loading CoValues that are not yet loaded locally and can do so *deeply* &mdash; by resolving nested CoValues. To make use of this, we'll show you how to specify the depth of data you need with resolve queries.
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.
With each update you can also handle loading states and inaccessible CoValues.
## Manual subscriptions
You can subscribe to a CoValue from anywhere in your code (if you have its ID) by using `CoValue.subscribe()`.
<ContentByFramework framework="vanilla">
If you're using React in your project, check out our [React hooks](/docs/react/using-covalues/subscription-and-loading#subscription-hooks) which provide a more streamlined experience with automatic subscription management.
</ContentByFramework>
<ContentByFramework framework={["react", "react-native"]}>
**Note:** Unless you're using vanilla JavaScript, this is only used outside of React components - for example in server-side code or in tests. See the section below for convenient subscription *hooks* that you typically use in React.
</ContentByFramework>
<CodeGroup>
```ts
```ts twoslash
import { ID, CoMap, co } from "jazz-tools";
const taskId = "co_123" as ID<Task>;
// ---cut-before---
class Task extends CoMap {
title = co.string;
description = co.string;
@@ -22,144 +37,82 @@ class Task extends CoMap {
// ...
// Subscribe to a Task by ID
const unsubscribe = Task.subscribe(taskId, { /* loading depth */ }, (updatedTask) => {
const unsubscribe = Task.subscribe(taskId, (updatedTask) => {
console.log("Task updated:", updatedTask.title);
console.log("New status:", updatedTask.status);
});
// Later, when you're done:
// Clean up when you're done
unsubscribe();
```
</CodeGroup>
If you already have a CoValue instance, you can subscribe to it by calling its `subscribe` method.
<CodeGroup>
```ts twoslash
import { ID, CoMap, co } from "jazz-tools";
class Task extends CoMap {
title = co.string;
description = co.string;
status = co.literal("todo", "in-progress", "completed");
assignedTo = co.optional.string;
}
const otherProps = {} as any;
// ---cut-before---
const task = Task.create({
title: "Cut the grass",
...otherProps
});
const unsubscribe = task.subscribe((updatedTask) => {
console.log("Task updated:", updatedTask.title);
});
// Clean up when you're done
unsubscribe();
```
</CodeGroup>
### Static vs. Instance Subscriptions
<ContentByFramework framework={["react", "react-native"]}>
## Subscription hooks
There are two main ways to subscribe to CoValues:
### `useCoState`
1. **Static Subscription** - When you have an ID but don't have the CoValue loaded yet:
Jazz provides a `useCoState` hook that provides a convenient way to subscribe to CoValues and handle loading states:
<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>
```tsx twoslash
import React from "react";
import { ID, CoMap, co, CoList } from "jazz-tools";
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);
});
class Task extends CoMap {
title = co.string;
status = co.literal("todo", "in-progress", "completed");
}
```
</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 ListOfTasks extends CoList.Of(co.ref(Task)) {}
class Task extends CoMap {
title = co.string;
subtasks = co.ref(ListOfSubtasks);
assignee = co.optional.ref(TeamMember);
}
// ---cut-before---
import { useCoState } from "jazz-react";
// 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: [{}]
resolve: {
tasks: { $each: true },
},
});
// Handle loading state
if (!project) {
return <div>Loading garden project...</div>;
return project === null
? "Project not found or not accessible"
: "Loading project ...";
}
return (
@@ -173,7 +126,7 @@ function GardenPlanner({ projectId }: { projectId: ID<Project> }) {
function TaskList({ tasks }: { tasks: Task[] }) {
return (
<ul>
{tasks.map(task => (
{tasks.map((task) => (
<li key={task.id}>
<span>{task.title}</span>
<span>{task.status}</span>
@@ -186,92 +139,512 @@ function TaskList({ tasks }: { tasks: Task[] }) {
</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
### `useAccount`
In Vue applications, you can use the `useCoState` composable to subscribe to CoValues:
`useAccount` is used to access the current user's account.
You can use this at the top-level of your app to subscribe to the current user's [account profile and root](../schemas/accounts-and-migrations#covalues-as-a-graph-of-data-rooted-in-accounts).
Like `useCoState`, you can specify a resolve query to also subscribe to CoValues referenced in the account profile or root.
<CodeGroup>
```vue
<script setup>
import { useCoState } from 'jazz-vue';
```tsx twoslash
import React from "react";
import { ID, CoMap, co, CoList, Account } from "jazz-tools";
class Task extends CoMap {
title = co.string;
}
class ListOfTasks extends CoList.Of(co.ref(Task)) {}
class Project extends CoMap {
name = co.string;
tasks = co.ref(ListOfTasks);
}
class ListOfProjects extends CoList.Of(co.ref(Project)) {}
const props = defineProps({
projectId: String
});
class AccountRoot extends CoMap {
myProjects = co.ref(ListOfProjects);
}
class MyAppAccount extends Account {
root = co.ref(AccountRoot);
}
declare module "jazz-react" { interface Register { Account: MyAppAccount; } }
// ---cut-before---
import { useAccount } from "jazz-react";
// Subscribe to a project and its tasks
const project = useCoState(Project, props.projectId, {
tasks: [{}]
});
</script>
function ProjectList() {
const { me } = useAccount({
resolve: {
profile: true,
root: {
myProjects: {
$each: {
tasks: true
}
}
},
},
});
<template>
<div v-if="project">
<h1>{{ project.name }}</h1>
if (!me) {
return <div>Loading...</div>;
}
return <div>
<h1>{me.profile.name}'s projects</h1>
<ul>
<li v-for="task in project.tasks" :key="task.id">
{{ task.title }} - {{ task.status }}
</li>
{me.root.myProjects.map(project => (
<li key={project.id}>
{project.name} ({project.tasks.length} tasks)
</li>
))}
</ul>
</div>
<div v-else>
Loading garden project...
</div>
</template>
}
```
</CodeGroup>
</ContentByFramework>
<ContentByFramework framework="svelte">
### Svelte Integration
## Loading States and Permission Checking
In Svelte applications, you can use the `useCoState` function to subscribe to CoValues:
When subscribing to or loading a CoValue, you need to handle three possible states:
- `undefined`: The initial loading state, indicating the value is being fetched
- `null`: The CoValue was not found or is not accessible (e.g., due to permissions)
- `Value`: The successfully loaded CoValue instance
This allows you to handle loading, error, and success states in your application:
<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>
```ts twoslash
import { ID, CoMap, co } from "jazz-tools";
class Task extends CoMap {
title = co.string;
}
{#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}
const taskId = "co_123" as ID<Task>;
// ---cut-before---
Task.subscribe(taskId, (task) => {
if (task === undefined) {
console.log("Task is loading...");
} else if (task === null) {
console.log("Task not found or not accessible");
} else {
console.log("Task loaded:", task.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. This is especially important when working with [CoMaps](/docs/using-covalues/comaps) that contain references to other CoValues or with [CoLists](/docs/using-covalues/colists) that contain multiple items. Jazz provides a flexible mechanism for specifying exactly how much of the object graph to load.
### Resolve queries
Resolve queries let you declare exactly which references to load and how deep to go using the `resolve` property:
<CodeGroup>
```ts twoslash
import { ID, CoMap, co, CoList } from "jazz-tools";
const projectId = "co_123" as ID<Project>;
// ---cut-before---
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(ListOfTasks);
assignee = co.optional.ref(TeamMember);
}
class TeamMember extends CoMap {
name = co.string;
}
class ListOfTasks extends CoList.Of(co.ref(Task)) {}
// Load just the project, not its references
const project = await Project.load(projectId);
if (!project) { throw new Error("Project not found or not accessible"); }
// string - primitive fields are always loaded
project.name;
// undefined | null | ListOfTasks - non-requested references might not be loaded, or inaccessible
project.tasks;
// Load the project and shallowly load its list of tasks
const projectWithTasksShallow = await Project.load(projectId, {
resolve: {
tasks: true
}
});
if (!projectWithTasksShallow) { throw new Error("Project or required references not found or not accessible"); }
// ListOfTasks - shallowly loaded
projectWithTasksShallow.tasks;
// number - length of the list
projectWithTasksShallow.tasks.length;
// undefined | null | Task - items might not be loaded, or inaccessible
projectWithTasksShallow.tasks[0];
// Load the project and its tasks
const projectWithTasks = await Project.load(projectId, {
resolve: {
tasks: {
$each: true
}
}
});
if (!projectWithTasks) { throw new Error("Project or required references not found or not accessible"); }
// ListOfTasks - fully loaded
projectWithTasks.tasks;
// Task - fully loaded
projectWithTasks.tasks[0];
// string - primitive fields are always loaded
projectWithTasks.tasks[0].title;
// undefined | null | ListOfTasks - subtasks might not be loaded, or inaccessible
projectWithTasks.tasks[0].subtasks;
// Load the project, its tasks, and their subtasks
const projectDeep = await Project.load(projectId, {
resolve: {
tasks: {
$each: {
subtasks: {
$each: true
},
assignee: true
}
}
}
});
if (!projectDeep) { throw new Error("Project or required references not found or not accessible"); }
// string - primitive fields are always loaded
projectDeep.tasks[0].subtasks[0].title;
// undefined | null | TeamMember - since assignee is optional:
// TeamMember - set and definitely loaded
// null - set but unavailable/inaccessible
// undefined - not set, or loading (in case of subscription)
projectDeep.tasks[0].assignee;
```
</CodeGroup>
The resolve query defines which parts of the graph you want to load, making it intuitive to express complex loading patterns.
### Loading states and permissions
When loading data with references, the load operation will fail if one of the references is unavailable or if the user doesn't have read access to it. Let's explore what happens in various scenarios:
#### Resolved References
When a user tries to load a reference they don't have access to:
<CodeGroup>
```typescript twoslash
import { ID, CoMap, co, CoList } from "jazz-tools";
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(ListOfTasks);
assignee = co.optional.ref(TeamMember);
}
class TeamMember extends CoMap {
name = co.string;
}
class ListOfTasks extends CoList.Of(co.ref(Task)) {}
const taskId = "co_123" as ID<Task>;
// ---cut-before---
// If assignee is not accessible to the user:
const task = await Task.load(taskId, {
resolve: { assignee: true }
});
task // => null
```
</CodeGroup>
The load operation will fail and return `null` if any requested reference is inaccessible. This maintains data consistency by ensuring all requested references are available before returning the object.
The behavior is the same for optional and required references.
#### List References
When a list contains references to items the user can't access:
<CodeGroup>
```typescript twoslash
import { ID, CoMap, co, CoList } from "jazz-tools";
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(ListOfTasks);
assignee = co.optional.ref(TeamMember);
}
class TeamMember extends CoMap {
name = co.string;
}
class ListOfTasks extends CoList.Of(co.ref(Task)) {}
const projectId = "co_123" as ID<Project>;
// ---cut-before---
// If any item in the list is not accessible:
const project = await Project.load(projectId, {
resolve: { tasks: { $each: true } }
});
project // => null
```
</CodeGroup>
If any item in a list is inaccessible to the user, the entire load operation will fail and return `null`. This is because lists expect all their items to be accessible - a partially loaded list could lead to data inconsistencies.
#### Reading a non-resolved inaccessible reference
When trying to load an object with an inaccessible reference without directly resolving it:
<CodeGroup>
```typescript twoslash
import { ID, CoMap, co, CoList } from "jazz-tools";
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(ListOfTasks);
assignee = co.optional.ref(TeamMember);
}
class TeamMember extends CoMap {
name = co.string;
}
class ListOfTasks extends CoList.Of(co.ref(Task)) {}
const projectId = "co_123" as ID<Project>;
// ---cut-before---
const project = await Project.load(projectId, {
resolve: true
});
project // => Project
// The user doesn't have access to the owner
project?.owner // => always null
```
</CodeGroup>
The load operation will succeed and return the object, but the inaccessible reference will always be `null`.
## Type Safety with Resolved Type
Jazz provides the `Resolved` type to help you define and enforce the structure of deeply loaded data in your application. This makes it easier to ensure that components receive the data they expect with proper TypeScript validation.
The `Resolved` type is especially useful when passing data between components, as it guarantees that all necessary nested data has been loaded:
<ContentByFramework framework="react">
<CodeGroup>
```tsx twoslash
import React from "react";
import { ID, CoMap, co, CoList, Resolved } from "jazz-tools";
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(ListOfTasks);
assignee = co.optional.ref(TeamMember);
}
class TeamMember extends CoMap {
name = co.string;
}
class ListOfTasks extends CoList.Of(co.ref(Task)) {}
// ---cut-before---
// Define a type that includes resolved nested data
type ProjectWithTasks = Resolved<Project, {
tasks: { $each: true }
}>;
// Component that expects a fully resolved project
function TaskList({ project }: { project: ProjectWithTasks }) {
// TypeScript knows tasks are loaded, so this is type-safe
return (
<ul>
{project.tasks.map(task => (
<li key={task.id}>{task.title}</li>
))}
</ul>
);
}
// For more complex resolutions
type FullyLoadedProject = Resolved<Project, {
tasks: {
$each: {
subtasks: true,
assignee: true
}
},
owner: true
}>;
// Function that requires deeply resolved data
function processProject(project: FullyLoadedProject) {
// Safe access to all resolved properties
console.log(`Project ${project.name} owned by ${project.owner.name}`);
project.tasks.forEach(task => {
console.log(`Task: ${task.title}, Assigned to: ${task.assignee?.name}`);
console.log(`Subtasks: ${task.subtasks.length}`);
});
}
```
</CodeGroup>
</ContentByFramework>
<ContentByFramework framework="vanilla">
<CodeGroup>
```ts twoslash
import { ID, CoMap, co, CoList, Resolved } from "jazz-tools";
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(ListOfTasks);
assignee = co.optional.ref(TeamMember);
}
class TeamMember extends CoMap {
name = co.string;
}
class ListOfTasks extends CoList.Of(co.ref(Task)) {}
// ---cut-before---
// Define a type that includes resolved nested data
type ProjectWithTasks = Resolved<Project, {
tasks: { $each: true }
}>;
// Function that expects resolved data
async function taskList({project}: {project: ProjectWithTasks}) {
// TypeScript knows tasks are loaded, so this is type-safe
return project.tasks
.map(task => task.title)
.join(`\n - `);
}
// For more complex resolutions
type FullyLoadedProject = Resolved<Project, {
tasks: {
$each: {
title: true,
subtasks: true,
assignee: true
}
},
owner: true
}>;
// Function that requires deeply resolved data
function processProject(project: FullyLoadedProject) {
// Safe access to all resolved properties
console.log(`Project ${project.name} owned by ${project.owner.name}`);
project.tasks.forEach(task => {
console.log(`Task: ${task.title}, Assigned to: ${task.assignee?.name}`);
console.log(`Subtasks: ${task.subtasks.length}`);
});
}
```
</CodeGroup>
</ContentByFramework>
Using the `Resolved` type helps catch errors at compile time rather than runtime, ensuring that your components and functions receive data with the proper resolution depth. This is especially useful for larger applications where data is passed between many components.
## 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
```ts twoslash
import { ID, CoMap, co, CoList, Resolved } from "jazz-tools";
class Project extends CoMap {
name = co.string;
tasks = co.ref(ListOfTasks);
owner = co.ref(TeamMember);
}
class Task extends CoMap {
title = co.string;
status = co.literal("todo", "in-progress", "completed");
subtasks = co.ref(ListOfTasks);
assignee = co.optional.ref(TeamMember);
}
class TeamMember extends CoMap {
name = co.string;
}
class ListOfTasks extends CoList.Of(co.ref(Task)) {}
// ---cut-before---
async function completeAllTasks(projectId: ID<Project>) {
// Ensure the project and its tasks are loaded
const project = await Project.load(projectId, {});
// Ensure the project is loaded
const project = await Project.load(projectId, { resolve: true });
if (!project) return;
// Ensure tasks are loaded
const loadedProject = await project.ensureLoaded({
tasks: [{}]
resolve: {
tasks: {
$each: true
}
}
});
// Now we can safely access and modify tasks
loadedProject.tasks.forEach(task => {
task.status = "completed";
@@ -280,61 +653,12 @@ async function completeAllTasks(projectId: ID<Project>) {
```
</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.
1. **Be explicit about resolution depths**: Always specify exactly what you need
2. **Use framework integrations**: They handle subscription lifecycle automatically
3. **Clean up subscriptions**: Always store and call the unsubscribe function when you're done
4. **Handle all loading states**: Check for undefined (loading), null (not found), and success states
5. **Use the Resolved type**: Add compile-time type safety for components that require specific resolution patterns

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

@@ -3,11 +3,7 @@ import DocsLayout from "@/components/docs/DocsLayout";
import { DocNav } from "@/components/docs/nav";
import { Prose } from "gcmp-design-system/src/app/components/molecules/Prose";
export default function Layout({
children,
}: {
children: React.ReactNode;
}) {
export default function Layout({ children }: { children: React.ReactNode }) {
return (
<TocProvider>
<DocsLayout nav={<DocNav />}>

View File

@@ -12,6 +12,57 @@
}
}
@layer components {
@import "shiki.css";
pre.shiki {
height: 100%;
padding-top: 1em;
padding-bottom: 1em;
}
.twoslash-popup-code pre.shiki {
padding: 0.2em;
font-size: 0.8em;
}
.twoslash-hover {
position: initial !important;
}
pre.shiki .line {
display: inline-block;
width: 100%;
padding-left: 1em;
line-height: 1.5;
cursor: text;
}
.twoslash-popup-code pre.shiki .line {
display: inline;
padding-left: 0;
}
html.dark .shiki {
color: var(--shiki-dark) !important;
background-color: var(--shiki-dark-bg) !important;
/* Optional, if you also want font styles */
font-style: var(--shiki-dark-font-style) !important;
font-weight: var(--shiki-dark-font-weight) !important;
text-decoration: var(--shiki-dark-text-decoration) !important;
}
html.dark .shiki span {
color: var(--shiki-dark) !important;
/* Optional, if you also want font styles */
font-style: var(--shiki-dark-font-style) !important;
font-weight: var(--shiki-dark-font-weight) !important;
text-decoration: var(--shiki-dark-text-decoration) !important;
}
.shiki .line.diff.remove {
background-color: rgba(255, 0, 0, 0.1) !important;
}
.shiki .line.diff.add {
background-color: rgba(0, 255, 0, 0.1) !important;
}
@import "@shikijs/twoslash/style-rich.css";

View File

@@ -1,330 +0,0 @@
pre.shiki {
overflow: hidden;
height: 100%;
}
pre.shiki:hover .dim {
opacity: 1;
}
pre.shiki div.dim {
opacity: 0.5;
}
pre.shiki div.dim,
pre.shiki div.highlight {
margin: 0;
padding: 0;
}
pre.shiki div.highlight {
opacity: 1;
background-color: #f1f8ff;
}
pre.shiki div.line {
/* min-height: 1rem; */
counter-increment: lineNumber 1;
}
pre.shiki div.line::before {
content: counter(lineNumber);
display: inline-block;
vertical-align: middle;
width: 1.3rem;
padding-right: 0.3rem;
text-align: right;
transition: color 0.3s;
@apply text-stone-200/70 dark:text-stone-900 text-[0.65rem];
}
pre.shiki div.line:hover::before {
@apply text-stone-400 dark:text-stone-600;
}
/** Don't show the language identifiers */
pre.shiki .language-id {
display: none;
}
/** When you mouse over the pre, show the underlines */
pre.twoslash:hover data-lsp {
@apply border-dotted border-b border-stone-300 dark:border-stone-700;
}
/** The tooltip-like which provides the LSP response */
pre.twoslash data-lsp::before {
content: attr(lsp);
position: absolute;
transform: translate(0, 1.2rem);
max-width: 30rem;
@apply text-xs px-1.5 py-1 rounded border shadow-lg overflow-hidden whitespace-pre-wrap text-stone-700 bg-stone-50 dark:text-stone-200 dark:bg-stone-950;
text-align: left;
z-index: 100;
opacity: 0;
transition: opacity 0.3s;
pointer-events: none;
display: none;
}
pre.twoslash data-lsp:hover::before {
display: block;
opacity: 1;
pointer-events: visible;
width: auto;
height: auto;
}
.shiki-outer {
@apply shadow-sm rounded-xl;
}
.shiki-filename {
@apply px-3 py-2 bg-stone-100 text-stone-700 dark:bg-stone-900 dark:text-stone-300 rounded-t-xl text-xs;
}
pre .code-container {
@apply overflow-auto p-2 pl-0 bg-white dark:bg-stone-950 rounded-b-xl text-xs h-full leading-5;
}
/* The try button */
pre .code-container > a {
position: absolute;
right: 8px;
bottom: 8px;
border-radius: 4px;
border: 1px solid #719af4;
padding: 0 8px;
color: #719af4;
text-decoration: none;
opacity: 0;
transition-timing-function: ease;
transition: opacity 0.3s;
}
/* Respect no animations */
@media (prefers-reduced-motion: reduce) {
pre .code-container > a {
transition: none;
}
}
pre .code-container > a:hover {
color: white;
background-color: #719af4;
}
pre .code-container:hover a {
opacity: 1;
}
pre code {
white-space: pre;
}
pre code a {
text-decoration: none;
}
pre data-err {
/* Extracted from VS Code */
background: url("data:image/svg+xml,%3Csvg%20xmlns%3D'http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg'%20viewBox%3D'0%200%206%203'%20enable-background%3D'new%200%200%206%203'%20height%3D'3'%20width%3D'6'%3E%3Cg%20fill%3D'%23c94824'%3E%3Cpolygon%20points%3D'5.5%2C0%202.5%2C3%201.1%2C3%204.1%2C0'%2F%3E%3Cpolygon%20points%3D'4%2C0%206%2C2%206%2C0.6%205.4%2C0'%2F%3E%3Cpolygon%20points%3D'0%2C2%201%2C3%202.4%2C3%200%2C0.6'%2F%3E%3C%2Fg%3E%3C%2Fsvg%3E")
repeat-x bottom left;
padding-bottom: 3px;
}
pre .query {
margin-bottom: 10px;
color: #137998;
display: inline-block;
}
/* In order to have the 'popped out' style design and to not break the layout
/* we need to place a fake and un-selectable copy of the error which _isn't_ broken out
/* behind the actual error message.
/* This sections keeps both of those two in in sync */
pre .error,
pre .error-behind {
margin-left: -14px;
margin-top: 8px;
margin-bottom: 4px;
padding: 6px;
padding-left: 14px;
width: calc(100% - 20px);
white-space: pre-wrap;
display: block;
}
pre .error {
position: absolute;
background-color: #fee;
border-left: 2px solid #bf1818;
/* Give the space to the error code */
display: flex;
align-items: center;
color: black;
}
pre .error .code {
display: none;
}
pre .error-behind {
user-select: none;
visibility: transparent;
color: #fee;
}
/* Queries */
pre .arrow {
/* Transparent background */
background-color: #eee;
position: relative;
top: -7px;
margin-left: 0.1rem;
/* Edges */
border-left: 1px solid #eee;
border-top: 1px solid #eee;
transform: translateY(25%) rotate(45deg);
/* Size */
height: 8px;
width: 8px;
}
pre .popover {
margin-bottom: 10px;
background-color: #eee;
display: inline-block;
padding: 0 0.5rem 0.3rem;
margin-top: 10px;
border-radius: 3px;
}
/* Completion */
pre .inline-completions ul.dropdown {
display: inline-block;
position: absolute;
width: 240px;
background-color: gainsboro;
color: grey;
padding-top: 4px;
font-family: var(--code-font);
font-size: 0.8rem;
margin: 0;
padding: 0;
border-left: 4px solid #4b9edd;
}
pre .inline-completions ul.dropdown::before {
background-color: #4b9edd;
width: 2px;
position: absolute;
top: -1.2rem;
left: -3px;
content: " ";
}
pre .inline-completions ul.dropdown li {
overflow-x: hidden;
padding-left: 4px;
margin-bottom: 4px;
}
pre .inline-completions ul.dropdown li.deprecated {
text-decoration: line-through;
}
pre .inline-completions ul.dropdown li span.result-found {
color: #4b9edd;
}
pre .inline-completions ul.dropdown li span.result {
width: 100px;
color: black;
display: inline-block;
}
.dark-theme .markdown pre {
background-color: #d8d8d8;
border-color: #ddd;
filter: invert(98%) hue-rotate(180deg);
}
data-lsp {
/* Ensures there's no 1px jump when the hover happens */
border-bottom: 1px dotted transparent;
/* Fades in unobtrusively */
transition-timing-function: ease;
transition: border-color 0.3s;
}
/* Respect people's wishes to not have animations */
@media (prefers-reduced-motion: reduce) {
data-lsp {
transition: none;
}
}
/** Annotations support, providing a tool for meta commentary */
.tag-container {
position: relative;
}
.tag-container .twoslash-annotation {
position: absolute;
font-family: "JetBrains Mono", Menlo, Monaco, Consolas, Courier New, monospace;
right: -10px;
/** Default annotation text to 200px */
width: 200px;
color: #187abf;
background-color: #fcf3d9 bb;
}
.tag-container .twoslash-annotation p {
text-align: left;
font-size: 0.8rem;
line-height: 0.9rem;
}
.tag-container .twoslash-annotation svg {
float: left;
margin-left: -44px;
}
.tag-container .twoslash-annotation.left {
right: auto;
left: -200px;
}
.tag-container .twoslash-annotation.left svg {
float: right;
margin-right: -5px;
}
/** Support for showing console log/warn/errors inline */
pre .logger {
display: flex;
align-items: center;
color: black;
padding: 6px;
padding-left: 8px;
width: calc(100% - 19px);
white-space: pre-wrap;
}
pre .logger svg {
margin-right: 9px;
}
pre .logger.error-log {
background-color: #fee;
border-left: 2px solid #bf1818;
}
pre .logger.warn-log {
background-color: #ffe;
border-left: 2px solid #eae662;
}
pre .logger.log-log {
background-color: #e9e9e9;
border-left: 2px solid #ababab;
}
pre .logger.log-log svg {
margin-left: 6px;
margin-right: 9px;
}
body {
--shiki-color-text: #606060;
--shiki-color-background: transparent;
--shiki-token-constant: #00a5a5;
--shiki-token-string: #4e3a2c;
--shiki-token-comment: #aaa;
--shiki-token-keyword: #7b8bff;
--shiki-token-parameter: #ff9800;
--shiki-token-function: #445dd7;
--shiki-token-string-expression: #38a35f;
--shiki-token-punctuation: #969696;
--shiki-token-link: #1aa245;
}
.dark body {
--shiki-color-text: #d1d1d1;
--shiki-token-constant: #2dc9c9;
--shiki-token-string: #feb179;
--shiki-token-comment: #6b737c;
--shiki-token-keyword: #7b8bff;
--shiki-token-parameter: #ff9800;
--shiki-token-function: #9babff;
--shiki-token-string-expression: #42bb69;
--shiki-token-punctuation: #bbb;
--shiki-token-link: #ffab70;
}

View File

@@ -1,10 +1,10 @@
"use client";
import { useTocItems } from "@/lib/TocContext";
import type { Toc } from "@stefanprobst/rehype-extract-toc";
import type { TocEntry } from "@stefanprobst/rehype-extract-toc";
import { useEffect } from "react";
export function TocItemsSetter({ items }: { items: Toc | undefined }) {
export function TocItemsSetter({ items }: { items: TocEntry[] | undefined }) {
const { setTocItems } = useTocItems();
useEffect(() => {

View File

@@ -17,6 +17,7 @@ import {
PropCategory,
PropDecl,
} from "./tags";
import { Fragment } from "react";
export async function PackageDocs({
package: packageName,
@@ -203,10 +204,10 @@ function renderSummary(commentSummary: CommentDisplayPart[] | undefined) {
part.kind === "text" ? (
<span key={idx}>
{part.text.split("\n").map((line, i, lines) => (
<>
<Fragment key={i}>
{line}
{i !== lines.length - 1 && <br />}
</>
</Fragment>
))}
</span>
) : part.kind === "inline-tag" ? (

View File

@@ -1,11 +1,13 @@
import { Icon } from "gcmp-design-system/src/app/components/atoms/Icon";
import Link from "next/link";
import { ReactNode } from "react";
import { getHighlighter } from "shiki";
import { createHighlighter } from "shiki";
import { jazzLight } from "../../themes/jazzLight.mjs";
import { jazzDark } from "../../themes/jazzDark.mjs";
const highlighter = getHighlighter({
langs: ["typescript", "bash"],
theme: "css-variables", // use the theme
const highlighterPromise = createHighlighter({
langs: ["typescript", "bash", "tsx", "json", "svelte", "vue"],
themes: [jazzLight as any, jazzDark as any],
});
export function Example({ children }: { children: ReactNode }) {
@@ -30,27 +32,20 @@ export async function Highlight({
lang?: string;
className?: string;
}) {
const lines = (await highlighter).codeToThemedTokens(
const html = (await highlighterPromise).codeToHtml(
children,
lang,
"css-variables",
{
lang,
structure: "inline",
themes: {
light: "jazz-light",
dark: "jazz-dark",
},
},
);
return (
<code className={className}>
{lines
.filter((_, i) => !hide?.includes(i))
.map((line, i, all) => (
<>
{line.map((token, i) => (
<span key={i} style={{ color: token.color }}>
{token.content}
</span>
))}
{i !== all.length - 1 && <br />}
</>
))}
</code>
<code className={className} dangerouslySetInnerHTML={{ __html: html }} />
);
}

View File

@@ -1,9 +1,9 @@
import type { Toc } from "@stefanprobst/rehype-extract-toc";
import type { TocEntry } from "@stefanprobst/rehype-extract-toc";
import { createContext, useContext } from "react";
type TocContextType = {
tocItems: Toc | undefined;
setTocItems: (items: Toc | undefined) => void;
tocItems: TocEntry[] | undefined;
setTocItems: (items: TocEntry[] | undefined) => void;
};
export const TocContext = createContext<TocContextType | undefined>(undefined);

View File

@@ -68,37 +68,43 @@ export const docNavigationItems = [
{
name: "Upgrade guides",
items: [
{
// upgrade guides
name: "0.12.0 - Deeply Resolved Data",
href: "/docs/upgrade/0-12-0",
done: 100,
},
{
// upgrade guides
name: "0.11.0 - Roles and permissions",
href: "/docs/upgrade/0-11-0",
done: 100,
},
{
// upgrade guides
name: "0.10.0 - New authentication flow",
href: "/docs/upgrade/0-10-0",
done: 100,
},
{
// upgrade guides
name: "0.9.8 - Without me!",
href: "/docs/upgrade/0-9-8",
done: 100,
},
{
// upgrade guides
name: "0.9.2 - Local persistence on React Native",
href: "/docs/upgrade/react-native-local-persistence",
done: 100,
framework: "react-native",
},
{
// upgrade guides
name: "0.9.0 - Top level imports",
href: "/docs/upgrade/0-9-0",
done: 100,
},
// {
// // upgrade guides
// name: "0.10.0 - New authentication flow",
// href: "/docs/upgrade/0-10-0",
// done: 100,
// },
// {
// // upgrade guides
// name: "0.9.8 - Without me!",
// href: "/docs/upgrade/0-9-8",
// done: 100,
// },
// {
// // upgrade guides
// name: "0.9.2 - Local persistence on React Native",
// href: "/docs/upgrade/react-native-local-persistence",
// done: 100,
// framework: "react-native",
// },
// {
// // upgrade guides
// name: "0.9.0 - Top level imports",
// href: "/docs/upgrade/0-9-0",
// done: 100,
// },
],
},
{
@@ -154,13 +160,13 @@ export const docNavigationItems = [
done: 0,
},
{
name: "Loading & subscribing",
href: "/docs/using-covalues/loading-and-subscribing",
done: 0,
name: "Subscriptions & Deep Loading",
href: "/docs/using-covalues/subscription-and-loading",
done: 80,
},
{
name: "History & time travel",
href: "/docs/using-covalues/history-and-time-travel",
href: "/docs/using-covalues/history",
done: 0,
},
],

View File

@@ -2,8 +2,12 @@ import createMDX from "@next/mdx";
import withToc from "@stefanprobst/rehype-extract-toc";
import withTocExport from "@stefanprobst/rehype-extract-toc/mdx";
import rehypeSlug from "rehype-slug";
import { getHighlighter } from "shiki";
import { createHighlighter } from "shiki";
import { transformerNotationDiff, transformerRemoveLineBreak } from '@shikijs/transformers'
import { transformerTwoslash } from "@shikijs/twoslash";
import { SKIP, visit } from "unist-util-visit";
import { jazzLight } from "./themes/jazzLight.mjs";
import { jazzDark } from "./themes/jazzDark.mjs";
/** @type {import('next').NextConfig} */
const nextConfig = {
@@ -34,66 +38,44 @@ const config = {
},
};
const highlighterPromise = createHighlighter({
langs: ["typescript", "bash", "tsx", "json", "svelte", "vue"],
themes: [jazzLight, jazzDark],
});
function highlightPlugin() {
return async function transformer(tree) {
const highlighter = await getHighlighter({
langs: ["typescript", "bash", "tsx", "json", "svelte", "vue"],
theme: "css-variables", // use css variables in shiki.css
});
const highlighter = await highlighterPromise;
visit(tree, "code", visitor);
function visitor(node) {
const lines = highlighter.codeToThemedTokens(
node.value,
node.lang,
"css-variables",
);
let error = "";
const html = highlighter.codeToHtml(node.value, {
lang: node.lang,
meta: { __raw: node.lang + " " + node.meta },
themes: {
light: "jazz-light",
dark: "jazz-dark",
},
let lineNo = -1;
transformers: [
transformerTwoslash({
explicitTrigger: true,
throws: process.env.NODE_ENV === "production",
onTwoslashError: process.env.NODE_ENV !== "production" ? (e) => {
console.error(e);
error = e;
} : undefined,
}),
transformerNotationDiff(),
],
});
node.type = "html";
node.value = `<code class="not-prose py-2 flex flex-col leading-relaxed">${lines
.map((line) => {
let lineClassName = "";
const isSubduedLine = line.some((token) =>
token.content.includes("// old"),
);
const isNewLine = line.some((token) =>
token.content.includes("// *add*"),
);
const isBinnedLine = line.some((token) =>
token.content.includes("// *bin*"),
);
const isHighlighted = line.some((token) =>
token.content.includes("// *highlight*"),
);
if (!isBinnedLine) {
lineNo++;
}
if (isBinnedLine) {
lineClassName = "bg-red-100 dark:bg-red-600/10";
} else if (isHighlighted) {
lineClassName =
"my-0.5 bg-blue-50 text-blue dark:bg-stone-925 dark:text-blue-300";
} else if (isNewLine) {
lineClassName = "bg-green-100 dark:bg-green-600/10";
}
return (
`<span class="block px-3 min-h-[1em] ${lineClassName}" style="${isBinnedLine ? "user-select: none" : ""}">` +
line
.map((token) => {
let color = isHighlighted ? "currentColor" : token.color;
return `<span style="color: ${color};${isSubduedLine ? "opacity: 0.4;" : ""}">${escape(token.content.replace("// old", "").replace("// *add*", "").replace("// *bin*", "").replace("// *highlight*", ""))}</span>`;
})
.join("") +
"</span>"
);
})
.join("\n")}</code>`;
node.value = error
? `<div style="color: red;">${error}</div>` + html
: html;
node.children = [];
return SKIP;
}

View File

@@ -23,6 +23,8 @@
"@mdx-js/react": "^2.3.0",
"@next/mdx": "^13.5.4",
"@radix-ui/react-tooltip": "^1.1.6",
"@shikijs/transformers": "^3.2.1",
"@shikijs/twoslash": "^3.2.1",
"@stefanprobst/rehype-extract-toc": "^2.2.0",
"@turf/turf": "^7.1.0",
"@types/mdx": "^2.0.8",
@@ -31,11 +33,11 @@
"@vercel/speed-insights": "^1.0.12",
"clsx": "^2.1.1",
"gcmp-design-system": "workspace:*",
"jazz-browser": "workspace:../*",
"jazz-browser-media-images": "workspace:../*",
"jazz-nodejs": "workspace:../*",
"jazz-react": "workspace:../*",
"jazz-tools": "workspace:../*",
"jazz-browser": "link:../../packages/jazz-browser",
"jazz-browser-media-images": "link:../../packages/jazz-browser-media-images",
"jazz-nodejs": "link:../../packages/jazz-nodejs",
"jazz-react": "link:../../packages/jazz-react",
"jazz-tools": "link:../../packages/jazz-tools",
"lucide-react": "^0.436.0",
"mdast-util-from-markdown": "^2.0.0",
"mdast-util-mdx": "^3.0.0",
@@ -46,8 +48,7 @@
"react": "^18",
"react-dom": "^18",
"rehype-slug": "^6.0.0",
"shiki": "^0.14.6",
"shiki-twoslash": "^3.1.2",
"shiki": "^3.2.1",
"tailwind-merge": "^1.14.0",
"tailwindcss-animate": "^1.0.7",
"unist-util-visit": "^5.0.0"

View File

@@ -0,0 +1,136 @@
export const jazzDark = {
name: "jazz-dark",
type: "dark",
fg: "#d1d1d1",
settings: [
{
scope: [
"keyword.operator.accessor",
"meta.group.braces.round.function.arguments",
"meta.template.expression",
"markup.fenced_code meta.embedded.block",
],
settings: {
foreground: "#969696",
},
},
{
scope: "emphasis",
settings: {
fontStyle: "italic",
},
},
{
scope: ["strong", "markup.heading.markdown", "markup.bold.markdown"],
settings: {
fontStyle: "bold",
},
},
{
scope: ["markup.italic.markdown"],
settings: {
fontStyle: "italic",
},
},
{
scope: "meta.link.inline.markdown",
settings: {
fontStyle: "underline",
foreground: "#ffab70",
},
},
{
scope: ["string", "markup.fenced_code", "markup.inline"],
settings: {
foreground: "#feb179",
},
},
{
scope: ["comment", "string.quoted.docstring.multi"],
settings: {
foreground: "#aaa",
},
},
{
scope: [
"constant.numeric",
"constant.language",
"constant.other.placeholder",
"constant.character.format.placeholder",
"variable.language.this",
"variable.other.object",
"variable.other.class",
"variable.other.constant",
"meta.property-name",
"meta.property-value",
"support",
],
settings: {
foreground: "#2dc9c9",
},
},
{
scope: [
"keyword",
"storage.modifier",
"storage.type",
"storage.control.clojure",
"entity.name.function.clojure",
"entity.name.tag.yaml",
"support.function.node",
"support.type.property-name.json",
"punctuation.separator.key-value",
"punctuation.definition.template-expression",
],
settings: {
foreground: "#7b8bff",
},
},
{
scope: [
"punctuation.definition.arguments",
"punctuation.definition.dict",
"punctuation.separator",
"meta.function-call.arguments",
],
settings: {
foreground: "#bbbbbb",
},
},
{
scope: "variable.parameter.function",
settings: {
foreground: "#bbbbbb",
},
},
{
scope: [
"support.function",
"entity.name.type",
"entity.other.inherited-class",
"meta.function-call",
"meta.instance.constructor",
"entity.other.attribute-name",
"entity.name.function",
"constant.keyword.clojure",
],
settings: {
foreground: "#9babff",
},
},
{
scope: [
"entity.name.tag",
"string.quoted",
"string.regexp",
"string.interpolated",
"string.template",
"string.unquoted.plain.out.yaml",
"keyword.other.template",
],
settings: {
foreground: "#42bb69",
},
},
],
};

View File

@@ -0,0 +1,135 @@
export const jazzLight = {
name: "jazz-light",
type: "light",
settings: [
{
scope: [
"keyword.operator.accessor",
"meta.group.braces.round.function.arguments",
"meta.template.expression",
"markup.fenced_code meta.embedded.block",
],
settings: {
foreground: "#969696",
},
},
{
scope: "emphasis",
settings: {
fontStyle: "italic",
},
},
{
scope: ["strong", "markup.heading.markdown", "markup.bold.markdown"],
settings: {
fontStyle: "bold",
},
},
{
scope: ["markup.italic.markdown"],
settings: {
fontStyle: "italic",
},
},
{
scope: "meta.link.inline.markdown",
settings: {
fontStyle: "underline",
foreground: "#1aa245",
},
},
{
scope: ["string", "markup.fenced_code", "markup.inline"],
settings: {
foreground: "#4e3a2c",
},
},
{
scope: ["comment", "string.quoted.docstring.multi"],
settings: {
foreground: "#aaa",
},
},
{
scope: [
"constant.numeric",
"constant.language",
"constant.other.placeholder",
"constant.character.format.placeholder",
"variable.language.this",
"variable.other.object",
"variable.other.class",
"variable.other.constant",
"meta.property-name",
"meta.property-value",
"support",
],
settings: {
foreground: "#00a5a5",
},
},
{
scope: [
"keyword",
"storage.modifier",
"storage.type",
"storage.control.clojure",
"entity.name.function.clojure",
"entity.name.tag.yaml",
"support.function.node",
"support.type.property-name.json",
"punctuation.separator.key-value",
"punctuation.definition.template-expression",
],
settings: {
foreground: "#7b8bff",
},
},
{
scope: [
"punctuation.definition.arguments",
"punctuation.definition.dict",
"punctuation.separator",
"meta.function-call.arguments",
],
settings: {
foreground: "#7b8bff",
},
},
{
scope: "variable.parameter.function",
settings: {
foreground: "#ff9800",
},
},
{
scope: [
"support.function",
"entity.name.type",
"entity.other.inherited-class",
"meta.function-call",
"meta.instance.constructor",
"entity.other.attribute-name",
"entity.name.function",
"constant.keyword.clojure",
],
settings: {
foreground: "#445dd7",
},
},
{
scope: [
"entity.name.tag",
"string.quoted",
"string.regexp",
"string.interpolated",
"string.template",
"string.unquoted.plain.out.yaml",
"keyword.other.template",
],
settings: {
foreground: "#42bb69",
},
},
],
};

325
homepage/pnpm-lock.yaml generated
View File

@@ -28,10 +28,10 @@ importers:
version: 0.436.0(react@18.3.1)
next:
specifier: 14.2.7
version: 14.2.7(react-dom@18.3.1(react@18.3.1))(react@18.3.1)
version: 14.2.7(@opentelemetry/api@1.9.0)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)
next-themes:
specifier: ^0.2.1
version: 0.2.1(next@14.2.7(react-dom@18.3.1(react@18.3.1))(react@18.3.1))(react-dom@18.3.1(react@18.3.1))(react@18.3.1)
version: 0.2.1(next@14.2.7(@opentelemetry/api@1.9.0)(react-dom@18.3.1(react@18.3.1))(react@18.3.1))(react-dom@18.3.1(react@18.3.1))(react@18.3.1)
react:
specifier: ^18
version: 18.3.1
@@ -95,10 +95,10 @@ importers:
version: 2.0.13
'@vercel/analytics':
specifier: ^1.3.1
version: 1.3.1(next@14.2.15(react-dom@18.3.1(react@18.3.1))(react@18.3.1))(react@18.3.1)
version: 1.3.1(next@14.2.15(@opentelemetry/api@1.9.0)(react-dom@18.3.1(react@18.3.1))(react@18.3.1))(react@18.3.1)
'@vercel/speed-insights':
specifier: ^1.0.12
version: 1.0.12(next@14.2.15(react-dom@18.3.1(react@18.3.1))(react@18.3.1))(react@18.3.1)
version: 1.0.12(next@14.2.15(@opentelemetry/api@1.9.0)(react-dom@18.3.1(react@18.3.1))(react@18.3.1))(react@18.3.1)
clsx:
specifier: ^2.1.1
version: 2.1.1
@@ -122,10 +122,10 @@ importers:
version: 3.0.0
next:
specifier: 14.2.15
version: 14.2.15(react-dom@18.3.1(react@18.3.1))(react@18.3.1)
version: 14.2.15(@opentelemetry/api@1.9.0)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)
next-themes:
specifier: ^0.2.1
version: 0.2.1(next@14.2.15(react-dom@18.3.1(react@18.3.1))(react@18.3.1))(react-dom@18.3.1(react@18.3.1))(react@18.3.1)
version: 0.2.1(next@14.2.15(@opentelemetry/api@1.9.0)(react-dom@18.3.1(react@18.3.1))(react@18.3.1))(react-dom@18.3.1(react@18.3.1))(react@18.3.1)
react:
specifier: ^18
version: 18.3.1
@@ -196,6 +196,12 @@ importers:
'@radix-ui/react-tooltip':
specifier: ^1.1.6
version: 1.1.6(@types/react-dom@18.3.0)(@types/react@18.3.1)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)
'@shikijs/transformers':
specifier: ^3.2.1
version: 3.2.1
'@shikijs/twoslash':
specifier: ^3.2.1
version: 3.2.1(typescript@5.4.5)
'@stefanprobst/rehype-extract-toc':
specifier: ^2.2.0
version: 2.2.0
@@ -210,10 +216,10 @@ importers:
version: 3.1.5
'@vercel/analytics':
specifier: ^1.3.1
version: 1.3.1(next@15.2.1(react-dom@18.3.1(react@18.3.1))(react@18.3.1))(react@18.3.1)
version: 1.3.1(next@15.2.1(@opentelemetry/api@1.9.0)(react-dom@18.3.1(react@18.3.1))(react@18.3.1))(react@18.3.1)
'@vercel/speed-insights':
specifier: ^1.0.12
version: 1.0.12(next@15.2.1(react-dom@18.3.1(react@18.3.1))(react@18.3.1))(react@18.3.1)
version: 1.0.12(next@15.2.1(@opentelemetry/api@1.9.0)(react-dom@18.3.1(react@18.3.1))(react@18.3.1))(react@18.3.1)
clsx:
specifier: ^2.1.1
version: 2.1.1
@@ -221,20 +227,20 @@ importers:
specifier: workspace:*
version: link:../design-system
jazz-browser:
specifier: workspace:../*
version: link:../*
specifier: link:../../packages/jazz-browser
version: link:../../packages/jazz-browser
jazz-browser-media-images:
specifier: workspace:../*
version: link:../*
specifier: link:../../packages/jazz-browser-media-images
version: link:../../packages/jazz-browser-media-images
jazz-nodejs:
specifier: workspace:../*
version: link:../*
specifier: link:../../packages/jazz-nodejs
version: link:../../packages/jazz-nodejs
jazz-react:
specifier: workspace:../*
version: link:../*
specifier: link:../../packages/jazz-react
version: link:../../packages/jazz-react
jazz-tools:
specifier: workspace:../*
version: link:../*
specifier: link:../../packages/jazz-tools
version: link:../../packages/jazz-tools
lucide-react:
specifier: ^0.436.0
version: 0.436.0(react@18.3.1)
@@ -249,10 +255,10 @@ importers:
version: 3.0.0
next:
specifier: 15.2.1
version: 15.2.1(react-dom@18.3.1(react@18.3.1))(react@18.3.1)
version: 15.2.1(@opentelemetry/api@1.9.0)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)
next-themes:
specifier: ^0.2.1
version: 0.2.1(next@15.2.1(react-dom@18.3.1(react@18.3.1))(react@18.3.1))(react-dom@18.3.1(react@18.3.1))(react@18.3.1)
version: 0.2.1(next@15.2.1(@opentelemetry/api@1.9.0)(react-dom@18.3.1(react@18.3.1))(react@18.3.1))(react-dom@18.3.1(react@18.3.1))(react@18.3.1)
qrcode:
specifier: ^1.5.4
version: 1.5.4
@@ -266,11 +272,8 @@ importers:
specifier: ^6.0.0
version: 6.0.0
shiki:
specifier: ^0.14.6
version: 0.14.7
shiki-twoslash:
specifier: ^3.1.2
version: 3.1.2(typescript@5.4.5)
specifier: ^3.2.1
version: 3.2.1
tailwind-merge:
specifier: ^1.14.0
version: 1.14.0
@@ -790,6 +793,10 @@ packages:
'@one-ini/wasm@0.1.1':
resolution: {integrity: sha512-XuySG1E38YScSJoMlqovLru4KTUNSjgVTIjyh7qMX6aNN5HY5Ct5LhRJdxO79JtTzKfzV/bnWpz+zquYrISsvw==}
'@opentelemetry/api@1.9.0':
resolution: {integrity: sha512-3giAOQvZiH5F9bMlMiv8+GSPMeqg0dbaeo58/0SlA9sxSqZhnUtxzX9/2FzyhS9sWQf5S0GJE0AKBrFqjpeYcg==}
engines: {node: '>=8.0.0'}
'@pkgjs/parseargs@0.11.0':
resolution: {integrity: sha512-+1VkjdD0QBLPodGrJUeqarH8VAIvQODIbwh9XpP5Syisf7YoQgsJKPNFoqqLQlu+VQ/tVSshMR6loPMn8U+dPg==}
engines: {node: '>=14'}
@@ -1035,6 +1042,35 @@ packages:
'@selderee/plugin-htmlparser2@0.11.0':
resolution: {integrity: sha512-P33hHGdldxGabLFjPPpaTxVolMrzrcegejx+0GxjrIb9Zv48D8yAIA/QTDR2dFl7Uz7urX8aX6+5bCZslr+gWQ==}
'@shikijs/core@3.2.1':
resolution: {integrity: sha512-FhsdxMWYu/C11sFisEp7FMGBtX/OSSbnXZDMBhGuUDBNTdsoZlMSgQv5f90rwvzWAdWIW6VobD+G3IrazxA6dQ==}
'@shikijs/engine-javascript@3.2.1':
resolution: {integrity: sha512-eMdcUzN3FMQYxOmRf2rmU8frikzoSHbQDFH2hIuXsrMO+IBOCI9BeeRkCiBkcLDHeRKbOCtYMJK3D6U32ooU9Q==}
'@shikijs/engine-oniguruma@3.2.1':
resolution: {integrity: sha512-wZZAkayEn6qu2+YjenEoFqj0OyQI64EWsNR6/71d1EkG4sxEOFooowKivsWPpaWNBu3sxAG+zPz5kzBL/SsreQ==}
'@shikijs/langs@3.2.1':
resolution: {integrity: sha512-If0iDHYRSGbihiA8+7uRsgb1er1Yj11pwpX1c6HLYnizDsKAw5iaT3JXj5ZpaimXSWky/IhxTm7C6nkiYVym+A==}
'@shikijs/themes@3.2.1':
resolution: {integrity: sha512-k5DKJUT8IldBvAm8WcrDT5+7GA7se6lLksR+2E3SvyqGTyFMzU2F9Gb7rmD+t+Pga1MKrYFxDIeyWjMZWM6uBQ==}
'@shikijs/transformers@3.2.1':
resolution: {integrity: sha512-oIT40p8LOPV/6XLnUrVPeRtJtbu0Mpl+BjGFuMXw870eX9zTSQlidg7CsksFDVyUiSAOC/CH1RQm+ldZp0/6eQ==}
'@shikijs/twoslash@3.2.1':
resolution: {integrity: sha512-2ZiL9xXY8JRXHG5BdJXE9KoIeSsyH9/yK+YTN90/SUIKkq7Nf5dWqXp5wJ6+4SL0FQO8mq2HUutwqU+gamOgOA==}
peerDependencies:
typescript: '>=5.5.0'
'@shikijs/types@3.2.1':
resolution: {integrity: sha512-/NTWAk4KE2M8uac0RhOsIhYQf4pdU0OywQuYDGIGAJ6Mjunxl2cGiuLkvu4HLCMn+OTTLRWkjZITp+aYJv60yA==}
'@shikijs/vscode-textmate@10.0.2':
resolution: {integrity: sha512-83yeghZ2xxin3Nj8z1NMd/NCuca+gsYXswywDy5bHvwlWL8tpTQmzGeUuHd9FC3E/SBEMvzJRwWEOz5gGes9Qg==}
'@stefanprobst/rehype-extract-toc@2.2.0':
resolution: {integrity: sha512-/4UjstX8ploZklY8MmlOQoXB1jWIo3Go4MP0R39sbkoWuN6rJ7Zt6l4bjkDPM4hKsjoODh9SSKn2otlp3XL3/A==}
engines: {node: '>=14.17'}
@@ -1488,6 +1524,14 @@ packages:
'@typescript/vfs@1.3.5':
resolution: {integrity: sha512-pI8Saqjupf9MfLw7w2+og+fmb0fZS0J6vsKXXrp4/PDXEFvntgzXmChCXC/KefZZS0YGS6AT8e0hGAJcTsdJlg==}
'@typescript/vfs@1.6.1':
resolution: {integrity: sha512-JwoxboBh7Oz1v38tPbkrZ62ZXNHAk9bJ7c9x0eI5zBfBnBYGhURdbnh7Z4smN/MV48Y5OCcZb58n972UtbazsA==}
peerDependencies:
typescript: '*'
'@ungap/structured-clone@1.3.0':
resolution: {integrity: sha512-WmoN8qaIAo7WTYWbAZuG8PYEhn5fkz7dZrqTBZ7dtt//lL2Gwms1IcnQ5yHqjDfX8Ft5j4YzDM23f87zBfDe9g==}
'@vercel/analytics@1.3.1':
resolution: {integrity: sha512-xhSlYgAuJ6Q4WQGkzYTLmXwhYl39sWjoMA3nHxfkvG+WdBT25c563a7QhwwKivEOZtPJXifYHR1m2ihoisbWyA==}
peerDependencies:
@@ -1863,6 +1907,9 @@ packages:
electron-to-chromium@1.5.64:
resolution: {integrity: sha512-IXEuxU+5ClW2IGEYFC2T7szbyVgehupCWQe5GNh+H065CD6U6IFN0s4KeAMFGNmQolRU4IV7zGBWSYMmZ8uuqQ==}
emoji-regex-xs@1.0.0:
resolution: {integrity: sha512-LRlerrMYoIDrT6jgpeZ2YYl/L8EulRTt5hQcYjy5AInh7HWXKimpqx68aknBFpGL2+/IcogTcaydJEgaTmOpDg==}
emoji-regex@8.0.0:
resolution: {integrity: sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==}
@@ -2035,6 +2082,9 @@ packages:
hast-util-to-estree@2.3.3:
resolution: {integrity: sha512-ihhPIUPxN0v0w6M5+IiAZZrn0LH2uZomeWwhn7uP7avZC6TE7lIiEh2yBMPr5+zi1aUCXq6VoYRgs2Bw9xmycQ==}
hast-util-to-html@9.0.5:
resolution: {integrity: sha512-OguPdidb+fbHQSU4Q4ZiLKnzWo8Wwsf5bZfbvu7//a9oTYoqD/fWpe96NuHkoS9h0ccGOTe0C4NGXdtS0iObOw==}
hast-util-to-string@2.0.0:
resolution: {integrity: sha512-02AQ3vLhuH3FisaMM+i/9sm4OXGSq1UhOOCpTLLQtHdL3tZt7qil69r8M8iDkZYyC0HCFylcYoP+8IO7ddta1A==}
@@ -2044,10 +2094,16 @@ packages:
hast-util-whitespace@2.0.1:
resolution: {integrity: sha512-nAxA0v8+vXSBDt3AnRUNjyRIQ0rD+ntpbAp4LnPkumc5M9yUbSMa4XDU9Q6etY4f1Wp4bNgvc1yjiZtsTTrSng==}
hast-util-whitespace@3.0.0:
resolution: {integrity: sha512-88JUN06ipLwsnv+dVn+OIYOvAuvBMy/Qoi6O7mQHxdPXpjy+Cd6xRkWwux7DKO+4sYILtLBRIKgsdpS2gQc7qw==}
html-to-text@9.0.5:
resolution: {integrity: sha512-qY60FjREgVZL03vJU6IfMV4GDjGBIoOyvuFdpBDIX9yTlDw0TjxVBQp+P8NvpdIXNJvfWBTNul7fsAQJq2FNpg==}
engines: {node: '>=14'}
html-void-elements@3.0.0:
resolution: {integrity: sha512-bEqo66MRXsUGxWHV5IP0PUiAWwoEjba4VCzg0LjFJBpchPaTfyfCKTG6bc5F8ucKec3q5y6qOdGyYTSBEvhCrg==}
htmlparser2@8.0.2:
resolution: {integrity: sha512-GYdjWKDkbRLkZ5geuHs5NY1puJ+PXwP7+fHPRz06Eirsb9ugf6d8kkXav6ADhcODhFFPMIXyxkxSuMf3D6NCFA==}
@@ -2262,6 +2318,9 @@ packages:
mdast-util-to-hast@12.3.0:
resolution: {integrity: sha512-pits93r8PhnIoU4Vy9bjW39M2jJ6/tdHyja9rrot9uujkN7UTU9SDnE6WNJz/IGyQk3XHX6yNNtrBH6cQzm8Hw==}
mdast-util-to-hast@13.2.0:
resolution: {integrity: sha512-QGYKEuUsYT9ykKBCMOEDLsU5JRObWQusAolFMeko/tYPufNkRffBAQjIE+99jbA87xv6FgmjLtwjh9wBWajwAA==}
mdast-util-to-markdown@1.5.0:
resolution: {integrity: sha512-bbv7TPv/WC49thZPg3jXuqzuvI45IL2EVAr/KxF0BSdHsU0ceFHOmwQn6evxAh1GaoK/6GQ1wp4R4oW2+LFL/A==}
@@ -2582,6 +2641,12 @@ packages:
resolution: {integrity: sha512-RSn9F68PjH9HqtltsSnqYC1XXoWe9Bju5+213R98cNGttag9q9yAOTzdbsqvIa7aNm5WffBZFpWYr2aWrklWAw==}
engines: {node: '>= 6'}
oniguruma-parser@0.5.4:
resolution: {integrity: sha512-yNxcQ8sKvURiTwP0mV6bLQCYE7NKfKRRWunhbZnXgxSmB1OXa1lHrN3o4DZd+0Si0kU5blidK7BcROO8qv5TZA==}
oniguruma-to-es@4.1.0:
resolution: {integrity: sha512-SNwG909cSLo4vPyyPbU/VJkEc9WOXqu2ycBlfd1UCXLqk1IijcQktSBb2yRQ2UFPsDhpkaf+C1dtT3PkLK/yWA==}
p-limit@2.3.0:
resolution: {integrity: sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w==}
engines: {node: '>=6'}
@@ -2704,6 +2769,9 @@ packages:
property-information@6.5.0:
resolution: {integrity: sha512-PgTgs/BlvHxOu8QuEN7wi5A0OmXaBcHpmCSTehcs6Uuu9IkDIEo13Hy7n898RHfrQ49vKCoGeWZSaAK01nwVig==}
property-information@7.0.0:
resolution: {integrity: sha512-7D/qOz/+Y4X/rzSB6jKxKUsQnphO046ei8qxG59mtM3RG3DHgTK81HrxrmoDVINJb8NKT5ZsRbwHvQ6B68Iyhg==}
proto-list@1.2.4:
resolution: {integrity: sha512-vtK/94akxsTMhe0/cbfpR+syPuszcuwhqVjJq26CuNDgFGj682oRBXOP5MJpv2r7JtE8MsiepGIqvvOTBwn2vA==}
@@ -2753,6 +2821,15 @@ packages:
resolution: {integrity: sha512-hOS089on8RduqdbhvQ5Z37A0ESjsqz6qnRcffsMU3495FuTdqSm+7bhJ29JvIOsBDEEnan5DPu9t3To9VRlMzA==}
engines: {node: '>=8.10.0'}
regex-recursion@6.0.2:
resolution: {integrity: sha512-0YCaSCq2VRIebiaUviZNs0cBz1kg5kVS2UKUfNIx8YVs1cN3AV7NTctO5FOKBA+UT2BPJIWZauYHPqJODG50cg==}
regex-utilities@2.3.0:
resolution: {integrity: sha512-8VhliFJAWRaUiVvREIiW2NXXTmHs4vMNnSzuJVhscgmGav3g9VDxLrQndI3dZZVVdp0ZO/5v0xmX516/7M9cng==}
regex@6.0.1:
resolution: {integrity: sha512-uorlqlzAKjKQZ5P+kTJr3eeJGSVroLKoHmquUj4zHWuR+hEyNqlXsSKlYYF5F4NI6nl7tWCs0apKJ0lmfsXAPA==}
rehype-slug@6.0.0:
resolution: {integrity: sha512-lWyvf/jwu+oS5+hL5eClVd3hNdmwM1kAC0BUvEGD19pajQMIzcNUd/k9GsfQ+FfECvX+JE+e9/btsKH0EjJT6A==}
@@ -2855,6 +2932,9 @@ packages:
shiki@0.14.7:
resolution: {integrity: sha512-dNPAPrxSc87ua2sKJ3H5dQ/6ZaY8RNnaAqK+t0eG7p0Soi2ydiqbGOTaZCqaYvA/uZYfS1LJnemt3Q+mSfcPCg==}
shiki@3.2.1:
resolution: {integrity: sha512-VML/2o1/KGYkEf/stJJ+s9Ypn7jUKQPomGLGYso4JJFMFxVDyPNsjsI3MB3KLjlMOeH44gyaPdXC6rik2WXvUQ==}
signal-exit@4.1.0:
resolution: {integrity: sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw==}
engines: {node: '>=14'}
@@ -3033,6 +3113,14 @@ packages:
tslib@2.8.1:
resolution: {integrity: sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==}
twoslash-protocol@0.3.1:
resolution: {integrity: sha512-BMePTL9OkuNISSyyMclBBhV2s9++DiOCyhhCoV5Kaht6eaWLwVjCCUJHY33eZJPsyKeZYS8Wzz0h+XI01VohVw==}
twoslash@0.3.1:
resolution: {integrity: sha512-OGqMTGvqXTcb92YQdwGfEdK0nZJA64Aj/ChLOelbl3TfYch2IoBST0Yx4C0LQ7Lzyqm9RpgcpgDxeXQIz4p2Kg==}
peerDependencies:
typescript: ^5.5.0
typedoc@0.25.13:
resolution: {integrity: sha512-pQqiwiJ+Z4pigfOnnysObszLiU3mVLWAExSPf+Mu06G/qsc3wzbuM56SZQvONhHLncLUhYzOVkjFFpFfL5AzhQ==}
engines: {node: '>= 16'}
@@ -3072,6 +3160,9 @@ packages:
unist-util-position@4.0.4:
resolution: {integrity: sha512-kUBE91efOWfIVBo8xzh/uZQ7p9ffYRtUbMRZBNFYwf0RK8koUMx6dGUfwylLOKmaT2cs4wSW96QoYUSXAyEtpg==}
unist-util-position@5.0.0:
resolution: {integrity: sha512-fucsC7HjXvkB5R3kTCO7kUjRdrS0BJt3M/FPxmHMBOm8JQi2BsHAHFsy27E0EolP8rp0NzXsJ+jNPyDWvOJZPA==}
unist-util-remove-position@4.0.2:
resolution: {integrity: sha512-TkBb0HABNmxzAcfLf4qsIbFbaPDvMO6wa3b3j4VcEzFVaw1LBKwnW4/sRJ/atSLSzoIg41JWEdnE7N6DIhGDGQ==}
@@ -3128,6 +3219,9 @@ packages:
vfile@5.3.7:
resolution: {integrity: sha512-r7qlzkgErKjobAmyNIkkSpizsFPYiUPuJb5pNW1RB4JcYVZhs4lIbVqk8XPk033CV/1z8ss5pkax8SuhGpcG8g==}
vfile@6.0.3:
resolution: {integrity: sha512-KzIbH/9tXat2u30jf+smMwFCsno4wHVdNmzFyL+T/L3UGqqk6JKfVqOFOZEpZSHADH1k40ab6NUIXZq422ov3Q==}
vscode-oniguruma@1.7.0:
resolution: {integrity: sha512-L9WMGRfrjOhgHSdOYgCt/yRMsXzLDJSL7BPrOZt73gU0iWO4mpqzqQzOz5srxqTvMBaR0XZTSrVWo4j55Rc6cA==}
@@ -3567,6 +3661,9 @@ snapshots:
'@one-ini/wasm@0.1.1': {}
'@opentelemetry/api@1.9.0':
optional: true
'@pkgjs/parseargs@0.11.0':
optional: true
@@ -3791,6 +3888,53 @@ snapshots:
domhandler: 5.0.3
selderee: 0.11.0
'@shikijs/core@3.2.1':
dependencies:
'@shikijs/types': 3.2.1
'@shikijs/vscode-textmate': 10.0.2
'@types/hast': 3.0.4
hast-util-to-html: 9.0.5
'@shikijs/engine-javascript@3.2.1':
dependencies:
'@shikijs/types': 3.2.1
'@shikijs/vscode-textmate': 10.0.2
oniguruma-to-es: 4.1.0
'@shikijs/engine-oniguruma@3.2.1':
dependencies:
'@shikijs/types': 3.2.1
'@shikijs/vscode-textmate': 10.0.2
'@shikijs/langs@3.2.1':
dependencies:
'@shikijs/types': 3.2.1
'@shikijs/themes@3.2.1':
dependencies:
'@shikijs/types': 3.2.1
'@shikijs/transformers@3.2.1':
dependencies:
'@shikijs/core': 3.2.1
'@shikijs/types': 3.2.1
'@shikijs/twoslash@3.2.1(typescript@5.4.5)':
dependencies:
'@shikijs/core': 3.2.1
'@shikijs/types': 3.2.1
twoslash: 0.3.1(typescript@5.4.5)
typescript: 5.4.5
transitivePeerDependencies:
- supports-color
'@shikijs/types@3.2.1':
dependencies:
'@shikijs/vscode-textmate': 10.0.2
'@types/hast': 3.0.4
'@shikijs/vscode-textmate@10.0.2': {}
'@stefanprobst/rehype-extract-toc@2.2.0':
dependencies:
estree-util-is-identifier-name: 2.1.0
@@ -5030,28 +5174,37 @@ snapshots:
transitivePeerDependencies:
- supports-color
'@vercel/analytics@1.3.1(next@14.2.15(react-dom@18.3.1(react@18.3.1))(react@18.3.1))(react@18.3.1)':
'@typescript/vfs@1.6.1(typescript@5.4.5)':
dependencies:
debug: 4.3.4
typescript: 5.4.5
transitivePeerDependencies:
- supports-color
'@ungap/structured-clone@1.3.0': {}
'@vercel/analytics@1.3.1(next@14.2.15(@opentelemetry/api@1.9.0)(react-dom@18.3.1(react@18.3.1))(react@18.3.1))(react@18.3.1)':
dependencies:
server-only: 0.0.1
optionalDependencies:
next: 14.2.15(react-dom@18.3.1(react@18.3.1))(react@18.3.1)
next: 14.2.15(@opentelemetry/api@1.9.0)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)
react: 18.3.1
'@vercel/analytics@1.3.1(next@15.2.1(react-dom@18.3.1(react@18.3.1))(react@18.3.1))(react@18.3.1)':
'@vercel/analytics@1.3.1(next@15.2.1(@opentelemetry/api@1.9.0)(react-dom@18.3.1(react@18.3.1))(react@18.3.1))(react@18.3.1)':
dependencies:
server-only: 0.0.1
optionalDependencies:
next: 15.2.1(react-dom@18.3.1(react@18.3.1))(react@18.3.1)
next: 15.2.1(@opentelemetry/api@1.9.0)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)
react: 18.3.1
'@vercel/speed-insights@1.0.12(next@14.2.15(react-dom@18.3.1(react@18.3.1))(react@18.3.1))(react@18.3.1)':
'@vercel/speed-insights@1.0.12(next@14.2.15(@opentelemetry/api@1.9.0)(react-dom@18.3.1(react@18.3.1))(react@18.3.1))(react@18.3.1)':
optionalDependencies:
next: 14.2.15(react-dom@18.3.1(react@18.3.1))(react@18.3.1)
next: 14.2.15(@opentelemetry/api@1.9.0)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)
react: 18.3.1
'@vercel/speed-insights@1.0.12(next@15.2.1(react-dom@18.3.1(react@18.3.1))(react@18.3.1))(react@18.3.1)':
'@vercel/speed-insights@1.0.12(next@15.2.1(@opentelemetry/api@1.9.0)(react-dom@18.3.1(react@18.3.1))(react@18.3.1))(react@18.3.1)':
optionalDependencies:
next: 15.2.1(react-dom@18.3.1(react@18.3.1))(react@18.3.1)
next: 15.2.1(@opentelemetry/api@1.9.0)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)
react: 18.3.1
'@webassemblyjs/ast@1.14.1':
@@ -5392,6 +5545,8 @@ snapshots:
electron-to-chromium@1.5.64: {}
emoji-regex-xs@1.0.0: {}
emoji-regex@8.0.0: {}
emoji-regex@9.2.2: {}
@@ -5575,6 +5730,20 @@ snapshots:
transitivePeerDependencies:
- supports-color
hast-util-to-html@9.0.5:
dependencies:
'@types/hast': 3.0.4
'@types/unist': 3.0.2
ccount: 2.0.1
comma-separated-tokens: 2.0.3
hast-util-whitespace: 3.0.0
html-void-elements: 3.0.0
mdast-util-to-hast: 13.2.0
property-information: 7.0.0
space-separated-tokens: 2.0.2
stringify-entities: 4.0.4
zwitch: 2.0.4
hast-util-to-string@2.0.0:
dependencies:
'@types/hast': 2.3.10
@@ -5585,6 +5754,10 @@ snapshots:
hast-util-whitespace@2.0.1: {}
hast-util-whitespace@3.0.0:
dependencies:
'@types/hast': 3.0.4
html-to-text@9.0.5:
dependencies:
'@selderee/plugin-htmlparser2': 0.11.0
@@ -5593,6 +5766,8 @@ snapshots:
htmlparser2: 8.0.2
selderee: 0.11.0
html-void-elements@3.0.0: {}
htmlparser2@8.0.2:
dependencies:
domelementtype: 2.3.0
@@ -5884,6 +6059,18 @@ snapshots:
unist-util-position: 4.0.4
unist-util-visit: 4.1.2
mdast-util-to-hast@13.2.0:
dependencies:
'@types/hast': 3.0.4
'@types/mdast': 4.0.3
'@ungap/structured-clone': 1.3.0
devlop: 1.1.0
micromark-util-sanitize-uri: 2.0.0
trim-lines: 3.0.1
unist-util-position: 5.0.0
unist-util-visit: 5.0.0
vfile: 6.0.3
mdast-util-to-markdown@1.5.0:
dependencies:
'@types/mdast': 3.0.15
@@ -6365,25 +6552,25 @@ snapshots:
neo-async@2.6.2: {}
next-themes@0.2.1(next@14.2.15(react-dom@18.3.1(react@18.3.1))(react@18.3.1))(react-dom@18.3.1(react@18.3.1))(react@18.3.1):
next-themes@0.2.1(next@14.2.15(@opentelemetry/api@1.9.0)(react-dom@18.3.1(react@18.3.1))(react@18.3.1))(react-dom@18.3.1(react@18.3.1))(react@18.3.1):
dependencies:
next: 14.2.15(react-dom@18.3.1(react@18.3.1))(react@18.3.1)
next: 14.2.15(@opentelemetry/api@1.9.0)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)
react: 18.3.1
react-dom: 18.3.1(react@18.3.1)
next-themes@0.2.1(next@14.2.7(react-dom@18.3.1(react@18.3.1))(react@18.3.1))(react-dom@18.3.1(react@18.3.1))(react@18.3.1):
next-themes@0.2.1(next@14.2.7(@opentelemetry/api@1.9.0)(react-dom@18.3.1(react@18.3.1))(react@18.3.1))(react-dom@18.3.1(react@18.3.1))(react@18.3.1):
dependencies:
next: 14.2.7(react-dom@18.3.1(react@18.3.1))(react@18.3.1)
next: 14.2.7(@opentelemetry/api@1.9.0)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)
react: 18.3.1
react-dom: 18.3.1(react@18.3.1)
next-themes@0.2.1(next@15.2.1(react-dom@18.3.1(react@18.3.1))(react@18.3.1))(react-dom@18.3.1(react@18.3.1))(react@18.3.1):
next-themes@0.2.1(next@15.2.1(@opentelemetry/api@1.9.0)(react-dom@18.3.1(react@18.3.1))(react@18.3.1))(react-dom@18.3.1(react@18.3.1))(react@18.3.1):
dependencies:
next: 15.2.1(react-dom@18.3.1(react@18.3.1))(react@18.3.1)
next: 15.2.1(@opentelemetry/api@1.9.0)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)
react: 18.3.1
react-dom: 18.3.1(react@18.3.1)
next@14.2.15(react-dom@18.3.1(react@18.3.1))(react@18.3.1):
next@14.2.15(@opentelemetry/api@1.9.0)(react-dom@18.3.1(react@18.3.1))(react@18.3.1):
dependencies:
'@next/env': 14.2.15
'@swc/helpers': 0.5.5
@@ -6404,11 +6591,12 @@ snapshots:
'@next/swc-win32-arm64-msvc': 14.2.15
'@next/swc-win32-ia32-msvc': 14.2.15
'@next/swc-win32-x64-msvc': 14.2.15
'@opentelemetry/api': 1.9.0
transitivePeerDependencies:
- '@babel/core'
- babel-plugin-macros
next@14.2.7(react-dom@18.3.1(react@18.3.1))(react@18.3.1):
next@14.2.7(@opentelemetry/api@1.9.0)(react-dom@18.3.1(react@18.3.1))(react@18.3.1):
dependencies:
'@next/env': 14.2.7
'@swc/helpers': 0.5.5
@@ -6429,11 +6617,12 @@ snapshots:
'@next/swc-win32-arm64-msvc': 14.2.7
'@next/swc-win32-ia32-msvc': 14.2.7
'@next/swc-win32-x64-msvc': 14.2.7
'@opentelemetry/api': 1.9.0
transitivePeerDependencies:
- '@babel/core'
- babel-plugin-macros
next@15.2.1(react-dom@18.3.1(react@18.3.1))(react@18.3.1):
next@15.2.1(@opentelemetry/api@1.9.0)(react-dom@18.3.1(react@18.3.1))(react@18.3.1):
dependencies:
'@next/env': 15.2.1
'@swc/counter': 0.1.3
@@ -6453,6 +6642,7 @@ snapshots:
'@next/swc-linux-x64-musl': 15.2.1
'@next/swc-win32-arm64-msvc': 15.2.1
'@next/swc-win32-x64-msvc': 15.2.1
'@opentelemetry/api': 1.9.0
sharp: 0.33.5
transitivePeerDependencies:
- '@babel/core'
@@ -6474,6 +6664,15 @@ snapshots:
object-hash@3.0.0: {}
oniguruma-parser@0.5.4: {}
oniguruma-to-es@4.1.0:
dependencies:
emoji-regex-xs: 1.0.0
oniguruma-parser: 0.5.4
regex: 6.0.1
regex-recursion: 6.0.2
p-limit@2.3.0:
dependencies:
p-try: 2.2.0
@@ -6592,6 +6791,8 @@ snapshots:
property-information@6.5.0: {}
property-information@7.0.0: {}
proto-list@1.2.4: {}
punycode@2.3.1: {}
@@ -6642,6 +6843,16 @@ snapshots:
dependencies:
picomatch: 2.3.1
regex-recursion@6.0.2:
dependencies:
regex-utilities: 2.3.0
regex-utilities@2.3.0: {}
regex@6.0.1:
dependencies:
regex-utilities: 2.3.0
rehype-slug@6.0.0:
dependencies:
'@types/hast': 3.0.4
@@ -6790,6 +7001,17 @@ snapshots:
vscode-oniguruma: 1.7.0
vscode-textmate: 8.0.0
shiki@3.2.1:
dependencies:
'@shikijs/core': 3.2.1
'@shikijs/engine-javascript': 3.2.1
'@shikijs/engine-oniguruma': 3.2.1
'@shikijs/langs': 3.2.1
'@shikijs/themes': 3.2.1
'@shikijs/types': 3.2.1
'@shikijs/vscode-textmate': 10.0.2
'@types/hast': 3.0.4
signal-exit@4.1.0: {}
simple-swizzle@0.2.2:
@@ -6960,6 +7182,16 @@ snapshots:
tslib@2.8.1: {}
twoslash-protocol@0.3.1: {}
twoslash@0.3.1(typescript@5.4.5):
dependencies:
'@typescript/vfs': 1.6.1(typescript@5.4.5)
twoslash-protocol: 0.3.1
typescript: 5.4.5
transitivePeerDependencies:
- supports-color
typedoc@0.25.13(typescript@5.4.5):
dependencies:
lunr: 2.3.9
@@ -7006,6 +7238,10 @@ snapshots:
dependencies:
'@types/unist': 2.0.10
unist-util-position@5.0.0:
dependencies:
'@types/unist': 3.0.2
unist-util-remove-position@4.0.2:
dependencies:
'@types/unist': 2.0.10
@@ -7088,6 +7324,11 @@ snapshots:
unist-util-stringify-position: 3.0.3
vfile-message: 3.1.4
vfile@6.0.3:
dependencies:
'@types/unist': 3.0.2
vfile-message: 4.0.2
vscode-oniguruma@1.7.0: {}
vscode-textmate@5.2.0: {}

View File

@@ -238,7 +238,7 @@ export class RawCoMapView<
get<K extends keyof Shape & string>(key: K): Shape[K] | undefined {
const entry = this.getRaw(key);
if (entry === undefined) {
if (entry?.change === undefined) {
return undefined;
}

View File

@@ -122,7 +122,8 @@ export class RawGroup<
if (!roleInfo && accountID !== "everyone") {
const everyoneRole = this.get("everyone");
if (everyoneRole) return { role: everyoneRole, via: undefined };
if (everyoneRole && everyoneRole !== "revoked")
return { role: everyoneRole, via: undefined };
}
return roleInfo;

View File

@@ -5,6 +5,7 @@ import { RawCoMap } from "../coValues/coMap.js";
import { RawCoStream } from "../coValues/coStream.js";
import { RawBinaryCoStream } from "../coValues/coStream.js";
import { WasmCrypto } from "../crypto/WasmCrypto.js";
import { RawAccountID } from "../exports.js";
import { LocalNode } from "../localNode.js";
import {
createThreeConnectedNodes,
@@ -915,117 +916,215 @@ describe("extend with role mapping", () => {
expect(mapOnNode2.get("test")).toEqual("Written from the admin");
});
});
test("roleOf should prioritize explicit account role over everyone role in same group", async () => {
const { node1, node2 } = await createTwoConnectedNodes("server", "server");
const group = node1.node.createGroup();
const account2 = await loadCoValueOrFail(node1.node, node2.accountID);
describe("roleOf", () => {
test("returns direct role assignments", () => {
const node = new LocalNode(...randomAnonymousAccountAndSessionID(), Crypto);
const group = node.createGroup();
const account = new LocalNode(
...randomAnonymousAccountAndSessionID(),
Crypto,
).account;
// Add both everyone and specific account
group.addMember("everyone", "reader");
group.addMember(account2, "writer");
group.addMember(account, "writer");
expect(group.roleOf(account.id as RawAccountID)).toEqual("writer");
});
// Should return the explicit role, not everyone's role
expect(group.roleOf(node2.accountID)).toEqual("writer");
test("returns undefined for non-members", () => {
const node = new LocalNode(...randomAnonymousAccountAndSessionID(), Crypto);
const group = node.createGroup();
const account = new LocalNode(
...randomAnonymousAccountAndSessionID(),
Crypto,
).account;
// Change everyone's role
group.addMember("everyone", "writer");
expect(group.roleOf(account.id as RawAccountID)).toEqual(undefined);
});
// Should still return the explicit role
expect(group.roleOf(node2.accountID)).toEqual("writer");
});
test("roleOf should prioritize inherited everyone role over explicit account role", async () => {
const { node1, node2 } = await createTwoConnectedNodes("server", "server");
const parentGroup = node1.node.createGroup();
const childGroup = node1.node.createGroup();
const account2 = await loadCoValueOrFail(node1.node, node2.accountID);
// Set up inheritance
childGroup.extend(parentGroup);
// Add everyone to parent and account to child
parentGroup.addMember("everyone", "writer");
childGroup.addMember(account2, "reader");
// Should return the explicit role from child, not inherited everyone role
expect(childGroup.roleOf(node2.accountID)).toEqual("writer");
});
test("roleOf should use everyone role when no explicit role exists", async () => {
const { node1, node2 } = await createTwoConnectedNodes("server", "server");
const group = node1.node.createGroup();
// Add only everyone role
group.addMember("everyone", "reader");
// Should return everyone's role when no explicit role exists
expect(group.roleOf(node2.accountID)).toEqual("reader");
});
test("roleOf should inherit everyone role from parent when no explicit roles exist", async () => {
const { node1, node2 } = await createTwoConnectedNodes("server", "server");
const parentGroup = node1.node.createGroup();
const childGroup = node1.node.createGroup();
// Set up inheritance
childGroup.extend(parentGroup);
// Add everyone to parent only
parentGroup.addMember("everyone", "reader");
// Should inherit everyone's role from parent
expect(childGroup.roleOf(node2.accountID)).toEqual("reader");
});
test("roleOf should handle everyone role inheritance through multiple levels", async () => {
const { node1, node2 } = await createTwoConnectedNodes("server", "server");
const grandParentGroup = node1.node.createGroup();
const parentGroup = node1.node.createGroup();
const childGroup = node1.node.createGroup();
const childGroupOnNode2 = await loadCoValueOrFail(node2.node, childGroup.id);
const account2 = await loadCoValueOrFail(node1.node, node2.accountID);
// Set up inheritance chain
parentGroup.extend(grandParentGroup);
childGroup.extend(parentGroup);
// Add everyone to grandparent
grandParentGroup.addMember("everyone", "writer");
// Should inherit everyone's role from grandparent
expect(childGroup.roleOf(node2.accountID)).toEqual("writer");
// Add explicit role in parent
parentGroup.addMember(account2, "reader");
// Should use parent's explicit role instead of grandparent's everyone role
expect(childGroup.roleOf(node2.accountID)).toEqual("writer");
// Add explicit role in child
childGroup.addMember(account2, "admin");
await childGroup.core.waitForSync();
// Should use child's explicit role
expect(childGroup.roleOf(node2.accountID)).toEqual("admin");
// Remove child's explicit role
await childGroupOnNode2.removeMember(account2);
await childGroupOnNode2.core.waitForSync();
// Should fall back to parent's explicit role
expect(childGroup.roleOf(node2.accountID)).toEqual("writer");
// Remove parent's explicit role
await parentGroup.removeMember(account2);
await childGroup.core.waitForSync();
// Should fall back to grandparent's everyone role
expect(childGroup.roleOf(node2.accountID)).toEqual("writer");
test("revoked roles return undefined", () => {
const node = new LocalNode(...randomAnonymousAccountAndSessionID(), Crypto);
const group = node.createGroup();
const account = new LocalNode(
...randomAnonymousAccountAndSessionID(),
Crypto,
).account;
group.addMember(account, "writer");
group.removeMemberInternal(account);
expect(group.roleOf(account.id as RawAccountID)).toEqual(undefined);
});
test("everyone role applies to all accounts", () => {
const node = new LocalNode(...randomAnonymousAccountAndSessionID(), Crypto);
const group = node.createGroup();
const account = new LocalNode(
...randomAnonymousAccountAndSessionID(),
Crypto,
).account;
group.addMemberInternal("everyone", "reader");
expect(group.roleOf(account.id as RawAccountID)).toEqual("reader");
});
test("account role overrides everyone role", () => {
const node = new LocalNode(...randomAnonymousAccountAndSessionID(), Crypto);
const group = node.createGroup();
const account = new LocalNode(
...randomAnonymousAccountAndSessionID(),
Crypto,
).account;
group.addMemberInternal("everyone", "writer");
group.addMember(account, "reader");
expect(group.roleOf(account.id as RawAccountID)).toEqual("reader");
});
test("Revoking access on everyone role should not affect existing members", () => {
const node = new LocalNode(...randomAnonymousAccountAndSessionID(), Crypto);
const group = node.createGroup();
const account = new LocalNode(
...randomAnonymousAccountAndSessionID(),
Crypto,
).account;
group.addMemberInternal("everyone", "reader");
group.addMember(account, "writer");
group.removeMemberInternal("everyone");
expect(group.roleOf(account.id as RawAccountID)).toEqual("writer");
expect(group.roleOf("123" as RawAccountID)).toEqual(undefined);
});
test("Everyone role is inherited following the most permissive algorithm", () => {
const node = new LocalNode(...randomAnonymousAccountAndSessionID(), Crypto);
const group = node.createGroup();
const account = new LocalNode(
...randomAnonymousAccountAndSessionID(),
Crypto,
).account;
const parentGroup = node.createGroup();
parentGroup.addMemberInternal("everyone", "writer");
group.extend(parentGroup);
group.addMember(account, "reader");
expect(group.roleOf(account.id as RawAccountID)).toEqual("writer");
});
test("roleOf should prioritize explicit account role over everyone role in same group", async () => {
const { node1, node2 } = await createTwoConnectedNodes("server", "server");
const group = node1.node.createGroup();
const account2 = await loadCoValueOrFail(node1.node, node2.accountID);
// Add both everyone and specific account
group.addMember("everyone", "reader");
group.addMember(account2, "writer");
// Should return the explicit role, not everyone's role
expect(group.roleOf(node2.accountID)).toEqual("writer");
// Change everyone's role
group.addMember("everyone", "writer");
// Should still return the explicit role
expect(group.roleOf(node2.accountID)).toEqual("writer");
});
test("roleOf should prioritize inherited everyone role over explicit account role", async () => {
const { node1, node2 } = await createTwoConnectedNodes("server", "server");
const parentGroup = node1.node.createGroup();
const childGroup = node1.node.createGroup();
const account2 = await loadCoValueOrFail(node1.node, node2.accountID);
// Set up inheritance
childGroup.extend(parentGroup);
// Add everyone to parent and account to child
parentGroup.addMember("everyone", "writer");
childGroup.addMember(account2, "reader");
// Should return the explicit role from child, not inherited everyone role
expect(childGroup.roleOf(node2.accountID)).toEqual("writer");
});
test("roleOf should use everyone role when no explicit role exists", async () => {
const { node1, node2 } = await createTwoConnectedNodes("server", "server");
const group = node1.node.createGroup();
// Add only everyone role
group.addMember("everyone", "reader");
// Should return everyone's role when no explicit role exists
expect(group.roleOf(node2.accountID)).toEqual("reader");
});
test("roleOf should inherit everyone role from parent when no explicit roles exist", async () => {
const { node1, node2 } = await createTwoConnectedNodes("server", "server");
const parentGroup = node1.node.createGroup();
const childGroup = node1.node.createGroup();
// Set up inheritance
childGroup.extend(parentGroup);
// Add everyone to parent only
parentGroup.addMember("everyone", "reader");
// Should inherit everyone's role from parent
expect(childGroup.roleOf(node2.accountID)).toEqual("reader");
});
test("roleOf should handle everyone role inheritance through multiple levels", async () => {
const { node1, node2 } = await createTwoConnectedNodes("server", "server");
const grandParentGroup = node1.node.createGroup();
const parentGroup = node1.node.createGroup();
const childGroup = node1.node.createGroup();
const childGroupOnNode2 = await loadCoValueOrFail(
node2.node,
childGroup.id,
);
const account2 = await loadCoValueOrFail(node1.node, node2.accountID);
// Set up inheritance chain
parentGroup.extend(grandParentGroup);
childGroup.extend(parentGroup);
// Add everyone to grandparent
grandParentGroup.addMember("everyone", "writer");
// Should inherit everyone's role from grandparent
expect(childGroup.roleOf(node2.accountID)).toEqual("writer");
// Add explicit role in parent
parentGroup.addMember(account2, "reader");
// Should use parent's explicit role instead of grandparent's everyone role
expect(childGroup.roleOf(node2.accountID)).toEqual("writer");
// Add explicit role in child
childGroup.addMember(account2, "admin");
await childGroup.core.waitForSync();
// Should use child's explicit role
expect(childGroup.roleOf(node2.accountID)).toEqual("admin");
// Remove child's explicit role
await childGroupOnNode2.removeMember(account2);
await childGroupOnNode2.core.waitForSync();
// Should fall back to parent's explicit role
expect(childGroup.roleOf(node2.accountID)).toEqual("writer");
// Remove parent's explicit role
await parentGroup.removeMember(account2);
await childGroup.core.waitForSync();
// Should fall back to grandparent's everyone role
expect(childGroup.roleOf(node2.accountID)).toEqual("writer");
});
});

View File

@@ -107,7 +107,9 @@ export class JazzClerkAuth {
});
const currentAccount = await Account.getMe().ensureLoaded({
profile: {},
resolve: {
profile: true,
},
});
const username = getClerkUsername(clerkClient);

View File

@@ -81,7 +81,9 @@ describe("JazzClerkAuth", () => {
});
const me = await Account.getMe().ensureLoaded({
profile: {},
resolve: {
profile: true,
},
});
expect(me.profile.name).toBe("Guido");
});

View File

@@ -83,7 +83,9 @@ export class BrowserPasskeyAuth {
});
const currentAccount = await Account.getMe().ensureLoaded({
profile: {},
resolve: {
profile: true,
},
});
if (username.trim().length !== 0) {

View File

@@ -198,7 +198,9 @@ describe("BrowserPasskeyAuth", () => {
await auth.signUp("");
const currentAccount = await Account.getMe().ensureLoaded({
profile: {},
resolve: {
profile: true,
},
});
// 'Test Account' is the name provided during account creation (see: `jazz-tools/src/testing.ts`)
@@ -228,7 +230,9 @@ describe("BrowserPasskeyAuth", () => {
await auth.signUp("testuser");
const currentAccount = await Account.getMe().ensureLoaded({
profile: {},
resolve: {
profile: true,
},
});
expect(currentAccount.profile.name).toEqual("testuser");

View File

@@ -75,7 +75,7 @@ describe("startWorker integration", () => {
await map.waitForSync();
const mapOnWorker2 = await TestMap.load(map.id, worker2.worker, {});
const mapOnWorker2 = await TestMap.load(map.id, { loadAs: worker2.worker });
expect(mapOnWorker2?.value).toBe("test");
@@ -113,7 +113,9 @@ describe("startWorker integration", () => {
const worker1 = await setup(CustomAccount);
const { root } = await worker1.worker.ensureLoaded({ root: {} });
const { root } = await worker1.worker.ensureLoaded({
resolve: { root: true },
});
expect(root.value).toBe("test");
@@ -126,7 +128,9 @@ describe("startWorker integration", () => {
AccountSchema: CustomAccount,
});
const { root: root2 } = await worker2.worker.ensureLoaded({ root: {} });
const { root: root2 } = await worker2.worker.ensureLoaded({
resolve: { root: true },
});
expect(root2.value).toBe("test");
@@ -150,7 +154,7 @@ describe("startWorker integration", () => {
const worker2 = await setupWorker(worker1.syncServer);
const mapOnWorker2 = await TestMap.load(map.id, worker2.worker, {});
const mapOnWorker2 = await TestMap.load(map.id, { loadAs: worker2.worker });
expect(mapOnWorker2?.value).toBe("test");
@@ -185,7 +189,7 @@ describe("startWorker integration", () => {
const resultId = await sender.sendMessage(map);
const result = await TestMap.load(resultId, worker2.worker, {});
const result = await TestMap.load(resultId, { loadAs: worker2.worker });
expect(result?.value).toEqual("Hello! Responded from the inbox");
@@ -231,8 +235,10 @@ describe("startWorker integration", () => {
await map2.waitForSync();
// Verify both old and new values are synced
const mapOnWorker2 = await TestMap.load(map.id, worker2.worker, {});
const map2OnWorker2 = await TestMap.load(map2.id, worker2.worker, {});
const mapOnWorker2 = await TestMap.load(map.id, { loadAs: worker2.worker });
const map2OnWorker2 = await TestMap.load(map2.id, {
loadAs: worker2.worker,
});
expect(mapOnWorker2?.value).toBe("initial value");
expect(map2OnWorker2?.value).toBe("created while offline");

View File

@@ -10,12 +10,13 @@ import {
AnonymousJazzAgent,
CoValue,
CoValueClass,
DeeplyLoaded,
DepthsIn,
ID,
InboxSender,
JazzContextManager,
JazzContextType,
RefsToResolve,
RefsToResolveStrict,
Resolved,
createCoValueObservable,
} from "jazz-tools";
import {
@@ -80,12 +81,11 @@ export function useIsAuthenticated() {
);
}
function useCoValueObservable<V extends CoValue, D>() {
const [initialValue] = React.useState(() =>
createCoValueObservable<V, D>({
syncResolution: true,
}),
);
function useCoValueObservable<
V extends CoValue,
const R extends RefsToResolve<V>,
>() {
const [initialValue] = React.useState(() => createCoValueObservable<V, R>());
const ref = useRef(initialValue);
return {
@@ -96,26 +96,25 @@ function useCoValueObservable<V extends CoValue, D>() {
return ref.current;
},
reset() {
ref.current = createCoValueObservable<V, D>({
syncResolution: true,
});
ref.current = createCoValueObservable<V, R>();
},
};
}
export function useCoState<V extends CoValue, D>(
export function useCoState<
V extends CoValue,
const R extends RefsToResolve<V> = true,
>(
// eslint-disable-next-line @typescript-eslint/no-explicit-any
Schema: CoValueClass<V>,
id: ID<CoValue> | undefined,
depth: D & DepthsIn<V> = [] as D & DepthsIn<V>,
): DeeplyLoaded<V, D> | undefined | null {
options?: { resolve?: RefsToResolveStrict<V, R> },
): Resolved<V, R> | undefined | null {
const contextManager = useJazzContextManager();
const observable = useCoValueObservable<V, D>();
const observable = useCoValueObservable<V, R>();
const value = React.useSyncExternalStore<
DeeplyLoaded<V, D> | undefined | null
>(
const value = React.useSyncExternalStore<Resolved<V, R> | undefined | null>(
React.useCallback(
(callback) => {
observable.reset();
@@ -127,12 +126,20 @@ export function useCoState<V extends CoValue, D>(
// up to date with the data when logging in and out.
return subscribeToContextManager(contextManager, () => {
const agent = getCurrentAccountFromContextManager(contextManager);
observable.reset();
return observable
.getCurrentObservable()
.subscribe(Schema, id, agent, depth, callback, callback);
return observable.getCurrentObservable().subscribe(
Schema,
id,
{
loadAs: agent,
resolve: options?.resolve,
onUnauthorized: callback,
onUnavailable: callback,
syncResolution: true,
},
callback,
);
});
},
[Schema, id, contextManager],
@@ -148,12 +155,18 @@ function useAccount<A extends RegisteredAccount>(): {
me: A;
logOut: () => void;
};
function useAccount<A extends RegisteredAccount, D extends DepthsIn<A>>(
depth: D,
): { me: DeeplyLoaded<A, D> | undefined | null; logOut: () => void };
function useAccount<A extends RegisteredAccount, D extends DepthsIn<A>>(
depth?: D,
): { me: A | DeeplyLoaded<A, D> | undefined | null; logOut: () => void } {
function useAccount<
A extends RegisteredAccount,
R extends RefsToResolve<A>,
>(options?: {
resolve?: RefsToResolveStrict<A, R>;
}): { me: Resolved<A, R> | undefined | null; logOut: () => void };
function useAccount<
A extends RegisteredAccount,
R extends RefsToResolve<A>,
>(options?: {
resolve?: RefsToResolveStrict<A, R>;
}): { me: A | Resolved<A, R> | undefined | null; logOut: () => void } {
const context = useJazzContext<A>();
const contextManager = useJazzContextManager<A>();
@@ -163,9 +176,9 @@ function useAccount<A extends RegisteredAccount, D extends DepthsIn<A>>(
);
}
const observable = useCoValueObservable<A, D>();
const observable = useCoValueObservable<A, R>();
const me = React.useSyncExternalStore<DeeplyLoaded<A, D> | undefined | null>(
const me = React.useSyncExternalStore<Resolved<A, R> | undefined | null>(
React.useCallback(
(callback) => {
return subscribeToContextManager(contextManager, () => {
@@ -181,16 +194,18 @@ function useAccount<A extends RegisteredAccount, D extends DepthsIn<A>>(
const Schema = agent.constructor as CoValueClass<A>;
return observable
.getCurrentObservable()
.subscribe(
Schema,
agent.id,
agent,
depth ?? ([] as D),
callback,
callback,
);
return observable.getCurrentObservable().subscribe(
Schema,
(agent as A).id,
{
loadAs: agent,
resolve: options?.resolve,
onUnauthorized: callback,
onUnavailable: callback,
syncResolution: true,
},
callback,
);
});
},
[contextManager],
@@ -200,28 +215,32 @@ function useAccount<A extends RegisteredAccount, D extends DepthsIn<A>>(
);
return {
me: depth === undefined ? me || context.me : me,
logOut: context.logOut,
me: options?.resolve === undefined ? me || context.me : me,
logOut: contextManager.logOut,
};
}
function useAccountOrGuest<A extends RegisteredAccount>(): {
me: A | AnonymousJazzAgent;
};
function useAccountOrGuest<A extends RegisteredAccount, D extends DepthsIn<A>>(
depth: D,
): { me: DeeplyLoaded<A, D> | undefined | null | AnonymousJazzAgent };
function useAccountOrGuest<A extends RegisteredAccount, D extends DepthsIn<A>>(
depth?: D,
): {
me: A | DeeplyLoaded<A, D> | undefined | null | AnonymousJazzAgent;
function useAccountOrGuest<
A extends RegisteredAccount,
R extends RefsToResolve<A>,
>(options?: { resolve?: RefsToResolveStrict<A, R> }): {
me: Resolved<A, R> | undefined | null | AnonymousJazzAgent;
};
function useAccountOrGuest<
A extends RegisteredAccount,
R extends RefsToResolve<A>,
>(options?: { resolve?: RefsToResolveStrict<A, R> }): {
me: A | Resolved<A, R> | undefined | null | AnonymousJazzAgent;
} {
const context = useJazzContext<A>();
const contextManager = useJazzContextManager<A>();
const observable = useCoValueObservable<A, D>();
const observable = useCoValueObservable<A, R>();
const me = React.useSyncExternalStore<DeeplyLoaded<A, D> | undefined | null>(
const me = React.useSyncExternalStore<Resolved<A, R> | undefined | null>(
React.useCallback(
(callback) => {
return subscribeToContextManager(contextManager, () => {
@@ -235,16 +254,18 @@ function useAccountOrGuest<A extends RegisteredAccount, D extends DepthsIn<A>>(
const Schema = agent.constructor as CoValueClass<A>;
return observable
.getCurrentObservable()
.subscribe(
Schema,
agent.id,
agent,
depth ?? ([] as D),
callback,
callback,
);
return observable.getCurrentObservable().subscribe(
Schema,
(agent as A).id,
{
loadAs: agent,
resolve: options?.resolve,
onUnauthorized: callback,
onUnavailable: callback,
syncResolution: true,
},
callback,
);
});
},
[contextManager],
@@ -255,7 +276,7 @@ function useAccountOrGuest<A extends RegisteredAccount, D extends DepthsIn<A>>(
if ("me" in context) {
return {
me: depth === undefined ? me || context.me : me,
me: options?.resolve === undefined ? me || context.me : me,
};
} else {
return { me: context.guest };

View File

@@ -1,6 +1,6 @@
// @vitest-environment happy-dom
import { Account, CoMap, DepthsIn, co } from "jazz-tools";
import { Account, CoMap, RefsToResolve, Resolved, co } from "jazz-tools";
import { beforeEach, describe, expect, it } from "vitest";
import { useAccount, useJazzContextManager } from "../hooks.js";
import { useIsAuthenticated } from "../index.js";
@@ -41,8 +41,10 @@ describe("useAccount", () => {
const { result } = renderHook(
() =>
useAccount<AccountSchema, DepthsIn<AccountSchema>>({
root: {},
useAccount<AccountSchema, RefsToResolve<{ root: true }>>({
resolve: {
root: true,
},
}),
{
account,

View File

@@ -1,6 +1,6 @@
// @vitest-environment happy-dom
import { Account, CoMap, DepthsIn, co } from "jazz-tools";
import { Account, CoMap, RefsToResolve, co } from "jazz-tools";
import { describe, expect, it } from "vitest";
import { useAccountOrGuest } from "../index.js";
import { createJazzTestAccount, createJazzTestGuest } from "../testing.js";
@@ -46,8 +46,10 @@ describe("useAccountOrGuest", () => {
const { result } = renderHook(
() =>
useAccountOrGuest<AccountSchema, DepthsIn<AccountSchema>>({
root: {},
useAccountOrGuest<AccountSchema, RefsToResolve<{ root: true }>>({
resolve: {
root: true,
},
}),
{
account,
@@ -64,7 +66,9 @@ describe("useAccountOrGuest", () => {
const { result } = renderHook(
() =>
useAccountOrGuest({
root: {},
resolve: {
root: true,
},
}),
{
account,

View File

@@ -1,7 +1,7 @@
// @vitest-environment happy-dom
import { cojsonInternals } from "cojson";
import { CoMap, CoValue, ID, co } from "jazz-tools";
import { CoMap, CoValue, Group, ID, co } from "jazz-tools";
import { beforeEach, describe, expect, expectTypeOf, it } from "vitest";
import { useCoState } from "../index.js";
import { createJazzTestAccount, setupJazzTestSync } from "../testing.js";
@@ -91,7 +91,9 @@ describe("useCoState", () => {
const { result } = renderHook(
() =>
useCoState(TestMap, map.id, {
nested: {},
resolve: {
nested: true,
},
}),
{
account,
@@ -145,7 +147,7 @@ describe("useCoState", () => {
});
const { result } = renderHook(
() => useCoState(TestMap, (map.id + "123") as any, {}),
() => useCoState(TestMap, (map.id + "123") as any),
{
account,
},
@@ -158,6 +160,168 @@ describe("useCoState", () => {
});
});
it("should return null if the coValue is not accessible", async () => {
class TestMap extends CoMap {
value = co.string;
}
const someoneElse = await createJazzTestAccount({
isCurrentActiveAccount: true,
});
const map = TestMap.create(
{
value: "123",
},
someoneElse,
);
const account = await createJazzTestAccount({
isCurrentActiveAccount: true,
});
const { result } = renderHook(() => useCoState(TestMap, map.id), {
account,
});
expect(result.current).toBeUndefined();
await waitFor(() => {
expect(result.current).toBeNull();
});
});
it("should not return null if the coValue is shared with everyone", async () => {
class TestMap extends CoMap {
value = co.string;
}
const someoneElse = await createJazzTestAccount({
isCurrentActiveAccount: true,
});
const group = Group.create(someoneElse);
group.addMember("everyone", "reader");
const map = TestMap.create(
{
value: "123",
},
group,
);
const account = await createJazzTestAccount({
isCurrentActiveAccount: true,
});
const { result } = renderHook(() => useCoState(TestMap, map.id), {
account,
});
expect(result.current).toBeUndefined();
await waitFor(() => {
expect(result.current?.value).toBe("123");
});
});
it("should return a value when the coValue becomes accessible", async () => {
class TestMap extends CoMap {
value = co.string;
}
const someoneElse = await createJazzTestAccount({
isCurrentActiveAccount: true,
});
const group = Group.create(someoneElse);
const map = TestMap.create(
{
value: "123",
},
group,
);
const account = await createJazzTestAccount({
isCurrentActiveAccount: true,
});
const { result } = renderHook(() => useCoState(TestMap, map.id), {
account,
});
expect(result.current).toBeUndefined();
await waitFor(() => {
expect(result.current).toBeNull();
});
group.addMember("everyone", "reader");
await waitFor(() => {
expect(result.current).not.toBeNull();
expect(result.current?.value).toBe("123");
});
});
it("should update when an inner coValue is updated", async () => {
class TestMap extends CoMap {
value = co.string;
nested = co.optional.ref(TestMap);
}
const someoneElse = await createJazzTestAccount({
isCurrentActiveAccount: true,
});
const everyone = Group.create(someoneElse);
everyone.addMember("everyone", "reader");
const group = Group.create(someoneElse);
const map = TestMap.create(
{
value: "123",
nested: TestMap.create(
{
value: "456",
},
group,
),
},
everyone,
);
const account = await createJazzTestAccount({
isCurrentActiveAccount: true,
});
const { result } = renderHook(
() =>
useCoState(TestMap, map.id, {
resolve: {
nested: true,
},
}),
{
account,
},
);
expect(result.current).toBeUndefined();
await waitFor(() => {
expect(result.current).not.toBeUndefined();
});
expect(result.current?.nested).toBeUndefined();
group.addMember("everyone", "reader");
await waitFor(() => {
expect(result.current?.nested?.value).toBe("456");
});
});
it("should return the same type as Schema", () => {
class TestMap extends CoMap {
value = co.string;
@@ -168,7 +332,7 @@ describe("useCoState", () => {
});
const { result } = renderHook(() =>
useCoState(TestMap, map.id as ID<CoValue>, []),
useCoState(TestMap, map.id as ID<CoValue>),
);
expectTypeOf(result).toEqualTypeOf<{
current: TestMap | null | undefined;
@@ -185,7 +349,7 @@ describe("useCoState", () => {
});
const { result, rerender } = renderHook(
(props) => useCoState(TestMap, props.id, []),
(props) => useCoState(TestMap, props.id),
{
initialProps: { id: map.id } as { id: ID<CoValue> | undefined },
},

View File

@@ -45,7 +45,9 @@ describe("useInboxSender", () => {
expect(incoming.value).toEqual("hello");
const response = await promise;
const responseMap = await TestMap.load(response, account, {});
const responseMap = await TestMap.load(response, {
loadAs: account,
});
expect(responseMap!.value).toEqual("got it");
});

View File

@@ -46,7 +46,9 @@ describe("useAcceptInvite", () => {
expect(acceptedId).toBeDefined();
});
const accepted = await TestMap.load(acceptedId!, account, {});
const accepted = await TestMap.load(acceptedId!, {
loadAs: account,
});
expect(accepted?.value).toEqual("hello");
});

View File

@@ -4,16 +4,17 @@ import type {
AuthSecretStorage,
CoValue,
CoValueClass,
DeeplyLoaded,
DepthsIn,
ID,
JazzAuthContext,
JazzContextType,
JazzGuestContext
JazzGuestContext,
RefsToResolve,
Resolved
} from 'jazz-tools';
import { Account, subscribeToCoValue } from 'jazz-tools';
import { getContext, untrack } from 'svelte';
import Provider from './Provider.svelte';
import type { RefsToResolveStrict } from 'jazz-tools';
export { Provider as JazzProvider };
@@ -71,21 +72,12 @@ declare module "jazz-tools" {
}
}
export function useAccount(): { me: RegisteredAccount; logOut: () => void };
export function useAccount<D extends DepthsIn<RegisteredAccount>>(
depth: D
): { me: DeeplyLoaded<RegisteredAccount, D> | undefined | null; logOut: () => void };
/**
* Use the current account with a optional depth.
* @param depth - The depth.
* @returns The current account.
*/
export function useAccount<D extends DepthsIn<RegisteredAccount>>(
depth?: D
): {
me: RegisteredAccount | DeeplyLoaded<RegisteredAccount, D> | undefined | null;
logOut: () => void;
} {
export function useAccount<const R extends RefsToResolve<RegisteredAccount>>(
options?: { resolve?: RefsToResolveStrict<RegisteredAccount, R> }
): { me: Resolved<RegisteredAccount, R> | undefined | null; logOut: () => void };
export function useAccount<const R extends RefsToResolve<RegisteredAccount>>(
options?: { resolve?: RefsToResolveStrict<RegisteredAccount, R> }
): { me: RegisteredAccount | Resolved<RegisteredAccount, R> | undefined | null; logOut: () => void } {
const ctx = getJazzContext<RegisteredAccount>();
if (!ctx?.current) {
throw new Error('useAccount must be used within a JazzProvider');
@@ -97,7 +89,7 @@ export function useAccount<D extends DepthsIn<RegisteredAccount>>(
}
// If no depth is specified, return the context's me directly
if (depth === undefined) {
if (options?.resolve === undefined) {
return {
get me() {
return (ctx.current as JazzAuthContext<RegisteredAccount>).me;
@@ -109,10 +101,10 @@ export function useAccount<D extends DepthsIn<RegisteredAccount>>(
}
// If depth is specified, use useCoState to get the deeply loaded version
const me = useCoState<RegisteredAccount, D>(
const me = useCoState<RegisteredAccount, R>(
ctx.current.me.constructor as CoValueClass<RegisteredAccount>,
(ctx.current as JazzAuthContext<RegisteredAccount>).me.id,
depth
options
);
return {
@@ -126,24 +118,12 @@ export function useAccount<D extends DepthsIn<RegisteredAccount>>(
}
export function useAccountOrGuest(): { me: RegisteredAccount | AnonymousJazzAgent };
export function useAccountOrGuest<D extends DepthsIn<RegisteredAccount>>(
depth: D
): { me: DeeplyLoaded<RegisteredAccount, D> | undefined | null | AnonymousJazzAgent };
/**
* Use the current account or guest with a optional depth.
* @param depth - The depth.
* @returns The current account or guest.
*/
export function useAccountOrGuest<D extends DepthsIn<RegisteredAccount>>(
depth?: D
): {
me:
| RegisteredAccount
| DeeplyLoaded<RegisteredAccount, D>
| undefined
| null
| AnonymousJazzAgent;
} {
export function useAccountOrGuest<R extends RefsToResolve<RegisteredAccount>>(
options?: { resolve?: RefsToResolveStrict<RegisteredAccount, R> }
): { me: Resolved<RegisteredAccount, R> | undefined | null| AnonymousJazzAgent };
export function useAccountOrGuest<R extends RefsToResolve<RegisteredAccount>>(
options?: { resolve?: RefsToResolveStrict<RegisteredAccount, R> }
): { me: RegisteredAccount | Resolved<RegisteredAccount, R> | undefined | null| AnonymousJazzAgent } {
const ctx = getJazzContext<RegisteredAccount>();
if (!ctx?.current) {
@@ -152,17 +132,17 @@ export function useAccountOrGuest<D extends DepthsIn<RegisteredAccount>>(
const contextMe = 'me' in ctx.current ? ctx.current.me : undefined;
const me = useCoState<RegisteredAccount, D>(
const me = useCoState<RegisteredAccount, R>(
contextMe?.constructor as CoValueClass<RegisteredAccount>,
contextMe?.id,
depth
options
);
// If the context has a me, return the account.
if ('me' in ctx.current) {
return {
get me() {
return depth === undefined
return options?.resolve === undefined
? me.current || (ctx.current as JazzAuthContext<RegisteredAccount>)?.me
: me.current;
}
@@ -178,24 +158,17 @@ export function useAccountOrGuest<D extends DepthsIn<RegisteredAccount>>(
}
}
/**
* Use a CoValue with a optional depth.
* @param Schema - The CoValue schema.
* @param id - The CoValue id.
* @param depth - The depth.
* @returns The CoValue.
*/
export function useCoState<V extends CoValue, D extends DepthsIn<V> = []>(
export function useCoState<V extends CoValue, R extends RefsToResolve<V>>(
Schema: CoValueClass<V>,
id: ID<CoValue> | undefined,
depth: D = [] as D
options?: { resolve?: RefsToResolveStrict<V, R> }
): {
current?: DeeplyLoaded<V, D> | null;
current: Resolved<V, R> | undefined | null;
} {
const ctx = getJazzContext<RegisteredAccount>();
// Create state and a stable observable
let state = $state.raw<DeeplyLoaded<V, D> | undefined | null>(undefined);
let state = $state.raw<Resolved<V, R> | undefined | null>(undefined);
// Effect to handle subscription
$effect(() => {
@@ -205,20 +178,27 @@ export function useCoState<V extends CoValue, D extends DepthsIn<V> = []>(
// Return early if no context or id, effectively cleaning up any previous subscription
if (!ctx?.current || !id) return;
const agent = "me" in ctx.current ? ctx.current.me : ctx.current.guest;
// Setup subscription with current values
return subscribeToCoValue(
return subscribeToCoValue<V, R>(
Schema,
id,
'me' in ctx.current ? ctx.current.me : ctx.current.guest,
depth,
{
resolve: options?.resolve,
loadAs: agent,
onUnavailable: () => {
state = null;
},
onUnauthorized: () => {
state = null;
},
syncResolution: true,
},
(value) => {
// Get current value from our stable observable
state = value;
},
() => {
state = null;
},
true
);
});

View File

@@ -15,8 +15,8 @@ function setup<T extends CoValue>(options: {
context: createJazzTestContext({ account: options.account }),
props: {
invitedObjectSchema: options.invitedObjectSchema,
onAccept: (id: ID<T>) => {
result.current = id;
onAccept: (id: ID<CoValue>) => {
result.current = id as ID<T>;
},
},
});
@@ -54,7 +54,9 @@ describe("useAcceptInvite", () => {
expect(result.current).toBeDefined();
});
const accepted = await TestMap.load(result.current!, account, {});
const accepted = await TestMap.load(result.current!, {
loadAs: account,
});
expect(accepted?.value).toEqual("hello");
});

View File

@@ -66,7 +66,9 @@ export class DemoAuth {
}
const currentAccount = await Account.getMe().ensureLoaded({
profile: {},
resolve: {
profile: true,
},
});
currentAccount.profile.name = username;

View File

@@ -83,7 +83,9 @@ export class PassphraseAuth {
if (name?.trim()) {
const currentAccount = await Account.getMe().ensureLoaded({
profile: {},
resolve: {
profile: true,
},
});
currentAccount.profile.name = name;

View File

@@ -20,18 +20,22 @@ import {
type CoValue,
CoValueBase,
CoValueClass,
DeeplyLoaded,
DepthsIn,
ID,
Ref,
type RefEncoded,
RefIfCoValue,
RefsToResolve,
RefsToResolveStrict,
Resolved,
type Schema,
SchemaInit,
SubscribeListenerOptions,
SubscribeRestArgs,
ensureCoValueLoaded,
inspect,
loadCoValue,
loadCoValueWithoutMe,
parseSubscribeRestArgs,
subscribeToCoValueWithoutMe,
subscribeToExistingCoValue,
subscriptionsScopes,
@@ -225,7 +229,7 @@ export class Account extends CoValueBase implements CoValue {
valueID: ID<V>,
inviteSecret: InviteSecret,
coValueClass: CoValueClass<V>,
) {
): Promise<Resolved<V, true> | null> {
if (!this.isLocalNodeOwner) {
throw new Error("Only a controlled account can accept invites");
}
@@ -235,8 +239,9 @@ export class Account extends CoValueBase implements CoValue {
inviteSecret,
);
return loadCoValue(coValueClass, valueID, this as Account, []);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
return loadCoValue(coValueClass, valueID, {
loadAs: this,
});
}
/** @private */
@@ -346,73 +351,62 @@ export class Account extends CoValueBase implements CoValue {
}
/** @category Subscription & Loading */
static load<A extends Account, Depth>(
static load<A extends Account, const R extends RefsToResolve<A> = true>(
this: CoValueClass<A>,
id: ID<A>,
depth: Depth & DepthsIn<A>,
): Promise<DeeplyLoaded<A, Depth> | undefined>;
static load<A extends Account, Depth>(
this: CoValueClass<A>,
id: ID<A>,
as: Account,
depth: Depth & DepthsIn<A>,
): Promise<DeeplyLoaded<A, Depth> | undefined>;
static load<A extends Account, Depth>(
this: CoValueClass<A>,
id: ID<A>,
asOrDepth: Account | (Depth & DepthsIn<A>),
depth?: Depth & DepthsIn<A>,
): Promise<DeeplyLoaded<A, Depth> | undefined> {
return loadCoValueWithoutMe(this, id, asOrDepth, depth);
options?: {
resolve?: RefsToResolveStrict<A, R>;
loadAs?: Account | AnonymousJazzAgent;
},
): Promise<Resolved<A, R> | null> {
return loadCoValueWithoutMe(this, id, options);
}
/** @category Subscription & Loading */
static subscribe<A extends Account, Depth>(
static subscribe<A extends Account, const R extends RefsToResolve<A> = true>(
this: CoValueClass<A>,
id: ID<A>,
depth: Depth & DepthsIn<A>,
listener: (value: DeeplyLoaded<A, Depth>) => void,
listener: (value: Resolved<A, R>, unsubscribe: () => void) => void,
): () => void;
static subscribe<A extends Account, Depth>(
static subscribe<A extends Account, const R extends RefsToResolve<A> = true>(
this: CoValueClass<A>,
id: ID<A>,
as: Account,
depth: Depth & DepthsIn<A>,
listener: (value: DeeplyLoaded<A, Depth>) => void,
options: SubscribeListenerOptions<A, R>,
listener: (value: Resolved<A, R>, unsubscribe: () => void) => void,
): () => void;
static subscribe<A extends Account, Depth>(
static subscribe<A extends Account, const R extends RefsToResolve<A>>(
this: CoValueClass<A>,
id: ID<A>,
asOrDepth: Account | (Depth & DepthsIn<A>),
depthOrListener:
| (Depth & DepthsIn<A>)
| ((value: DeeplyLoaded<A, Depth>) => void),
listener?: (value: DeeplyLoaded<A, Depth>) => void,
...args: SubscribeRestArgs<A, R>
): () => void {
return subscribeToCoValueWithoutMe<A, Depth>(
this,
id,
asOrDepth,
depthOrListener,
listener!,
);
const { options, listener } = parseSubscribeRestArgs(args);
return subscribeToCoValueWithoutMe<A, R>(this, id, options, listener);
}
/** @category Subscription & Loading */
ensureLoaded<A extends Account, Depth>(
ensureLoaded<A extends Account, const R extends RefsToResolve<A>>(
this: A,
depth: Depth & DepthsIn<A>,
): Promise<DeeplyLoaded<A, Depth>> {
return ensureCoValueLoaded(this, depth);
options: { resolve: RefsToResolveStrict<A, R> },
): Promise<Resolved<A, R>> {
return ensureCoValueLoaded(this, options);
}
/** @category Subscription & Loading */
subscribe<A extends Account, Depth>(
subscribe<A extends Account, const R extends RefsToResolve<A>>(
this: A,
depth: Depth & DepthsIn<A>,
listener: (value: DeeplyLoaded<A, Depth>) => void,
listener: (value: Resolved<A, R>, unsubscribe: () => void) => void,
): () => void;
subscribe<A extends Account, const R extends RefsToResolve<A>>(
this: A,
options: { resolve?: RefsToResolveStrict<A, R> },
listener: (value: Resolved<A, R>, unsubscribe: () => void) => void,
): () => void;
subscribe<A extends Account, const R extends RefsToResolve<A>>(
this: A,
...args: SubscribeRestArgs<A, R>
): () => void {
return subscribeToExistingCoValue(this, depth, listener);
const { options, listener } = parseSubscribeRestArgs(args);
return subscribeToExistingCoValue(this, options, listener);
}
/**

View File

@@ -10,17 +10,19 @@ import type {
SessionID,
} from "cojson";
import { MAX_RECOMMENDED_TX_SIZE, cojsonInternals } from "cojson";
import { activeAccountContext } from "../implementation/activeAccountContext.js";
import type {
AnonymousJazzAgent,
CoValue,
CoValueClass,
DeeplyLoaded,
DepthsIn,
ID,
IfCo,
RefsToResolve,
RefsToResolveStrict,
Resolved,
Schema,
SchemaFor,
SubscribeListenerOptions,
SubscribeRestArgs,
UnCo,
} from "../internal.js";
import {
@@ -31,11 +33,10 @@ import {
co,
ensureCoValueLoaded,
inspect,
isAccountInstance,
isRefEncoded,
loadCoValueWithoutMe,
parseCoValueCreateOptions,
subscribeToCoValue,
parseSubscribeRestArgs,
subscribeToCoValueWithoutMe,
subscribeToExistingCoValue,
} from "../internal.js";
@@ -327,73 +328,52 @@ export class CoFeed<Item = any> extends CoValueBase implements CoValue {
* Load a `CoFeed`
* @category Subscription & Loading
*/
static load<S extends CoFeed, Depth>(
this: CoValueClass<S>,
id: ID<S>,
depth: Depth & DepthsIn<S>,
): Promise<DeeplyLoaded<S, Depth> | undefined>;
static load<S extends CoFeed, Depth>(
this: CoValueClass<S>,
id: ID<S>,
as: Account,
depth: Depth & DepthsIn<S>,
): Promise<DeeplyLoaded<S, Depth> | undefined>;
static load<S extends CoFeed, Depth>(
this: CoValueClass<S>,
id: ID<S>,
asOrDepth: Account | (Depth & DepthsIn<S>),
depth?: Depth & DepthsIn<S>,
): Promise<DeeplyLoaded<S, Depth> | undefined> {
return loadCoValueWithoutMe(this, id, asOrDepth, depth);
static load<F extends CoFeed, const R extends RefsToResolve<F> = true>(
this: CoValueClass<F>,
id: ID<F>,
options: {
resolve?: RefsToResolveStrict<F, R>;
loadAs?: Account | AnonymousJazzAgent;
},
): Promise<Resolved<F, R> | null> {
return loadCoValueWithoutMe(this, id, options);
}
/**
* Subscribe to a `CoFeed`, when you have an ID but don't have a `CoFeed` instance yet
* @category Subscription & Loading
*/
static subscribe<S extends CoFeed, Depth>(
this: CoValueClass<S>,
id: ID<S>,
depth: Depth & DepthsIn<S>,
listener: (value: DeeplyLoaded<S, Depth>) => void,
static subscribe<F extends CoFeed, const R extends RefsToResolve<F> = true>(
this: CoValueClass<F>,
id: ID<F>,
listener: (value: Resolved<F, R>, unsubscribe: () => void) => void,
): () => void;
static subscribe<S extends CoFeed, Depth>(
this: CoValueClass<S>,
id: ID<S>,
as: Account,
depth: Depth & DepthsIn<S>,
listener: (value: DeeplyLoaded<S, Depth>) => void,
static subscribe<F extends CoFeed, const R extends RefsToResolve<F> = true>(
this: CoValueClass<F>,
id: ID<F>,
options: SubscribeListenerOptions<F, R>,
listener: (value: Resolved<F, R>, unsubscribe: () => void) => void,
): () => void;
static subscribe<S extends CoFeed, Depth>(
this: CoValueClass<S>,
id: ID<S>,
asOrDepth: Account | (Depth & DepthsIn<S>),
depthOrListener:
| (Depth & DepthsIn<S>)
| ((value: DeeplyLoaded<S, Depth>) => void),
listener?: (value: DeeplyLoaded<S, Depth>) => void,
static subscribe<F extends CoFeed, const R extends RefsToResolve<F>>(
this: CoValueClass<F>,
id: ID<F>,
...args: SubscribeRestArgs<F, R>
): () => void {
return subscribeToCoValueWithoutMe<S, Depth>(
this,
id,
asOrDepth,
depthOrListener,
listener,
);
const { options, listener } = parseSubscribeRestArgs(args);
return subscribeToCoValueWithoutMe<F, R>(this, id, options, listener);
}
/**
* Ensure a `CoFeed` is loaded to the specified depth
*
* @returns A new instance of the same CoFeed that's loaded to the specified depth,
* or undefined if it cannot be loaded that deeply
* @returns A new instance of the same CoFeed that's loaded to the specified depth
* @category Subscription & Loading
*/
ensureLoaded<S extends CoFeed, Depth>(
this: S,
depth: Depth & DepthsIn<S>,
): Promise<DeeplyLoaded<S, Depth>> {
return ensureCoValueLoaded(this, depth);
ensureLoaded<F extends CoFeed, const R extends RefsToResolve<F>>(
this: F,
options?: { resolve?: RefsToResolveStrict<F, R> },
): Promise<Resolved<F, R>> {
return ensureCoValueLoaded(this, options);
}
/**
@@ -402,12 +382,21 @@ export class CoFeed<Item = any> extends CoValueBase implements CoValue {
* No need to provide an ID or Account since they're already part of the instance.
* @category Subscription & Loading
*/
subscribe<S extends CoFeed, Depth>(
this: S,
depth: Depth & DepthsIn<S>,
listener: (value: DeeplyLoaded<S, Depth>) => void,
subscribe<F extends CoFeed, const R extends RefsToResolve<F>>(
this: F,
listener: (value: Resolved<F, R>, unsubscribe: () => void) => void,
): () => void;
subscribe<F extends CoFeed, const R extends RefsToResolve<F>>(
this: F,
options: { resolve?: RefsToResolveStrict<F, R> },
listener: (value: Resolved<F, R>, unsubscribe: () => void) => void,
): () => void;
subscribe<F extends CoFeed, const R extends RefsToResolve<F>>(
this: F,
...args: SubscribeRestArgs<F, R>
): () => void {
return subscribeToExistingCoValue(this, depth, listener);
const { options, listener } = parseSubscribeRestArgs(args);
return subscribeToExistingCoValue(this, options, listener);
}
/**
@@ -785,34 +774,10 @@ export class FileStream extends CoValueBase implements CoValue {
id: ID<FileStream>,
options?: {
allowUnfinished?: boolean;
},
): Promise<Blob | undefined>;
static async loadAsBlob(
id: ID<FileStream>,
as: Account,
options?: {
allowUnfinished?: boolean;
},
): Promise<Blob | undefined>;
static async loadAsBlob(
id: ID<FileStream>,
asOrOptions?:
| Account
| {
allowUnfinished?: boolean;
},
optionsOrUndefined?: {
allowUnfinished?: boolean;
loadAs?: Account | AnonymousJazzAgent;
},
): Promise<Blob | undefined> {
const as = isAccountInstance(asOrOptions)
? asOrOptions
: activeAccountContext.get();
const options = isAccountInstance(asOrOptions)
? optionsOrUndefined
: asOrOptions;
let stream = await this.load(id, as, []);
let stream = await this.load(id, options);
/**
* If the user hasn't requested an incomplete blob and the
@@ -820,12 +785,17 @@ export class FileStream extends CoValueBase implements CoValue {
*/
if (!options?.allowUnfinished && !stream?.isBinaryStreamEnded()) {
stream = await new Promise<FileStream>((resolve) => {
subscribeToCoValue(this, id, as, [], (value, unsubscribe) => {
if (value.isBinaryStreamEnded()) {
unsubscribe();
resolve(value);
}
});
subscribeToCoValueWithoutMe(
this,
id,
options || {},
(value, unsubscribe) => {
if (value.isBinaryStreamEnded()) {
unsubscribe();
resolve(value);
}
},
);
});
}
@@ -924,78 +894,36 @@ export class FileStream extends CoValueBase implements CoValue {
* Load a `FileStream`
* @category Subscription & Loading
*/
static load<C extends FileStream, Depth>(
static load<C extends FileStream>(
this: CoValueClass<C>,
id: ID<C>,
depth: Depth & DepthsIn<C>,
): Promise<DeeplyLoaded<C, Depth> | undefined>;
static load<C extends FileStream, Depth>(
this: CoValueClass<C>,
id: ID<C>,
as: Account,
depth: Depth & DepthsIn<C>,
): Promise<DeeplyLoaded<C, Depth> | undefined>;
static load<C extends FileStream, Depth>(
this: CoValueClass<C>,
id: ID<C>,
asOrDepth: Account | (Depth & DepthsIn<C>),
depth?: Depth & DepthsIn<C>,
): Promise<DeeplyLoaded<C, Depth> | undefined> {
return loadCoValueWithoutMe(this, id, asOrDepth, depth);
options?: { loadAs?: Account | AnonymousJazzAgent },
): Promise<Resolved<C, true> | null> {
return loadCoValueWithoutMe(this, id, options);
}
/**
* Subscribe to a `FileStream`, when you have an ID but don't have a `FileStream` instance yet
* @category Subscription & Loading
*/
static subscribe<C extends FileStream, Depth>(
static subscribe<C extends FileStream>(
this: CoValueClass<C>,
id: ID<C>,
depth: Depth & DepthsIn<C>,
listener: (value: DeeplyLoaded<C, Depth>) => void,
): () => void;
static subscribe<C extends FileStream, Depth>(
this: CoValueClass<C>,
id: ID<C>,
as: Account,
depth: Depth & DepthsIn<C>,
listener: (value: DeeplyLoaded<C, Depth>) => void,
): () => void;
static subscribe<C extends FileStream, Depth>(
this: CoValueClass<C>,
id: ID<C>,
asOrDepth: Account | (Depth & DepthsIn<C>),
depthOrListener:
| (Depth & DepthsIn<C>)
| ((value: DeeplyLoaded<C, Depth>) => void),
listener?: (value: DeeplyLoaded<C, Depth>) => void,
options: { loadAs?: Account | AnonymousJazzAgent },
listener: (value: Resolved<C, true>) => void,
): () => void {
return subscribeToCoValueWithoutMe<C, Depth>(
this,
id,
asOrDepth,
depthOrListener,
listener,
);
}
ensureLoaded<B extends FileStream, Depth>(
this: B,
depth: Depth & DepthsIn<B>,
): Promise<DeeplyLoaded<B, Depth> | undefined> {
return ensureCoValueLoaded(this, depth);
return subscribeToCoValueWithoutMe<C, true>(this, id, options, listener);
}
/**
* An instance method to subscribe to an existing `FileStream`
* @category Subscription & Loading
*/
subscribe<B extends FileStream, Depth>(
subscribe<B extends FileStream>(
this: B,
depth: Depth & DepthsIn<B>,
listener: (value: DeeplyLoaded<B, Depth>) => void,
listener: (value: Resolved<B, true>) => void,
): () => void {
return subscribeToExistingCoValue(this, depth, listener);
return subscribeToExistingCoValue(this, {}, listener);
}
/**

View File

@@ -5,12 +5,15 @@ import type {
CoValue,
CoValueClass,
CoValueFromRaw,
DeeplyLoaded,
DepthsIn,
ID,
RefEncoded,
RefsToResolve,
RefsToResolveStrict,
Resolved,
Schema,
SchemaFor,
SubscribeListenerOptions,
SubscribeRestArgs,
UnCo,
} from "../internal.js";
import {
@@ -25,6 +28,7 @@ import {
loadCoValueWithoutMe,
makeRefs,
parseCoValueCreateOptions,
parseSubscribeRestArgs,
subscribeToCoValueWithoutMe,
subscribeToExistingCoValue,
subscriptionsScopes,
@@ -419,24 +423,15 @@ export class CoList<Item = any> extends Array<Item> implements CoValue {
*
* @category Subscription & Loading
*/
static load<C extends CoList, Depth>(
this: CoValueClass<C>,
id: ID<C>,
depth: Depth & DepthsIn<C>,
): Promise<DeeplyLoaded<C, Depth> | undefined>;
static load<C extends CoList, Depth>(
this: CoValueClass<C>,
id: ID<C>,
as: Account,
depth: Depth & DepthsIn<C>,
): Promise<DeeplyLoaded<C, Depth> | undefined>;
static load<C extends CoList, Depth>(
this: CoValueClass<C>,
id: ID<C>,
asOrDepth: Account | (Depth & DepthsIn<C>),
depth?: Depth & DepthsIn<C>,
): Promise<DeeplyLoaded<C, Depth> | undefined> {
return loadCoValueWithoutMe(this, id, asOrDepth, depth);
static load<L extends CoList, const R extends RefsToResolve<L> = true>(
this: CoValueClass<L>,
id: ID<L>,
options?: {
resolve?: RefsToResolveStrict<L, R>;
loadAs?: Account | AnonymousJazzAgent;
},
): Promise<Resolved<L, R> | null> {
return loadCoValueWithoutMe(this, id, options);
}
/**
@@ -467,35 +462,24 @@ export class CoList<Item = any> extends Array<Item> implements CoValue {
*
* @category Subscription & Loading
*/
static subscribe<C extends CoList, Depth>(
this: CoValueClass<C>,
id: ID<C>,
depth: Depth & DepthsIn<C>,
listener: (value: DeeplyLoaded<C, Depth>) => void,
static subscribe<L extends CoList, const R extends RefsToResolve<L> = true>(
this: CoValueClass<L>,
id: ID<L>,
listener: (value: Resolved<L, R>, unsubscribe: () => void) => void,
): () => void;
static subscribe<C extends CoList, Depth>(
this: CoValueClass<C>,
id: ID<C>,
as: Account,
depth: Depth & DepthsIn<C>,
listener: (value: DeeplyLoaded<C, Depth>) => void,
static subscribe<L extends CoList, const R extends RefsToResolve<L> = true>(
this: CoValueClass<L>,
id: ID<L>,
options: SubscribeListenerOptions<L, R>,
listener: (value: Resolved<L, R>, unsubscribe: () => void) => void,
): () => void;
static subscribe<C extends CoList, Depth>(
this: CoValueClass<C>,
id: ID<C>,
asOrDepth: Account | (Depth & DepthsIn<C>),
depthOrListener:
| (Depth & DepthsIn<C>)
| ((value: DeeplyLoaded<C, Depth>) => void),
listener?: (value: DeeplyLoaded<C, Depth>) => void,
static subscribe<L extends CoList, const R extends RefsToResolve<L>>(
this: CoValueClass<L>,
id: ID<L>,
...args: SubscribeRestArgs<L, R>
): () => void {
return subscribeToCoValueWithoutMe<C, Depth>(
this,
id,
asOrDepth,
depthOrListener,
listener,
);
const { options, listener } = parseSubscribeRestArgs(args);
return subscribeToCoValueWithoutMe<L, R>(this, id, options, listener);
}
/**
@@ -505,11 +489,11 @@ export class CoList<Item = any> extends Array<Item> implements CoValue {
*
* @category Subscription & Loading
*/
ensureLoaded<L extends CoList, Depth>(
ensureLoaded<L extends CoList, const R extends RefsToResolve<L>>(
this: L,
depth: Depth & DepthsIn<L>,
): Promise<DeeplyLoaded<L, Depth>> {
return ensureCoValueLoaded(this, depth);
options: { resolve: RefsToResolveStrict<L, R> },
): Promise<Resolved<L, R>> {
return ensureCoValueLoaded(this, options);
}
/**
@@ -521,12 +505,21 @@ export class CoList<Item = any> extends Array<Item> implements CoValue {
*
* @category Subscription & Loading
**/
subscribe<L extends CoList, Depth>(
subscribe<L extends CoList, const R extends RefsToResolve<L> = true>(
this: L,
depth: Depth & DepthsIn<L>,
listener: (value: DeeplyLoaded<L, Depth>) => void,
listener: (value: Resolved<L, R>, unsubscribe: () => void) => void,
): () => void;
subscribe<L extends CoList, const R extends RefsToResolve<L> = true>(
this: L,
options: { resolve?: RefsToResolveStrict<L, R> },
listener: (value: Resolved<L, R>, unsubscribe: () => void) => void,
): () => void;
subscribe<L extends CoList, const R extends RefsToResolve<L>>(
this: L,
...args: SubscribeRestArgs<L, R>
): () => void {
return subscribeToExistingCoValue(this, depth, listener);
const { options, listener } = parseSubscribeRestArgs(args);
return subscribeToExistingCoValue(this, options, listener);
}
/** @category Type Helpers */

View File

@@ -12,13 +12,16 @@ import type {
AnonymousJazzAgent,
CoValue,
CoValueClass,
DeeplyLoaded,
DepthsIn,
ID,
IfCo,
RefEncoded,
RefIfCoValue,
RefsToResolve,
RefsToResolveStrict,
Resolved,
Schema,
SubscribeListenerOptions,
SubscribeRestArgs,
co,
} from "../internal.js";
import {
@@ -32,6 +35,7 @@ import {
loadCoValueWithoutMe,
makeRefs,
parseCoValueCreateOptions,
parseSubscribeRestArgs,
subscribeToCoValueWithoutMe,
subscribeToExistingCoValue,
subscriptionsScopes,
@@ -433,24 +437,15 @@ export class CoMap extends CoValueBase implements CoValue {
*
* @category Subscription & Loading
*/
static load<C extends CoMap, Depth>(
this: CoValueClass<C>,
id: ID<C>,
depth: Depth & DepthsIn<C>,
): Promise<DeeplyLoaded<C, Depth> | undefined>;
static load<C extends CoMap, Depth>(
this: CoValueClass<C>,
id: ID<C>,
as: Account,
depth: Depth & DepthsIn<C>,
): Promise<DeeplyLoaded<C, Depth> | undefined>;
static load<C extends CoMap, Depth>(
this: CoValueClass<C>,
id: ID<C>,
asOrDepth: Account | (Depth & DepthsIn<C>),
depth?: Depth & DepthsIn<C>,
): Promise<DeeplyLoaded<C, Depth> | undefined> {
return loadCoValueWithoutMe(this, id, asOrDepth, depth);
static load<M extends CoMap, const R extends RefsToResolve<M> = true>(
this: CoValueClass<M>,
id: ID<M>,
options?: {
resolve?: RefsToResolveStrict<M, R>;
loadAs?: Account | AnonymousJazzAgent;
},
): Promise<Resolved<M, R> | null> {
return loadCoValueWithoutMe(this, id, options);
}
/**
@@ -480,35 +475,24 @@ export class CoMap extends CoValueBase implements CoValue {
*
* @category Subscription & Loading
*/
static subscribe<C extends CoMap, Depth>(
this: CoValueClass<C>,
id: ID<C>,
depth: Depth & DepthsIn<C>,
listener: (value: DeeplyLoaded<C, Depth>) => void,
static subscribe<M extends CoMap, const R extends RefsToResolve<M> = true>(
this: CoValueClass<M>,
id: ID<M>,
listener: (value: Resolved<M, R>, unsubscribe: () => void) => void,
): () => void;
static subscribe<C extends CoMap, Depth>(
this: CoValueClass<C>,
id: ID<C>,
as: Account,
depth: Depth & DepthsIn<C>,
listener: (value: DeeplyLoaded<C, Depth>) => void,
static subscribe<M extends CoMap, const R extends RefsToResolve<M> = true>(
this: CoValueClass<M>,
id: ID<M>,
options: SubscribeListenerOptions<M, R>,
listener: (value: Resolved<M, R>, unsubscribe: () => void) => void,
): () => void;
static subscribe<C extends CoMap, Depth>(
this: CoValueClass<C>,
id: ID<C>,
asOrDepth: Account | (Depth & DepthsIn<C>),
depthOrListener:
| (Depth & DepthsIn<C>)
| ((value: DeeplyLoaded<C, Depth>) => void),
listener?: (value: DeeplyLoaded<C, Depth>) => void,
static subscribe<M extends CoMap, const R extends RefsToResolve<M>>(
this: CoValueClass<M>,
id: ID<M>,
...args: SubscribeRestArgs<M, R>
): () => void {
return subscribeToCoValueWithoutMe<C, Depth>(
this,
id,
asOrDepth,
depthOrListener,
listener,
);
const { options, listener } = parseSubscribeRestArgs(args);
return subscribeToCoValueWithoutMe<M, R>(this, id, options, listener);
}
static findUnique<M extends CoMap>(
@@ -540,11 +524,11 @@ export class CoMap extends CoValueBase implements CoValue {
*
* @category Subscription & Loading
*/
ensureLoaded<M extends CoMap, Depth>(
ensureLoaded<M extends CoMap, const R extends RefsToResolve<M>>(
this: M,
depth: Depth & DepthsIn<M>,
): Promise<DeeplyLoaded<M, Depth>> {
return ensureCoValueLoaded(this, depth);
options: { resolve: RefsToResolveStrict<M, R> },
): Promise<Resolved<M, R>> {
return ensureCoValueLoaded(this, options);
}
/**
@@ -556,12 +540,21 @@ export class CoMap extends CoValueBase implements CoValue {
*
* @category Subscription & Loading
**/
subscribe<M extends CoMap, Depth>(
subscribe<M extends CoMap, const R extends RefsToResolve<M> = true>(
this: M,
depth: Depth & DepthsIn<M>,
listener: (value: DeeplyLoaded<M, Depth>) => void,
listener: (value: Resolved<M, R>, unsubscribe: () => void) => void,
): () => void;
subscribe<M extends CoMap, const R extends RefsToResolve<M> = true>(
this: M,
options: { resolve?: RefsToResolveStrict<M, R> },
listener: (value: Resolved<M, R>, unsubscribe: () => void) => void,
): () => void;
subscribe<M extends CoMap, const R extends RefsToResolve<M>>(
this: M,
...args: SubscribeRestArgs<M, R>
): () => void {
return subscribeToExistingCoValue(this, depth, listener);
const { options, listener } = parseSubscribeRestArgs(args);
return subscribeToExistingCoValue<M, R>(this, options, listener);
}
applyDiff<N extends Partial<CoMapInit<this>>>(newValues: N) {

View File

@@ -4,13 +4,20 @@ import {
type RawCoPlainText,
stringifyOpID,
} from "cojson";
import { activeAccountContext } from "../implementation/activeAccountContext.js";
import type { CoValue, CoValueClass, ID } from "../internal.js";
import type {
AnonymousJazzAgent,
CoValue,
CoValueClass,
ID,
Resolved,
SubscribeListenerOptions,
SubscribeRestArgs,
} from "../internal.js";
import {
inspect,
isAccountInstance,
loadCoValue,
subscribeToCoValue,
loadCoValueWithoutMe,
parseSubscribeRestArgs,
subscribeToCoValueWithoutMe,
subscribeToExistingCoValue,
} from "../internal.js";
import { Account } from "./account.js";
@@ -122,9 +129,9 @@ export class CoPlainText extends String implements CoValue {
static load<T extends CoPlainText>(
this: CoValueClass<T>,
id: ID<T>,
as?: Account,
): Promise<T | undefined> {
return loadCoValue(this, id, as ?? activeAccountContext.get(), []);
options?: { loadAs?: Account | AnonymousJazzAgent },
): Promise<T | null> {
return loadCoValueWithoutMe(this, id, options);
}
// /**
@@ -157,47 +164,23 @@ export class CoPlainText extends String implements CoValue {
static subscribe<T extends CoPlainText>(
this: CoValueClass<T>,
id: ID<T>,
listener: (value: T) => void,
listener: (value: Resolved<T, true>, unsubscribe: () => void) => void,
): () => void;
static subscribe<T extends CoPlainText>(
this: CoValueClass<T>,
id: ID<T>,
as: Account,
listener: (value: T) => void,
options: Omit<SubscribeListenerOptions<T, true>, "resolve">,
listener: (value: Resolved<T, true>, unsubscribe: () => void) => void,
): () => void;
static subscribe<T extends CoPlainText>(
this: CoValueClass<T>,
id: ID<T>,
asOrListener: Account | ((value: T) => void),
listener?: (value: T) => void,
...args: SubscribeRestArgs<T, true>
): () => void {
if (isAccountInstance(asOrListener)) {
return subscribeToCoValue(this, id, asOrListener, [], listener!);
}
return subscribeToCoValue(
this,
id,
activeAccountContext.get(),
[],
listener!,
);
const { options, listener } = parseSubscribeRestArgs(args);
return subscribeToCoValueWithoutMe<T, true>(this, id, options, listener);
}
// /**
// * Effectful version of `CoMap.subscribe()` that returns a stream of updates.
// *
// * Needs to be run inside an `AccountCtx` context.
// *
// * @category Subscription & Loading
// */
// static subscribeEf<T extends CoPlainText>(
// this: CoValueClass<T>,
// id: ID<T>,
// ): Stream.Stream<T, UnavailableError, AccountCtx> {
// return subscribeToCoValueEf(this, id, []);
// }
/**
* Given an already loaded `CoPlainText`, subscribe to updates to the `CoPlainText` and ensure that the specified fields are loaded to the specified depth.
*
@@ -209,8 +192,8 @@ export class CoPlainText extends String implements CoValue {
**/
subscribe<T extends CoPlainText>(
this: T,
listener: (value: T) => void,
listener: (value: Resolved<T, true>, unsubscribe: () => void) => void,
): () => void {
return subscribeToExistingCoValue(this, [], listener);
return subscribeToExistingCoValue(this, {}, listener);
}
}

View File

@@ -6,94 +6,208 @@ import { type CoList } from "./coList.js";
import { type CoKeys, type CoMap } from "./coMap.js";
import { type CoValue, type ID } from "./interfaces.js";
function hasRefValue(value: CoValue, key: string | number) {
return Boolean(
(
value as unknown as {
_refs: { [key: string]: Ref<CoValue> | undefined };
}
)._refs?.[key],
);
}
function hasReadAccess(value: CoValue, key: string | number) {
return Boolean(
(
value as unknown as {
_refs: { [key: string]: Ref<CoValue> | undefined };
}
)._refs?.[key]?.hasReadAccess(),
);
}
function isOptionalField(value: CoValue, key: string): boolean {
return (
((value as CoMap)._schema[key] as RefEncoded<CoValue>)?.optional ?? false
);
}
type FulfillsDepthResult = "unauthorized" | "fulfilled" | "unfulfilled";
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export function fulfillsDepth(depth: any, value: CoValue): boolean {
export function fulfillsDepth(depth: any, value: CoValue): FulfillsDepthResult {
if (depth === true || depth === undefined) {
return "fulfilled";
}
if (
value._type === "CoMap" ||
value._type === "Group" ||
value._type === "Account"
) {
if (Array.isArray(depth) && depth.length === 1) {
return Object.entries(value).every(([key, item]) => {
return (
value as unknown as {
_refs: { [key: string]: Ref<CoValue> | undefined };
}
)._refs[key]
? item && fulfillsDepth(depth[0], item)
: ((value as CoMap)._schema[ItemsSym] as RefEncoded<CoValue>)!
.optional;
});
} else {
for (const key of Object.keys(depth)) {
const map = value as unknown as {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
[key: string]: any;
};
const map = value as CoMap;
if ("$each" in depth) {
let result: FulfillsDepthResult = "fulfilled";
for (const [key, item] of Object.entries(value)) {
if (map._raw.get(key) !== undefined) {
if (!item) {
if (hasReadAccess(map, key)) {
result = "unfulfilled";
continue;
} else {
return "unauthorized";
}
}
const innerResult = fulfillsDepth(depth.$each, item);
if (innerResult === "unfulfilled") {
result = "unfulfilled";
} else if (
innerResult === "unauthorized" &&
!isOptionalField(value, ItemsSym)
) {
return "unauthorized"; // If any item is unauthorized, the whole thing is unauthorized
}
} else if (!isOptionalField(value, ItemsSym)) {
return "unfulfilled";
}
}
return result;
} else {
let result: FulfillsDepthResult = "fulfilled";
for (const key of Object.keys(depth)) {
if (map._raw.get(key) === undefined) {
if (!map._schema?.[key]) {
// Field not defined in schema
if (map._schema?.[ItemsSym]) {
// CoMap.Record
if (map._schema[ItemsSym].optional) {
if (isOptionalField(map, ItemsSym)) {
continue;
} else {
// All fields are required, so the returned type is not optional and we must comply
throw new Error(
`The ref ${key} requested on ${map.constructor.name} is missing`,
);
}
} else {
// Field not defined in CoMap schema
throw new Error(
`The ref ${key} requested on ${map.constructor.name} is not defined in the schema`,
);
}
} else if (map._schema[key].optional) {
} else if (isOptionalField(map, key)) {
continue;
} else {
// Field is required but has never been set
throw new Error(
`The ref ${key} on ${map.constructor.name} is required but missing`,
);
}
}
} else {
const item = (value as Record<string, any>)[key];
if (!map[key]) {
return false;
}
if (!fulfillsDepth(depth[key], map[key])) {
return false;
if (!item) {
if (hasReadAccess(map, key)) {
result = "unfulfilled";
continue;
} else {
return "unauthorized";
}
}
const innerResult = fulfillsDepth(depth[key], item);
if (innerResult === "unfulfilled") {
result = "unfulfilled";
} else if (
innerResult === "unauthorized" &&
!isOptionalField(value, key)
) {
return "unauthorized"; // If any item is unauthorized, the whole thing is unauthorized
}
}
}
return true;
return result;
}
} else if (value._type === "CoList") {
if (depth.length === 0) {
return true;
} else {
const itemDepth = depth[0];
return (value as CoList).every((item, i) =>
(value as CoList)._refs[i]
? item && fulfillsDepth(itemDepth, item)
: ((value as CoList)._schema[ItemsSym] as RefEncoded<CoValue>)
.optional,
);
if ("$each" in depth) {
let result: FulfillsDepthResult = "fulfilled";
for (const [key, item] of (value as CoList).entries()) {
if (hasRefValue(value, key)) {
if (!item) {
if (hasReadAccess(value, key)) {
result = "unfulfilled";
continue;
} else {
return "unauthorized";
}
}
const innerResult = fulfillsDepth(depth.$each, item);
if (innerResult === "unfulfilled") {
result = "unfulfilled";
} else if (
innerResult === "unauthorized" &&
!isOptionalField(value, ItemsSym)
) {
return "unauthorized"; // If any item is unauthorized, the whole thing is unauthorized
}
} else if (!isOptionalField(value, ItemsSym)) {
return "unfulfilled";
}
}
return result;
}
return "fulfilled";
} else if (value._type === "CoStream") {
if (depth.length === 0) {
return true;
} else {
const itemDepth = depth[0];
return Object.values((value as CoFeed).perSession).every((entry) =>
entry.ref
? entry.value && fulfillsDepth(itemDepth, entry.value)
: ((value as CoFeed)._schema[ItemsSym] as RefEncoded<CoValue>)
.optional,
);
if ("$each" in depth) {
let result: FulfillsDepthResult = "fulfilled";
for (const item of Object.values((value as CoFeed).perSession)) {
if (item.ref) {
if (!item.value) {
if (item.ref.hasReadAccess()) {
result = "unfulfilled";
continue;
} else {
return "unauthorized";
}
}
const innerResult = fulfillsDepth(depth.$each, item.value);
if (innerResult === "unfulfilled") {
result = "unfulfilled";
} else if (
innerResult === "unauthorized" &&
!isOptionalField(value, ItemsSym)
) {
return "unauthorized"; // If any item is unauthorized, the whole thing is unauthorized
}
} else if (!isOptionalField(value, ItemsSym)) {
return "unfulfilled";
}
}
return result;
}
return "fulfilled";
} else if (
value._type === "BinaryCoStream" ||
value._type === "CoPlainText"
) {
return true;
return "fulfilled";
} else {
console.error(value);
throw new Error("Unexpected value type: " + value._type);
@@ -101,101 +215,119 @@ export function fulfillsDepth(depth: any, value: CoValue): boolean {
}
type UnCoNotNull<T> = UnCo<Exclude<T, null>>;
type Clean<T> = UnCo<NonNullable<T>>;
export type Clean<T> = UnCo<NonNullable<T>>;
export type DepthsIn<
export type RefsToResolve<
V,
DepthLimit extends number = 5,
DepthLimit extends number = 10,
CurrentDepth extends number[] = [],
> =
| boolean
| (DepthLimit extends CurrentDepth["length"]
? // eslint-disable-next-line @typescript-eslint/no-explicit-any
any
: // Basically V extends CoList - but if we used that we'd introduce circularity into the definition of CoList itself
V extends Array<infer Item>
?
| [DepthsIn<UnCoNotNull<Item>, DepthLimit, [0, ...CurrentDepth]>]
| never[]
| {
$each: RefsToResolve<
UnCoNotNull<Item>,
DepthLimit,
[0, ...CurrentDepth]
>;
}
| boolean
: // Basically V extends CoMap | Group | Account - but if we used that we'd introduce circularity into the definition of CoMap itself
V extends { _type: "CoMap" | "Group" | "Account" }
?
| {
[Key in CoKeys<V> as Clean<V[Key]> extends CoValue
? Key
: never]?: DepthsIn<
: never]?: RefsToResolve<
Clean<V[Key]>,
DepthLimit,
[0, ...CurrentDepth]
>;
}
| (ItemsSym extends keyof V
? [
DepthsIn<
? {
$each: RefsToResolve<
Clean<V[ItemsSym]>,
DepthLimit,
[0, ...CurrentDepth]
>,
]
>;
}
: never)
| never[]
| boolean
: V extends {
_type: "CoStream";
byMe: CoFeedEntry<infer Item> | undefined;
}
?
| [
DepthsIn<
| {
$each: RefsToResolve<
UnCoNotNull<Item>,
DepthLimit,
[0, ...CurrentDepth]
>,
]
| never[]
: never[])
| never[];
>;
}
| boolean
: boolean);
export type RefsToResolveStrict<T, V> = V extends RefsToResolve<T>
? RefsToResolve<T>
: V;
export type Resolved<T, R extends RefsToResolve<T> | undefined> = DeeplyLoaded<
T,
R,
10,
[]
>;
export type DeeplyLoaded<
V,
Depth,
DepthLimit extends number = 5,
DepthLimit extends number = 10,
CurrentDepth extends number[] = [],
> = DepthLimit extends CurrentDepth["length"]
? V
: // Basically V extends CoList - but if we used that we'd introduce circularity into the definition of CoList itself
[V] extends [Array<infer Item>]
? Depth extends never[] // []
? V
: UnCoNotNull<Item> extends CoValue
? Depth extends Array<infer ItemDepth> // [item-depth]
? (UnCoNotNull<Item> &
: Depth extends boolean | undefined // Checking against boolean instead of true because the inference from RefsToResolveStrict transforms true into boolean
? V
: // Basically V extends CoList - but if we used that we'd introduce circularity into the definition of CoList itself
[V] extends [Array<infer Item>]
? UnCoNotNull<Item> extends CoValue
? Depth extends { $each: infer ItemDepth }
? // Deeply loaded CoList
(UnCoNotNull<Item> &
DeeplyLoaded<
UnCoNotNull<Item>,
ItemDepth,
DepthLimit,
[0, ...CurrentDepth]
>)[] &
V
V // the CoList base type needs to be intersected after so that built-in methods return the correct narrowed array type
: never
: V
: // Basically V extends CoMap | Group | Account - but if we used that we'd introduce circularity into the definition of CoMap itself
[V] extends [{ _type: "CoMap" | "Group" | "Account" }]
? Depth extends never[]
? V
: Depth extends Array<infer ItemDepth>
? ItemsSym extends keyof V
? V & {
: // Basically V extends CoMap | Group | Account - but if we used that we'd introduce circularity into the definition of CoMap itself
[V] extends [{ _type: "CoMap" | "Group" | "Account" }]
? ItemsSym extends keyof V
? Depth extends { $each: infer ItemDepth }
? // Deeply loaded Record-like CoMap
{
[key: string]: DeeplyLoaded<
Clean<V[ItemsSym]>,
ItemDepth,
DepthLimit,
[0, ...CurrentDepth]
>;
}
} & V // same reason as in CoList
: never
: keyof Depth extends never
: keyof Depth extends never // Depth = {}
? V
: {
[Key in keyof Depth]-?: Key extends CoKeys<V>
: // Deeply loaded CoMap
{
-readonly [Key in keyof Depth]-?: Key extends CoKeys<V>
? Clean<V[Key]> extends CoValue
?
| DeeplyLoaded<
@@ -207,32 +339,31 @@ export type DeeplyLoaded<
| (undefined extends V[Key] ? undefined : never)
: never
: never;
} & V
: [V] extends [
} & V // same reason as in CoList
: [V] extends [
{
_type: "CoStream";
byMe: CoFeedEntry<infer Item> | undefined;
},
]
? // Deeply loaded CoStream
{
_type: "CoStream";
byMe: CoFeedEntry<infer Item> | undefined;
},
]
? Depth extends never[]
? V
: V & {
byMe?: { value: UnCoNotNull<Item> };
inCurrentSession?: { value: UnCoNotNull<Item> };
perSession: {
[key: SessionID]: { value: UnCoNotNull<Item> };
};
} & { [key: ID<Account>]: { value: UnCoNotNull<Item> } }
: [V] extends [
{
_type: "BinaryCoStream";
},
]
? V
} & { [key: ID<Account>]: { value: UnCoNotNull<Item> } } & V // same reason as in CoList
: [V] extends [
{
_type: "CoPlainText";
_type: "BinaryCoStream";
},
]
? V
: never;
: [V] extends [
{
_type: "CoPlainText";
},
]
? V
: never;

View File

@@ -10,11 +10,14 @@ import { activeAccountContext } from "../implementation/activeAccountContext.js"
import type {
CoValue,
CoValueClass,
DeeplyLoaded,
DepthsIn,
ID,
RefEncoded,
RefsToResolve,
RefsToResolveStrict,
Resolved,
Schema,
SubscribeListenerOptions,
SubscribeRestArgs,
} from "../internal.js";
import {
CoValueBase,
@@ -23,6 +26,7 @@ import {
ensureCoValueLoaded,
loadCoValueWithoutMe,
parseGroupCreateOptions,
parseSubscribeRestArgs,
subscribeToCoValueWithoutMe,
subscribeToExistingCoValue,
} from "../internal.js";
@@ -229,73 +233,59 @@ export class Group extends CoValueBase implements CoValue {
}
/** @category Subscription & Loading */
static load<C extends Group, Depth>(
this: CoValueClass<C>,
id: ID<C>,
depth: Depth & DepthsIn<C>,
): Promise<DeeplyLoaded<C, Depth> | undefined>;
static load<C extends Group, Depth>(
this: CoValueClass<C>,
id: ID<C>,
as: Account,
depth: Depth & DepthsIn<C>,
): Promise<DeeplyLoaded<C, Depth> | undefined>;
static load<C extends Group, Depth>(
this: CoValueClass<C>,
id: ID<C>,
asOrDepth: Account | (Depth & DepthsIn<C>),
depth?: Depth & DepthsIn<C>,
): Promise<DeeplyLoaded<C, Depth> | undefined> {
return loadCoValueWithoutMe(this, id, asOrDepth, depth);
static load<G extends Group, const R extends RefsToResolve<G>>(
this: CoValueClass<G>,
id: ID<G>,
options?: { resolve?: RefsToResolveStrict<G, R>; loadAs?: Account },
): Promise<Resolved<G, R> | null> {
return loadCoValueWithoutMe(this, id, options);
}
/** @category Subscription & Loading */
static subscribe<C extends Group, Depth>(
this: CoValueClass<C>,
id: ID<C>,
depth: Depth & DepthsIn<C>,
listener: (value: DeeplyLoaded<C, Depth>) => void,
static subscribe<G extends Group, const R extends RefsToResolve<G>>(
this: CoValueClass<G>,
id: ID<G>,
listener: (value: Resolved<G, R>, unsubscribe: () => void) => void,
): () => void;
static subscribe<C extends Group, Depth>(
this: CoValueClass<C>,
id: ID<C>,
as: Account,
depth: Depth & DepthsIn<C>,
listener: (value: DeeplyLoaded<C, Depth>) => void,
static subscribe<G extends Group, const R extends RefsToResolve<G>>(
this: CoValueClass<G>,
id: ID<G>,
options: SubscribeListenerOptions<G, R>,
listener: (value: Resolved<G, R>, unsubscribe: () => void) => void,
): () => void;
static subscribe<C extends Group, Depth>(
this: CoValueClass<C>,
id: ID<C>,
asOrDepth: Account | (Depth & DepthsIn<C>),
depthOrListener:
| (Depth & DepthsIn<C>)
| ((value: DeeplyLoaded<C, Depth>) => void),
listener?: (value: DeeplyLoaded<C, Depth>) => void,
static subscribe<G extends Group, const R extends RefsToResolve<G>>(
this: CoValueClass<G>,
id: ID<G>,
...args: SubscribeRestArgs<G, R>
): () => void {
return subscribeToCoValueWithoutMe<C, Depth>(
this,
id,
asOrDepth,
depthOrListener,
listener,
);
const { options, listener } = parseSubscribeRestArgs(args);
return subscribeToCoValueWithoutMe<G, R>(this, id, options, listener);
}
/** @category Subscription & Loading */
ensureLoaded<G extends Group, Depth>(
ensureLoaded<G extends Group, const R extends RefsToResolve<G>>(
this: G,
depth: Depth & DepthsIn<G>,
): Promise<DeeplyLoaded<G, Depth>> {
return ensureCoValueLoaded(this, depth);
options?: { resolve?: RefsToResolveStrict<G, R> },
): Promise<Resolved<G, R>> {
return ensureCoValueLoaded(this, options);
}
/** @category Subscription & Loading */
subscribe<G extends Group, Depth>(
subscribe<G extends Group, const R extends RefsToResolve<G>>(
this: G,
depth: Depth & DepthsIn<G>,
listener: (value: DeeplyLoaded<G, Depth>) => void,
listener: (value: Resolved<G, R>, unsubscribe: () => void) => void,
): () => void;
subscribe<G extends Group, const R extends RefsToResolve<G>>(
this: G,
options: { resolve?: RefsToResolveStrict<G, R> },
listener: (value: Resolved<G, R>, unsubscribe: () => void) => void,
): () => void;
subscribe<G extends Group, const R extends RefsToResolve<G>>(
this: G,
...args: SubscribeRestArgs<G, R>
): () => void {
return subscribeToExistingCoValue(this, depth, listener);
const { options, listener } = parseSubscribeRestArgs(args);
return subscribeToExistingCoValue(this, options, listener);
}
/**

View File

@@ -167,12 +167,9 @@ export class Inbox {
);
}
return loadCoValue(
Schema,
message.get("payload") as ID<I>,
account,
[],
);
return loadCoValue(Schema, message.get("payload") as ID<I>, {
loadAs: account,
});
})
.then((value) => {
if (!value) {

View File

@@ -6,7 +6,6 @@ import type {
import { RawAccount } from "cojson";
import { activeAccountContext } from "../implementation/activeAccountContext.js";
import { AnonymousJazzAgent } from "../implementation/anonymousJazzAgent.js";
import type { DeeplyLoaded, DepthsIn } from "../internal.js";
import {
Ref,
SubscriptionScope,
@@ -15,7 +14,12 @@ import {
} from "../internal.js";
import { coValuesCache } from "../lib/cache.js";
import { type Account } from "./account.js";
import { fulfillsDepth } from "./deepLoading.js";
import {
RefsToResolve,
RefsToResolveStrict,
Resolved,
fulfillsDepth,
} from "./deepLoading.js";
import { type Group } from "./group.js";
import { RegisteredSchemas } from "./registeredSchemas.js";
@@ -155,56 +159,70 @@ export class CoValueBase implements CoValue {
}
}
export function loadCoValueWithoutMe<V extends CoValue, Depth>(
export function loadCoValueWithoutMe<
V extends CoValue,
const R extends RefsToResolve<V>,
>(
cls: CoValueClass<V>,
id: ID<CoValue>,
asOrDepth: Account | AnonymousJazzAgent | (Depth & DepthsIn<V>),
depth?: Depth & DepthsIn<V>,
): Promise<DeeplyLoaded<V, Depth> | undefined> {
if (isAccountInstance(asOrDepth) || isAnonymousAgentInstance(asOrDepth)) {
if (!depth) {
throw new Error(
"Depth is required when loading a CoValue as an Account or AnonymousJazzAgent",
);
}
return loadCoValue(cls, id, asOrDepth, depth);
}
return loadCoValue(cls, id, activeAccountContext.get(), asOrDepth);
options?: {
resolve?: RefsToResolveStrict<V, R>;
loadAs?: Account | AnonymousJazzAgent;
},
): Promise<Resolved<V, R> | null> {
return loadCoValue(cls, id, {
...options,
loadAs: options?.loadAs ?? activeAccountContext.get(),
});
}
export function loadCoValue<V extends CoValue, Depth>(
export function loadCoValue<
V extends CoValue,
const R extends RefsToResolve<V>,
>(
cls: CoValueClass<V>,
id: ID<CoValue>,
as: Account | AnonymousJazzAgent,
depth: Depth & DepthsIn<V>,
): Promise<DeeplyLoaded<V, Depth> | undefined> {
options: {
resolve?: RefsToResolveStrict<V, R>;
loadAs: Account | AnonymousJazzAgent;
},
): Promise<Resolved<V, R> | null> {
return new Promise((resolve) => {
subscribeToCoValue(
subscribeToCoValue<V, R>(
cls,
id,
as,
depth,
{
resolve: options.resolve,
loadAs: options.loadAs,
onUnavailable: () => {
resolve(null);
},
onUnauthorized: () => {
resolve(null);
},
},
(value, unsubscribe) => {
resolve(value);
unsubscribe();
},
() => {
resolve(undefined);
},
);
});
}
export async function ensureCoValueLoaded<V extends CoValue, Depth>(
export async function ensureCoValueLoaded<
V extends CoValue,
const R extends RefsToResolve<V>,
>(
existing: V,
depth: Depth & DepthsIn<V>,
): Promise<DeeplyLoaded<V, Depth>> {
options?: { resolve?: RefsToResolveStrict<V, R> } | undefined,
): Promise<Resolved<V, R>> {
const response = await loadCoValue(
existing.constructor as CoValueClass<V>,
existing.id,
existing._loadedAs,
depth,
{
loadAs: existing._loadedAs,
resolve: options?.resolve,
},
);
if (!response) {
@@ -214,70 +232,140 @@ export async function ensureCoValueLoaded<V extends CoValue, Depth>(
return response;
}
export function subscribeToCoValueWithoutMe<V extends CoValue, Depth>(
type SubscribeListener<V extends CoValue, R extends RefsToResolve<V>> = (
value: Resolved<V, R>,
unsubscribe: () => void,
) => void;
export type SubscribeListenerOptions<
V extends CoValue,
R extends RefsToResolve<V>,
> = {
resolve?: RefsToResolveStrict<V, R>;
loadAs?: Account | AnonymousJazzAgent;
onUnauthorized?: () => void;
onUnavailable?: () => void;
};
export type SubscribeRestArgs<V extends CoValue, R extends RefsToResolve<V>> =
| [options: SubscribeListenerOptions<V, R>, listener: SubscribeListener<V, R>]
| [listener: SubscribeListener<V, R>];
export function parseSubscribeRestArgs<
V extends CoValue,
R extends RefsToResolve<V>,
>(
args: SubscribeRestArgs<V, R>,
): {
options: SubscribeListenerOptions<V, R>;
listener: SubscribeListener<V, R>;
} {
if (args.length === 2) {
if (
typeof args[0] === "object" &&
args[0] &&
typeof args[1] === "function"
) {
return {
options: {
resolve: args[0].resolve,
loadAs: args[0].loadAs,
onUnauthorized: args[0].onUnauthorized,
onUnavailable: args[0].onUnavailable,
},
listener: args[1],
};
} else {
throw new Error("Invalid arguments");
}
} else {
if (typeof args[0] === "function") {
return { options: {}, listener: args[0] };
} else {
throw new Error("Invalid arguments");
}
}
}
export function subscribeToCoValueWithoutMe<
V extends CoValue,
const R extends RefsToResolve<V>,
>(
cls: CoValueClass<V>,
id: ID<CoValue>,
asOrDepth: Account | AnonymousJazzAgent | (Depth & DepthsIn<V>),
depthOrListener:
| (Depth & DepthsIn<V>)
| ((value: DeeplyLoaded<V, Depth>) => void),
listener?: (value: DeeplyLoaded<V, Depth>) => void,
options: SubscribeListenerOptions<V, R>,
listener: SubscribeListener<V, R>,
) {
if (isAccountInstance(asOrDepth) || isAnonymousAgentInstance(asOrDepth)) {
if (typeof depthOrListener !== "function") {
return subscribeToCoValue<V, Depth>(
cls,
id,
asOrDepth,
depthOrListener,
listener!,
);
}
throw new Error("Invalid arguments");
}
if (typeof depthOrListener !== "function") {
throw new Error("Invalid arguments");
}
return subscribeToCoValue<V, Depth>(
return subscribeToCoValue(
cls,
id,
activeAccountContext.get(),
asOrDepth,
depthOrListener,
{
...options,
loadAs: options.loadAs ?? activeAccountContext.get(),
},
listener,
);
}
export function subscribeToCoValue<V extends CoValue, Depth>(
export function subscribeToCoValue<
V extends CoValue,
const R extends RefsToResolve<V>,
>(
cls: CoValueClass<V>,
id: ID<CoValue>,
as: Account | AnonymousJazzAgent,
depth: Depth & DepthsIn<V>,
listener: (value: DeeplyLoaded<V, Depth>, unsubscribe: () => void) => void,
onUnavailable?: () => void,
syncResolution?: boolean,
options: {
resolve?: RefsToResolveStrict<V, R>;
loadAs: Account | AnonymousJazzAgent;
onUnavailable?: () => void;
onUnauthorized?: () => void;
syncResolution?: boolean;
},
listener: SubscribeListener<V, R>,
): () => void {
const ref = new Ref(id, as, { ref: cls, optional: false });
const ref = new Ref(id, options.loadAs, { ref: cls, optional: false });
let unsubscribed = false;
let unsubscribe: (() => void) | undefined;
function subscribe(value: CoValue | undefined) {
function subscribe() {
const value = ref.getValueWithoutAccessCheck();
if (!value) {
onUnavailable && onUnavailable();
options.onUnavailable?.();
return;
}
if (unsubscribed) return;
const subscription = new SubscriptionScope(
value,
cls as CoValueClass<V> & CoValueFromRaw<V>,
(update, subscription) => {
if (fulfillsDepth(depth, update)) {
listener(
update as DeeplyLoaded<V, Depth>,
subscription.unsubscribeAll,
if (!ref.hasReadAccess()) {
options.onUnauthorized?.();
return;
}
let result;
try {
result = fulfillsDepth(options.resolve, update);
} catch (e) {
console.error(
"Failed to load / subscribe to CoValue",
e,
e instanceof Error ? e.stack : undefined,
);
options.onUnavailable?.();
return;
}
if (result === "unauthorized") {
options.onUnauthorized?.();
return;
}
if (result === "fulfilled") {
listener(update as Resolved<V, R>, subscription.unsubscribeAll);
}
},
);
@@ -285,17 +373,21 @@ export function subscribeToCoValue<V extends CoValue, Depth>(
unsubscribe = subscription.unsubscribeAll;
}
const sync = syncResolution ? ref.syncLoad() : undefined;
const sync = options.syncResolution ? ref.syncLoad() : undefined;
if (sync) {
subscribe(sync);
subscribe();
} else {
ref
.load()
.then((value) => subscribe(value))
.then(() => subscribe())
.catch((e) => {
console.error("Failed to load / subscribe to CoValue", e);
onUnavailable?.();
console.error(
"Failed to load / subscribe to CoValue",
e,
e instanceof Error ? e.stack : undefined,
);
options.onUnavailable?.();
});
}
@@ -305,36 +397,47 @@ export function subscribeToCoValue<V extends CoValue, Depth>(
};
}
export function createCoValueObservable<V extends CoValue, Depth>(options?: {
syncResolution?: boolean;
}) {
let currentValue: DeeplyLoaded<V, Depth> | undefined | null = undefined;
export function createCoValueObservable<
V extends CoValue,
const R extends RefsToResolve<V>,
>() {
let currentValue: Resolved<V, R> | undefined | null = undefined;
let subscriberCount = 0;
function subscribe(
cls: CoValueClass<V>,
id: ID<CoValue>,
as: Account | AnonymousJazzAgent,
depth: Depth & DepthsIn<V>,
options: {
loadAs: Account | AnonymousJazzAgent;
resolve?: RefsToResolveStrict<V, R>;
onUnavailable?: () => void;
onUnauthorized?: () => void;
syncResolution?: boolean;
},
listener: () => void,
onUnavailable?: () => void,
) {
subscriberCount++;
const unsubscribe = subscribeToCoValue(
cls,
id,
as,
depth,
{
loadAs: options.loadAs,
resolve: options.resolve,
onUnavailable: () => {
currentValue = null;
options.onUnavailable?.();
},
onUnauthorized: () => {
currentValue = null;
options.onUnauthorized?.();
},
syncResolution: options.syncResolution,
},
(value) => {
currentValue = value;
listener();
},
() => {
currentValue = null;
onUnavailable?.();
},
options?.syncResolution,
);
return () => {
@@ -354,16 +457,29 @@ export function createCoValueObservable<V extends CoValue, Depth>(options?: {
return observable;
}
export function subscribeToExistingCoValue<V extends CoValue, Depth>(
export function subscribeToExistingCoValue<
V extends CoValue,
const R extends RefsToResolve<V>,
>(
existing: V,
depth: Depth & DepthsIn<V>,
listener: (value: DeeplyLoaded<V, Depth>) => void,
options:
| {
resolve?: RefsToResolveStrict<V, R>;
onUnavailable?: () => void;
onUnauthorized?: () => void;
}
| undefined,
listener: SubscribeListener<V, R>,
): () => void {
return subscribeToCoValue(
existing.constructor as CoValueClass<V>,
existing.id,
existing._loadedAs,
depth,
{
loadAs: existing._loadedAs,
resolve: options?.resolve,
onUnavailable: options?.onUnavailable,
onUnauthorized: options?.onUnauthorized,
},
listener,
);
}

View File

@@ -42,7 +42,13 @@ export { CoValueBase } from "./coValues/interfaces.js";
export { Profile } from "./coValues/profile.js";
export { SchemaUnion } from "./coValues/schemaUnion.js";
export type { CoValueClass, DeeplyLoaded, DepthsIn } from "./internal.js";
export type {
CoValueClass,
DeeplyLoaded,
Resolved,
RefsToResolve,
RefsToResolveStrict,
} from "./internal.js";
export {
createCoValueObservable,

View File

@@ -1,4 +1,4 @@
import type { CoID, RawCoValue } from "cojson";
import { type CoID, RawAccount, type RawCoValue, RawGroup } from "cojson";
import { type Account } from "../coValues/account.js";
import type {
AnonymousJazzAgent,
@@ -27,12 +27,42 @@ export class Ref<out V extends CoValue> {
}
}
get value() {
const node =
"node" in this.controlledAccount
? this.controlledAccount.node
: this.controlledAccount._raw.core.node;
private getNode() {
return "node" in this.controlledAccount
? this.controlledAccount.node
: this.controlledAccount._raw.core.node;
}
hasReadAccess() {
const node = this.getNode();
const raw = node.getLoaded(this.id as unknown as CoID<RawCoValue>);
if (!raw) {
return true;
}
if (raw instanceof RawAccount || raw instanceof RawGroup) {
return true;
}
const group = raw.core.getGroup();
if (group instanceof RawAccount) {
if (node.account.id !== group.id) {
return false;
}
} else if (group.myRole() === undefined) {
return false;
}
return true;
}
getValueWithoutAccessCheck() {
const node = this.getNode();
const raw = node.getLoaded(this.id as unknown as CoID<RawCoValue>);
if (raw) {
return coValuesCache.get(raw, () =>
instantiateRefEncoded(this.schema, raw),
@@ -42,6 +72,14 @@ export class Ref<out V extends CoValue> {
}
}
get value() {
if (!this.hasReadAccess()) {
return null;
}
return this.getValueWithoutAccessCheck();
}
private async loadHelper(): Promise<V | "unavailable"> {
const node =
"node" in this.controlledAccount
@@ -100,7 +138,7 @@ export class Ref<out V extends CoValue> {
} else if (this.value !== null) {
const freshValueInstance = instantiateRefEncoded(
this.schema,
this.value?._raw,
this.value._raw,
);
TRACE_ACCESSES && console.log("freshValueInstance", freshValueInstance);
subScope.cachedValues[this.id] = freshValueInstance;

View File

@@ -247,7 +247,9 @@ describe("ContextManager", () => {
provider: "test",
});
const me = await CustomAccount.getMe().ensureLoaded({ root: {} });
const me = await CustomAccount.getMe().ensureLoaded({
resolve: { root: true },
});
expect(me.root.id).toBe(lastRootId);
});
@@ -266,7 +268,7 @@ describe("ContextManager", () => {
value: 1,
});
} else {
const { root } = await this.ensureLoaded({ root: {} });
const { root } = await this.ensureLoaded({ resolve: { root: true } });
root.value = 2;
}
@@ -289,7 +291,9 @@ describe("ContextManager", () => {
provider: "test",
});
const me = await CustomAccount.getMe().ensureLoaded({ root: {} });
const me = await CustomAccount.getMe().ensureLoaded({
resolve: { root: true },
});
expect(me.root.value).toBe(2);
});
@@ -316,10 +320,16 @@ describe("ContextManager", () => {
anonymousAccount: CustomAccount,
) => {
const anonymousAccountWithRoot = await anonymousAccount.ensureLoaded({
root: {},
resolve: {
root: true,
},
});
const meWithRoot = await CustomAccount.getMe().ensureLoaded({ root: {} });
const meWithRoot = await CustomAccount.getMe().ensureLoaded({
resolve: {
root: true,
},
});
const rootToTransfer = anonymousAccountWithRoot.root;
@@ -347,7 +357,11 @@ describe("ContextManager", () => {
provider: "test",
});
const me = await CustomAccount.getMe().ensureLoaded({ root: {} });
const me = await CustomAccount.getMe().ensureLoaded({
resolve: {
root: true,
},
});
expect(me.root.transferredRoot?.value).toBe("Hello");
});

View File

@@ -152,7 +152,9 @@ describe("PassphraseAuth", () => {
// Verify the account name was set
const { profile } = await account.ensureLoaded({
profile: {},
resolve: {
profile: true,
},
});
expect(profile.name).toBe(testName);

View File

@@ -124,15 +124,16 @@ describe("CoFeed resolution", async () => {
crypto: Crypto,
});
const loadedStream = await TestStream.load(stream.id, meOnSecondPeer, []);
const loadedStream = await TestStream.load(stream.id, {
loadAs: meOnSecondPeer,
});
expect(loadedStream?.[me.id]?.value).toEqual(null);
expect(loadedStream?.[me.id]?.ref?.id).toEqual(stream[me.id]?.value?.id);
const loadedNestedStream = await NestedStream.load(
stream[me.id]!.value!.id,
meOnSecondPeer,
[],
{ loadAs: meOnSecondPeer },
);
// expect(loadedStream?.[me.id]?.value).toEqual(loadedNestedStream);
@@ -148,8 +149,7 @@ describe("CoFeed resolution", async () => {
const loadedTwiceNestedStream = await TwiceNestedStream.load(
stream[me.id]!.value![me.id]!.value!.id,
meOnSecondPeer,
[],
{ loadAs: meOnSecondPeer },
);
// expect(loadedStream?.[me.id]?.value?.[me.id]?.value).toEqual(
@@ -212,9 +212,13 @@ describe("CoFeed resolution", async () => {
const queue = new cojsonInternals.Channel();
TestStream.subscribe(stream.id, meOnSecondPeer, [], (subscribedStream) => {
void queue.push(subscribedStream);
});
TestStream.subscribe(
stream.id,
{ loadAs: meOnSecondPeer },
(subscribedStream) => {
void queue.push(subscribedStream);
},
);
const update1 = (await queue.next()).value;
expect(update1[me.id]?.value).toEqual(null);
@@ -330,7 +334,9 @@ describe("FileStream loading & Subscription", async () => {
crypto: Crypto,
});
const loadedStream = await FileStream.load(stream.id, meOnSecondPeer, []);
const loadedStream = await FileStream.load(stream.id, {
loadAs: meOnSecondPeer,
});
expect(loadedStream?.getChunks()).toEqual({
mimeType: "text/plain",
@@ -364,9 +370,13 @@ describe("FileStream loading & Subscription", async () => {
const queue = new cojsonInternals.Channel();
FileStream.subscribe(stream.id, meOnSecondPeer, [], (subscribedStream) => {
void queue.push(subscribedStream);
});
FileStream.subscribe(
stream.id,
{ loadAs: meOnSecondPeer },
(subscribedStream) => {
void queue.push(subscribedStream);
},
);
const update1 = (await queue.next()).value;
expect(update1.getChunks()).toBe(undefined);
@@ -435,9 +445,7 @@ describe("FileStream.loadAsBlob", async () => {
const { stream, me } = await setup();
stream.push(new Uint8Array([1]));
const promise = FileStream.loadAsBlob(stream.id, me);
await stream.ensureLoaded([]);
const promise = FileStream.loadAsBlob(stream.id, { loadAs: me });
stream.push(new Uint8Array([2]));
stream.end();
@@ -453,17 +461,16 @@ describe("FileStream.loadAsBlob", async () => {
const { stream, me } = await setup();
stream.push(new Uint8Array([1]));
const promise = FileStream.loadAsBlob(stream.id, me, {
const promise = FileStream.loadAsBlob(stream.id, {
loadAs: me,
allowUnfinished: true,
});
await stream.ensureLoaded([]);
const blob = await promise;
stream.push(new Uint8Array([2]));
stream.end();
const blob = await promise;
// The promise resolves before the stream is ended
// so we get a blob only with the first chunk
expect(blob?.size).toBe(1);

View File

@@ -508,16 +508,14 @@ describe("CoList resolution", async () => {
crypto: Crypto,
});
const loadedList = await TestList.load(list.id, meOnSecondPeer, []);
const loadedList = await TestList.load(list.id, { loadAs: meOnSecondPeer });
expect(loadedList?.[0]).toBe(null);
expect(loadedList?._refs[0]?.id).toEqual(list[0]!.id);
const loadedNestedList = await NestedList.load(
list[0]!.id,
meOnSecondPeer,
[],
);
const loadedNestedList = await NestedList.load(list[0]!.id, {
loadAs: meOnSecondPeer,
});
expect(loadedList?.[0]).toBeDefined();
expect(loadedList?.[0]?.[0]).toBe(null);
@@ -528,11 +526,9 @@ describe("CoList resolution", async () => {
loadedNestedList?.toJSON(),
);
const loadedTwiceNestedList = await TwiceNestedList.load(
list[0]![0]!.id,
meOnSecondPeer,
[],
);
const loadedTwiceNestedList = await TwiceNestedList.load(list[0]![0]!.id, {
loadAs: meOnSecondPeer,
});
expect(loadedList?.[0]?.[0]).toBeDefined();
expect(loadedList?.[0]?.[0]?.[0]).toBe("a");
@@ -582,13 +578,17 @@ describe("CoList resolution", async () => {
const queue = new cojsonInternals.Channel();
TestList.subscribe(list.id, meOnSecondPeer, [], (subscribedList) => {
console.log(
"subscribedList?.[0]?.[0]?.[0]",
subscribedList?.[0]?.[0]?.[0],
);
void queue.push(subscribedList);
});
TestList.subscribe(
list.id,
{ loadAs: meOnSecondPeer },
(subscribedList) => {
console.log(
"subscribedList?.[0]?.[0]?.[0]",
subscribedList?.[0]?.[0]?.[0],
);
void queue.push(subscribedList);
},
);
const update1 = (await queue.next()).value;
expect(update1?.[0]).toBe(null);

View File

@@ -12,7 +12,7 @@ import {
} from "../index.js";
import { setupTwoNodes } from "./utils.js";
const connectedPeers = cojsonInternals.connectedPeers;
const { connectedPeers } = cojsonInternals;
const Crypto = await WasmCrypto.create();
@@ -444,7 +444,7 @@ describe("CoMap resolution", async () => {
crypto: Crypto,
});
const loadedMap = await TestMap.load(map.id, meOnSecondPeer, {});
const loadedMap = await TestMap.load(map.id, { loadAs: meOnSecondPeer });
expect(loadedMap?.color).toEqual("red");
expect(loadedMap?.height).toEqual(10);
@@ -452,11 +452,9 @@ describe("CoMap resolution", async () => {
expect(loadedMap?._refs.nested?.id).toEqual(map.nested?.id);
expect(loadedMap?._refs.nested?.value).toEqual(null);
const loadedNestedMap = await NestedMap.load(
map.nested!.id,
meOnSecondPeer,
{},
);
const loadedNestedMap = await NestedMap.load(map.nested!.id, {
loadAs: meOnSecondPeer,
});
expect(loadedMap?.nested?.name).toEqual("nested");
expect(loadedMap?.nested?._fancyName).toEqual("Sir nested");
@@ -465,8 +463,7 @@ describe("CoMap resolution", async () => {
const loadedTwiceNestedMap = await TwiceNestedMap.load(
map.nested!.twiceNested!.id,
meOnSecondPeer,
{},
{ loadAs: meOnSecondPeer },
);
expect(loadedMap?.nested?.twiceNested?.taste).toEqual("sour");
@@ -493,7 +490,7 @@ describe("CoMap resolution", async () => {
expect(loadedMap?.nested?._refs.twiceNested?.value).toBeDefined();
});
test("Subscription & auto-resolution", async () => {
async function setupTest() {
const { me, map } = await initNodeAndMap();
const [initialAsPeer, secondAsPeer] = connectedPeers("initial", "second", {
@@ -518,28 +515,53 @@ describe("CoMap resolution", async () => {
const queue = new cojsonInternals.Channel<TestMap>();
TestMap.subscribe(map.id, meOnSecondPeer, {}, (subscribedMap) => {
await meOnSecondPeer.waitForAllCoValuesSync();
TestMap.subscribe(map.id, { loadAs: meOnSecondPeer }, (subscribedMap) => {
// Read to property to trigger loading
subscribedMap.nested?.twiceNested?.taste;
void queue.push(subscribedMap);
});
return { me, map, meOnSecondPeer, queue };
}
test("initial subscription loads nested data progressively", async () => {
const { queue } = await setupTest();
const update1 = (await queue.next()).value;
expect(update1.nested).toEqual(null);
const update2 = (await queue.next()).value;
expect(update2.nested?.name).toEqual("nested");
});
test("updates to nested properties are received", async () => {
const { map, queue } = await setupTest();
// Skip initial updates
await queue.next();
await queue.next();
map.nested!.name = "nestedUpdated";
const _ = (await queue.next()).value;
await queue.next(); // Skip intermediate update
const update3 = (await queue.next()).value;
expect(update3.nested?.name).toEqual("nestedUpdated");
const oldTwiceNested = update3.nested!.twiceNested;
expect(oldTwiceNested?.taste).toEqual("sour");
});
test("replacing nested object triggers updates", async () => {
const { meOnSecondPeer, queue } = await setupTest();
// Skip initial updates
await queue.next();
await queue.next();
const update3 = (await queue.next()).value;
// When assigning a new nested value, we get an update
const newTwiceNested = TwiceNestedMap.create(
{
taste: "sweet",
@@ -557,14 +579,40 @@ describe("CoMap resolution", async () => {
update3.nested = newNested;
(await queue.next()).value;
// const update4 = (await queue.next()).value;
const update4b = (await queue.next()).value;
await queue.next(); // Skip intermediate update
const update4 = (await queue.next()).value;
expect(update4b.nested?.name).toEqual("newNested");
expect(update4b.nested?.twiceNested?.taste).toEqual("sweet");
expect(update4.nested?.name).toEqual("newNested");
expect(update4.nested?.twiceNested?.taste).toEqual("sweet");
});
test("updates to deeply nested properties are received", async () => {
const { queue } = await setupTest();
// Skip to the point where we have the nested object
await queue.next();
await queue.next();
const update3 = (await queue.next()).value;
const newTwiceNested = TwiceNestedMap.create(
{ taste: "sweet" },
{ owner: update3.nested!._raw.owner },
);
const newNested = NestedMap.create(
{
name: "newNested",
twiceNested: newTwiceNested,
},
{ owner: update3.nested!._raw.owner },
);
update3.nested = newNested;
// Skip intermediate updates
await queue.next();
await queue.next();
// we get updates when the new nested value changes
newTwiceNested.taste = "salty";
const update5 = (await queue.next()).value;
expect(update5.nested?.twiceNested?.taste).toEqual("salty");

View File

@@ -109,7 +109,7 @@ describe("CoPlainText", () => {
});
// Load the text on the second peer
const loaded = await CoPlainText.load(id, meOnSecondPeer);
const loaded = await CoPlainText.load(id, { loadAs: meOnSecondPeer });
expect(loaded).toBeDefined();
expect(loaded!.toString()).toBe("hello world");
});
@@ -142,9 +142,13 @@ describe("CoPlainText", () => {
const queue = new cojsonInternals.Channel();
// Subscribe to text updates
CoPlainText.subscribe(text.id, meOnSecondPeer, (subscribedText) => {
void queue.push(subscribedText);
});
CoPlainText.subscribe(
text.id,
{ loadAs: meOnSecondPeer },
(subscribedText) => {
void queue.push(subscribedText);
},
);
// Initial subscription should give us the text
const update1 = (await queue.next()).value;

View File

@@ -602,17 +602,17 @@ describe("CoRichText", async () => {
crypto: Crypto,
});
const loadedText = await CoRichText.load(text.id, meOnSecondPeer, {
marks: [{}],
text: [],
const loadedText = await CoRichText.load(text.id, {
loadAs: meOnSecondPeer,
resolve: { marks: { $each: true }, text: true },
});
expect(loadedText).toBeDefined();
expect(loadedText?.toString()).toEqual("hello world");
const loadedText2 = await CoRichText.load(text.id, meOnSecondPeer, {
marks: [{}],
text: [],
const loadedText2 = await CoRichText.load(text.id, {
loadAs: meOnSecondPeer,
resolve: { marks: { $each: true }, text: true },
});
expect(loadedText2).toBeDefined();
@@ -646,8 +646,10 @@ describe("CoRichText", async () => {
CoRichText.subscribe(
text.id,
meOnSecondPeer,
{ marks: [{}], text: [] },
{
loadAs: meOnSecondPeer,
resolve: { marks: { $each: true }, text: true },
},
(subscribedText) => {
void queue.push(subscribedText);
},

View File

@@ -1,6 +1,6 @@
import { cojsonInternals } from "cojson";
import { WasmCrypto } from "cojson/crypto/WasmCrypto";
import { describe, expect, expectTypeOf, test, vi } from "vitest";
import { assert, describe, expect, expectTypeOf, test, vi } from "vitest";
import {
Account,
CoFeed,
@@ -15,6 +15,7 @@ import {
isControlledAccount,
} from "../index.js";
import { randomSessionProvider } from "../internal.js";
import { createJazzTestAccount, linkAccounts } from "../testing.js";
import { waitFor } from "./utils.js";
const Crypto = await WasmCrypto.create();
@@ -63,89 +64,104 @@ describe("Deep loading with depth arg", async () => {
crypto: Crypto,
});
test("loading a deeply nested object will wait until all required refs are loaded", async () => {
const ownership = { owner: me };
const map = TestMap.create(
{
list: TestList.create(
[
InnerMap.create(
{
stream: TestStream.create(
[InnermostMap.create({ value: "hello" }, ownership)],
ownership,
),
},
ownership,
),
],
ownership,
),
},
ownership,
);
const ownership = { owner: me };
const map = TestMap.create(
{
list: TestList.create(
[
InnerMap.create(
{
stream: TestStream.create(
[InnermostMap.create({ value: "hello" }, ownership)],
ownership,
),
},
ownership,
),
],
ownership,
),
},
ownership,
);
test("load without resolve", async () => {
const map1 = await TestMap.load(map.id, { loadAs: meOnSecondPeer });
expectTypeOf(map1).toEqualTypeOf<TestMap | null>();
assert(map1, "map1 is null");
const map1 = await TestMap.load(map.id, meOnSecondPeer, {});
expectTypeOf(map1).toEqualTypeOf<TestMap | undefined>();
if (map1 === undefined) {
throw new Error("map1 is undefined");
}
expect(map1.list).toBe(null);
});
const map2 = await TestMap.load(map.id, meOnSecondPeer, { list: [] });
test("load with resolve { list: true }", async () => {
const map2 = await TestMap.load(map.id, {
loadAs: meOnSecondPeer,
resolve: { list: true },
});
expectTypeOf(map2).toEqualTypeOf<
| (TestMap & {
list: TestList;
})
| undefined
| null
>();
if (map2 === undefined) {
throw new Error("map2 is undefined");
}
expect(map2.list).not.toBe(null);
assert(map2, "map2 is null");
expect(map2.list).toBeTruthy();
expect(map2.list[0]).toBe(null);
});
const map3 = await TestMap.load(map.id, meOnSecondPeer, { list: [{}] });
test("load with resolve { list: { $each: true } }", async () => {
const map3 = await TestMap.load(map.id, {
loadAs: meOnSecondPeer,
resolve: { list: { $each: true } },
});
expectTypeOf(map3).toEqualTypeOf<
| (TestMap & {
list: TestList & InnerMap[];
})
| undefined
| null
>();
if (map3 === undefined) {
throw new Error("map3 is undefined");
}
expect(map3.list[0]).not.toBe(null);
assert(map3, "map3 is null");
expect(map3.list[0]).toBeTruthy();
expect(map3.list[0]?.stream).toBe(null);
});
const map3a = await TestMap.load(map.id, meOnSecondPeer, {
optionalRef: {},
test("load with resolve { optionalRef: true }", async () => {
const map3a = await TestMap.load(map.id, {
loadAs: meOnSecondPeer,
resolve: { optionalRef: true } as const,
});
expectTypeOf(map3a).toEqualTypeOf<
| (TestMap & {
optionalRef: InnermostMap | undefined;
})
| undefined
| null
>();
assert(map3a, "map3a is null");
expect(map3a).toBeTruthy();
});
const map4 = await TestMap.load(map.id, meOnSecondPeer, {
list: [{ stream: [] }],
test("load with resolve { list: { $each: { stream: true } } }", async () => {
const map4 = await TestMap.load(map.id, {
loadAs: meOnSecondPeer,
resolve: { list: { $each: { stream: true } } },
});
expectTypeOf(map4).toEqualTypeOf<
| (TestMap & {
list: TestList & (InnerMap & { stream: TestStream })[];
})
| undefined
| null
>();
if (map4 === undefined) {
throw new Error("map4 is undefined");
}
expect(map4.list[0]?.stream).not.toBe(null);
expect(map4.list[0]?.stream?.[me.id]).not.toBe(null);
assert(map4, "map4 is null");
expect(map4.list[0]?.stream).toBeTruthy();
expect(map4.list[0]?.stream?.[me.id]).toBeTruthy();
expect(map4.list[0]?.stream?.byMe?.value).toBe(null);
});
const map5 = await TestMap.load(map.id, meOnSecondPeer, {
list: [{ stream: [{}] }],
test("load with resolve { list: { $each: { stream: { $each: true } } } }", async () => {
const map5 = await TestMap.load(map.id, {
loadAs: meOnSecondPeer,
resolve: { list: { $each: { stream: { $each: true } } } },
});
type ExpectedMap5 =
| (TestMap & {
@@ -164,14 +180,12 @@ describe("Deep loading with depth arg", async () => {
};
})[];
})
| undefined;
| null;
expectTypeOf(map5).toEqualTypeOf<ExpectedMap5>();
if (map5 === undefined) {
throw new Error("map5 is undefined");
}
expect(map5.list[0]?.stream?.[me.id]?.value).not.toBe(null);
expect(map5.list[0]?.stream?.byMe?.value).not.toBe(null);
assert(map5, "map5 is null");
expect(map5.list[0]?.stream?.[me.id]?.value).toBeTruthy();
expect(map5.list[0]?.stream?.byMe?.value).toBeTruthy();
});
});
@@ -200,8 +214,10 @@ class CustomAccount extends Account {
}
const thisLoaded = await this.ensureLoaded({
profile: { stream: [] },
root: { list: [] },
resolve: {
profile: { stream: true },
root: { list: true },
},
});
expectTypeOf(thisLoaded).toEqualTypeOf<
CustomAccount & {
@@ -223,8 +239,10 @@ test("Deep loading within account", async () => {
});
const meLoaded = await me.ensureLoaded({
profile: { stream: [] },
root: { list: [] },
resolve: {
profile: { stream: true },
root: { list: true },
},
});
expectTypeOf(meLoaded).toEqualTypeOf<
CustomAccount & {
@@ -237,8 +255,8 @@ test("Deep loading within account", async () => {
}
>();
expect(meLoaded.profile.stream).not.toBe(null);
expect(meLoaded.root.list).not.toBe(null);
expect(meLoaded.profile.stream).toBeTruthy();
expect(meLoaded.root.list).toBeTruthy();
});
class RecordLike extends CoMap.Record(co.ref(TestMap)) {}
@@ -284,24 +302,242 @@ test("Deep loading a record-like coMap", async () => {
{ owner: me },
);
const recordLoaded = await RecordLike.load(record.id, meOnSecondPeer, [
{ list: [{}] },
]);
const recordLoaded = await RecordLike.load(record.id, {
loadAs: meOnSecondPeer,
resolve: {
$each: { list: { $each: true } },
},
});
expectTypeOf(recordLoaded).toEqualTypeOf<
| (RecordLike & {
[key: string]: TestMap & {
list: TestList & InnerMap[];
};
})
| undefined
| null
>();
if (recordLoaded === undefined) {
throw new Error("recordLoaded is undefined");
}
assert(recordLoaded, "recordLoaded is null");
expect(recordLoaded.key1?.list).not.toBe(null);
expect(recordLoaded.key1?.list).not.toBe(undefined);
expect(recordLoaded.key1?.list).toBeTruthy();
expect(recordLoaded.key2?.list).not.toBe(null);
expect(recordLoaded.key2?.list).not.toBe(undefined);
expect(recordLoaded.key2?.list).toBeTruthy();
});
test("The resolve type doesn't accept extra keys", async () => {
expect.assertions(1);
const me = await CustomAccount.create({
creationProps: { name: "Hermes Puggington" },
crypto: Crypto,
});
try {
const meLoaded = await me.ensureLoaded({
resolve: {
// @ts-expect-error
profile: { stream: true, extraKey: true },
// @ts-expect-error
root: { list: true, extraKey: true },
},
});
await me.ensureLoaded({
resolve: {
// @ts-expect-error
root: { list: { $each: true, extraKey: true } },
},
});
await me.ensureLoaded({
resolve: {
root: { list: true },
// @ts-expect-error
extraKey: true,
},
});
expectTypeOf(meLoaded).toEqualTypeOf<
CustomAccount & {
profile: CustomProfile & {
stream: TestStream;
extraKey: never;
};
root: TestMap & {
list: TestList;
extraKey: never;
};
}
>();
} catch (e) {
expect(e).toBeInstanceOf(Error);
}
});
describe("Deep loading with unauthorized account", async () => {
const bob = await createJazzTestAccount({
creationProps: { name: "Bob" },
});
const alice = await createJazzTestAccount({
creationProps: { name: "Alice" },
});
linkAccounts(bob, alice);
await alice.waitForAllCoValuesSync();
const onlyBob = bob;
const group = Group.create(bob);
group.addMember(alice, "reader");
test("unaccessible root", async () => {
const map = TestMap.create({ list: TestList.create([], group) }, onlyBob);
const mapOnAlice = await TestMap.load(map.id, { loadAs: alice });
expect(mapOnAlice).toBe(null);
});
test("unaccessible list", async () => {
const map = TestMap.create({ list: TestList.create([], onlyBob) }, group);
const mapOnAlice = await TestMap.load(map.id, { loadAs: alice });
expect(mapOnAlice).toBeTruthy();
const mapWithListOnAlice = await TestMap.load(map.id, {
resolve: { list: true },
loadAs: alice,
});
expect(mapWithListOnAlice).toBe(null);
});
test("unaccessible list element", async () => {
const map = TestMap.create(
{
list: TestList.create(
[
InnerMap.create(
{
stream: TestStream.create([], group),
},
onlyBob,
),
],
group,
),
},
group,
);
const mapOnAlice = await TestMap.load(map.id, {
resolve: { list: { $each: true } },
loadAs: alice,
});
expect(mapOnAlice).toBe(null);
});
test("unaccessible optional element", async () => {
const map = TestMap.create(
{
list: TestList.create([], group),
optionalRef: InnermostMap.create({ value: "hello" }, onlyBob),
},
group,
);
const mapOnAlice = await TestMap.load(map.id, {
loadAs: alice,
resolve: { optionalRef: true } as const,
});
expect(mapOnAlice).toBe(null);
expect(mapOnAlice?.optionalRef).toBe(undefined);
expect(mapOnAlice?.optionalRef?.value).toBe(undefined);
});
test("unaccessible optional element via autoload", async () => {
const map = TestMap.create(
{
list: TestList.create([], group),
optionalRef: InnermostMap.create({ value: "hello" }, onlyBob),
},
group,
);
const mapOnAlice = await TestMap.load(map.id, {
loadAs: alice,
resolve: { list: true } as const,
});
assert(mapOnAlice, "Alice isn't able to load the map");
const result = await new Promise((resolve) => {
const unsub = mapOnAlice.subscribe((value) => {
resolve(value.optionalRef);
unsub();
});
});
expect(result).toBe(null);
});
test("unaccessible stream", async () => {
const map = TestMap.create(
{
list: TestList.create(
[
InnerMap.create(
{
stream: TestStream.create([], onlyBob),
},
group,
),
],
group,
),
},
group,
);
const mapOnAlice = await TestMap.load(map.id, {
resolve: { list: { $each: { stream: true } } },
loadAs: alice,
});
expect(mapOnAlice).toBe(null);
});
test("unaccessible stream element", async () => {
const map = TestMap.create(
{
list: TestList.create(
[
InnerMap.create(
{
stream: TestStream.create(
[InnermostMap.create({ value: "hello" }, onlyBob)],
group,
),
},
group,
),
],
group,
),
},
group,
);
const mapOnAlice = await TestMap.load(map.id, {
resolve: { list: { $each: { stream: { $each: true } } } },
loadAs: alice,
});
expect(mapOnAlice).toBe(null);
});
});
test("doesn't break on Map.Record key deletion when the key is referenced in the depth", async () => {
@@ -317,7 +553,10 @@ test("doesn't break on Map.Record key deletion when the key is referenced in the
});
const spy = vi.fn();
const unsub = snapStore.subscribe({ profile1: {}, profile2: {} }, spy);
const unsub = snapStore.subscribe(
{ resolve: { profile1: true, profile2: true } },
spy,
);
await waitFor(() => expect(spy).toHaveBeenCalled());
@@ -330,7 +569,9 @@ test("doesn't break on Map.Record key deletion when the key is referenced in the
await expect(
snapStore.ensureLoaded({
profile1: {},
resolve: {
profile1: true,
},
}),
).rejects.toThrow("Failed to deeply load CoValue " + snapStore.id);
});
@@ -357,7 +598,7 @@ test("throw when calling ensureLoaded on a ref that's required but missing", asy
await expect(
root.ensureLoaded({
profile: {},
resolve: { profile: true },
}),
).rejects.toThrow("Failed to deeply load CoValue " + root.id);
});
@@ -374,7 +615,7 @@ test("throw when calling ensureLoaded on a ref that is not defined in the schema
await expect(
root.ensureLoaded({
profile: {},
resolve: { profile: true },
}),
).rejects.toThrow("Failed to deeply load CoValue " + root.id);
});
@@ -399,7 +640,7 @@ test("should not throw when calling ensureLoaded a record with a deleted ref", a
);
let value: any;
let unsub = root.subscribe([{}], (v) => {
let unsub = root.subscribe({ resolve: { $each: true } }, (v) => {
value = v;
});
@@ -412,7 +653,7 @@ test("should not throw when calling ensureLoaded a record with a deleted ref", a
unsub();
value = undefined;
unsub = root.subscribe([{}], (v) => {
unsub = root.subscribe({ resolve: { $each: true } }, (v) => {
value = v;
});

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