@owdproject/nuxt-module-atproto-persistence 0.0.0-stage → 4.0.0-alpha.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,20 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Open Web Desktop Team ~ github.com/owdproject
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
19
+ WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
20
+ IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,71 @@
1
- # Temporary Holding Version
1
+ <p align="center">
2
+ <img width="160" height="160" src="https://avatars.githubusercontent.com/u/201536780?s=160&v=4" />
3
+ </p>
4
+ <h1 align="center">ATProto Persistence Module</h1>
5
+ <h3 align="center">
6
+ Hybrid Pinia persistence for Open Web Desktop: local-first with AT Protocol sync.
7
+ </h3>
2
8
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
9
+ ## Overview
10
+
11
+ This module registers a Pinia persisted-state adapter backed by **IndexedDB**
12
+ (`idb-keyval`) with optional sync to the user's AT Protocol repository. It
13
+ replaces `@owdproject/nuxt-module-pinia-persistence` — **do not install both** in the same
14
+ desktop.
15
+
16
+ Boot order is handled without core coupling: the plugin runs in Nuxt's **pre**
17
+ phase (registers the adapter only). Remote hydration runs **lazily** on the first
18
+ `getItem`, after the `atproto` OAuth plugin has finished init. Core and apps
19
+ already await `$persistedState.isReady()` before restoring windows.
20
+
21
+ ## Requirements
22
+
23
+ - `@owdproject/core` ^3.4.0
24
+ - `@owdproject/module-atproto` (provides OAuth session and agents)
25
+
26
+ ## Installation
27
+
28
+ ```bash
29
+ pnpm desktop add module-atproto-persistence
30
+ ```
31
+
32
+ ## Configuration
33
+
34
+ ```ts
35
+ // desktop/desktop.config.ts
36
+ export default defineDesktopConfig({
37
+ modules: [
38
+ '@owdproject/module-atproto',
39
+ '@owdproject/module-atproto-persistence',
40
+ ],
41
+ atprotoPersistence: {
42
+ // Load atprotoDesktop.owner.did remote state on boot (not only /actor/:did)
43
+ loadOwnerDesktopOnMounted: false,
44
+ },
45
+ })
46
+ ```
47
+
48
+ ## Actor resolution (remote hydrate)
49
+
50
+ On first store read, remote state is fetched once per boot when an actor DID is
51
+ resolved:
52
+
53
+ 1. Route `/actor/:did` — view another actor's desktop
54
+ 2. Logged-in session — `session.sub`
55
+ 3. `loadOwnerDesktopOnMounted: true` — `atprotoDesktop.owner.did`
56
+ 4. Otherwise — IndexedDB only
57
+
58
+ ## AT Protocol collections
59
+
60
+ | Pinia store id | AT Proto collection | rkey |
61
+ |---|---|---|
62
+ | `desktop` | `org.owdproject.desktop` | `self` |
63
+ | `desktop/application/<appId>/windows` | `org.owdproject.application.windows` | `<appId>` |
64
+ | `desktop/application/<appId>/meta` | `org.owdproject.application.meta` | `<appId>` |
65
+
66
+ When logged in, mapped keys are written to the repo on change (`putRecord`).
67
+ Unmapped keys stay local-only.
68
+
69
+ ## License
70
+
71
+ This module is released under the [MIT License](LICENSE).
@@ -0,0 +1,5 @@
1
+ import { NuxtModule } from '@nuxt/schema';
2
+
3
+ declare const module$1: NuxtModule<any>;
4
+
5
+ export { module$1 as default };
@@ -0,0 +1,9 @@
1
+ {
2
+ "name": "desktop-module-atproto-persistence",
3
+ "configKey": "atprotoPersistence",
4
+ "version": "4.0.0-alpha.3",
5
+ "builder": {
6
+ "@nuxt/module-builder": "1.0.3",
7
+ "unbuild": "3.6.1"
8
+ }
9
+ }
@@ -0,0 +1,21 @@
1
+ import { createResolver, addPlugin } from '@nuxt/kit';
2
+ import { defineDesktopModule } from '@owdproject/nuxt/kit';
3
+
4
+ const module$1 = defineDesktopModule({
5
+ meta: {
6
+ name: "desktop-module-atproto-persistence",
7
+ configKey: "atprotoPersistence"
8
+ },
9
+ defaults: {
10
+ loadOwnerDesktopOnMounted: false
11
+ },
12
+ setup(_options, _nuxt) {
13
+ const { resolve } = createResolver(import.meta.url);
14
+ addPlugin({
15
+ src: resolve("./runtime/plugin"),
16
+ mode: "client"
17
+ });
18
+ }
19
+ });
20
+
21
+ export { module$1 as default };
@@ -0,0 +1,2 @@
1
+ declare const _default: import("nuxt/app").Plugin<Record<string, unknown>> & import("nuxt/app").ObjectPlugin<Record<string, unknown>>;
2
+ export default _default;
@@ -0,0 +1,100 @@
1
+ import { createPersistedStatePlugin } from "pinia-plugin-persistedstate-2";
2
+ import { defineNuxtPlugin } from "nuxt/app";
3
+ function deepEqual(obj1, obj2) {
4
+ if (obj1 === obj2) return true;
5
+ if (!obj1 || !obj2 || typeof obj1 !== "object" || typeof obj2 !== "object") return false;
6
+ const keys1 = Object.keys(obj1);
7
+ const keys2 = Object.keys(obj2);
8
+ if (keys1.length !== keys2.length) return false;
9
+ for (const key of keys1) {
10
+ if (!Object.prototype.hasOwnProperty.call(obj2, key)) return false;
11
+ if (!deepEqual(obj1[key], obj2[key])) return false;
12
+ }
13
+ return true;
14
+ }
15
+ import { useAtprotoSession, useAtprotoAgent } from "#imports";
16
+ import { get, set, del } from "idb-keyval";
17
+ import {
18
+ putAtprotoApplicationState,
19
+ parseAtprotoStoreKey
20
+ } from "./utils/utilAtprotoApplicationStates.js";
21
+ import { ensureActorStatesLoaded } from "./utils/utilAtprotoPersistenceLoad.js";
22
+ function mapStoreKey(key) {
23
+ if (key === "desktop") {
24
+ return "owd/desktop";
25
+ }
26
+ if (key.startsWith("desktop/application/")) {
27
+ return key.replace(/^desktop\/application\//, "owd/application/");
28
+ }
29
+ if (key.startsWith("desktop/")) {
30
+ return key.replace(/^desktop\//, "owd/desktop/");
31
+ }
32
+ return key;
33
+ }
34
+ export default defineNuxtPlugin({
35
+ name: "desktop-plugin-atproto-persistence",
36
+ dependsOn: ["pinia", "atproto"],
37
+ enforce: "pre",
38
+ async setup(nuxtApp) {
39
+ const pinia = nuxtApp.$pinia;
40
+ if (!pinia) {
41
+ return;
42
+ }
43
+ await ensureActorStatesLoaded(nuxtApp);
44
+ pinia.use(
45
+ createPersistedStatePlugin({
46
+ persist: false,
47
+ storage: {
48
+ getItem: async (piniaKey) => {
49
+ const remote = await ensureActorStatesLoaded(nuxtApp);
50
+ const mappedKey = mapStoreKey(piniaKey);
51
+ if (Object.prototype.hasOwnProperty.call(remote, mappedKey)) {
52
+ return JSON.stringify(remote[mappedKey]);
53
+ }
54
+ const value = await get(piniaKey);
55
+ return value ?? null;
56
+ },
57
+ setItem: async (piniaKey, piniaValue) => {
58
+ const previousPiniaValue = await get(piniaKey) ?? null;
59
+ await set(piniaKey, piniaValue);
60
+ const atprotoTargetRecord = parseAtprotoStoreKey(piniaKey);
61
+ if (!atprotoTargetRecord) {
62
+ return piniaValue;
63
+ }
64
+ const { isLogged } = nuxtApp.runWithContext(() => useAtprotoSession());
65
+ if (!isLogged.value) {
66
+ return piniaValue;
67
+ }
68
+ const { collection, rkey } = atprotoTargetRecord;
69
+ try {
70
+ const currentObj = JSON.parse(piniaValue);
71
+ const previousObj = previousPiniaValue ? JSON.parse(previousPiniaValue) : null;
72
+ if (previousObj && deepEqual(currentObj, previousObj)) {
73
+ return piniaValue;
74
+ }
75
+ } catch {
76
+ if (piniaValue === previousPiniaValue) {
77
+ return piniaValue;
78
+ }
79
+ }
80
+ const agent = nuxtApp.runWithContext(() => useAtprotoAgent("authenticated"));
81
+ return putAtprotoApplicationState(
82
+ agent,
83
+ agent.assertDid,
84
+ collection,
85
+ rkey,
86
+ JSON.parse(piniaValue)
87
+ ).then(() => {
88
+ return piniaValue;
89
+ }).catch(() => {
90
+ return piniaValue;
91
+ });
92
+ },
93
+ removeItem: async (key) => {
94
+ await del(key);
95
+ }
96
+ }
97
+ })
98
+ );
99
+ }
100
+ });
@@ -0,0 +1,24 @@
1
+ /** Resolve PDS endpoint via PLC directory (Bluesky); custom PDSs use the same DID document shape. */
2
+ export declare function resolveActorServiceEndpoint(did: string): Promise<string>;
3
+ /**
4
+ * Maps a Pinia store id to an AT Protocol collection and rkey.
5
+ *
6
+ * Key format → AT Proto mapping:
7
+ * - `desktop/application/<appId>/windows` → collection: `org.owdproject.application.windows`, rkey: `<appId>`
8
+ * - `desktop/application/<appId>/meta` → collection: `org.owdproject.application.meta`, rkey: `<appId>`
9
+ * - `desktop` (or `desktop/<sub>`) → collection: `org.owdproject.desktop`, rkey: `self` (or `<sub>`)
10
+ *
11
+ * Returns `null` for keys that are not persisted to AT Proto.
12
+ */
13
+ export declare function parseAtprotoStoreKey(key: string): {
14
+ collection: string;
15
+ rkey: string;
16
+ } | null;
17
+ export declare function listAtprotoApplicationStateRecords(agent: any, repo: string, collection: string): any;
18
+ export declare function getAtprotoApplicationState(agent: any, repo: string, collection: string, rkey: string): any;
19
+ export declare function putAtprotoApplicationState(agent: any, repo: string, collection: string, rkey: string, record: any): any;
20
+ /**
21
+ * Loads the full desktop state map for a given actor from the AT Protocol
22
+ * repository. Returns a map keyed by Pinia store id (`desktop/` prefix).
23
+ */
24
+ export declare function loadActorDesktopStateMap(nuxtApp: any, actorDid: string): Promise<Record<string, any>>;
@@ -0,0 +1,110 @@
1
+ import { useAtprotoAgent, useAtprotoSession } from "#imports";
2
+ export async function resolveActorServiceEndpoint(did) {
3
+ const response = await fetch(`https://plc.directory/${did}`);
4
+ if (!response.ok) {
5
+ throw new Error("Failed to fetch profile service endpoint");
6
+ }
7
+ const data = await response.json();
8
+ return data.service[0].serviceEndpoint;
9
+ }
10
+ export function parseAtprotoStoreKey(key) {
11
+ if (key.startsWith("desktop/application/")) {
12
+ const parts = key.split("/");
13
+ const last = parts[parts.length - 1];
14
+ if (last === "windows" || last === "meta") {
15
+ const appId = parts.slice(2, -1).join("/");
16
+ return {
17
+ collection: `org.owdproject.application.${last}`,
18
+ rkey: appId
19
+ };
20
+ }
21
+ }
22
+ if (key === "desktop" || key.startsWith("desktop/")) {
23
+ const sub = key.split("/")[1] ?? "self";
24
+ if (!key.startsWith("desktop/application/")) {
25
+ return {
26
+ collection: "org.owdproject.desktop",
27
+ rkey: sub
28
+ };
29
+ }
30
+ }
31
+ return null;
32
+ }
33
+ export function listAtprotoApplicationStateRecords(agent, repo, collection) {
34
+ return agent.com.atproto.repo.listRecords({
35
+ repo,
36
+ collection
37
+ }).then((response) => response.data).then((data) => data.records).catch(() => []);
38
+ }
39
+ export function getAtprotoApplicationState(agent, repo, collection, rkey) {
40
+ return agent.com.atproto.repo.getRecord({
41
+ repo,
42
+ collection,
43
+ rkey
44
+ });
45
+ }
46
+ export function putAtprotoApplicationState(agent, repo, collection, rkey, record) {
47
+ return agent.com.atproto.repo.putRecord({
48
+ repo,
49
+ collection,
50
+ rkey,
51
+ record
52
+ });
53
+ }
54
+ export async function loadActorDesktopStateMap(nuxtApp, actorDid) {
55
+ const { isLogged, session } = nuxtApp.runWithContext(() => useAtprotoSession());
56
+ const isOwner = isLogged.value && session.value?.sub === actorDid;
57
+ let actorAgent;
58
+ if (isOwner) {
59
+ actorAgent = nuxtApp.runWithContext(() => useAtprotoAgent("authenticated"));
60
+ } else {
61
+ const actorServiceEndpoint = await resolveActorServiceEndpoint(actorDid);
62
+ actorAgent = nuxtApp.runWithContext(() => useAtprotoAgent(actorServiceEndpoint));
63
+ }
64
+ const [
65
+ atprotoActorDesktopList,
66
+ atprotoApplicationWindowsList,
67
+ atprotoApplicationMetaList
68
+ ] = await Promise.allSettled([
69
+ listAtprotoApplicationStateRecords(
70
+ actorAgent,
71
+ actorDid,
72
+ "org.owdproject.desktop"
73
+ ),
74
+ listAtprotoApplicationStateRecords(
75
+ actorAgent,
76
+ actorDid,
77
+ "org.owdproject.application.windows"
78
+ ),
79
+ listAtprotoApplicationStateRecords(
80
+ actorAgent,
81
+ actorDid,
82
+ "org.owdproject.application.meta"
83
+ )
84
+ ]);
85
+ const stateMap = {};
86
+ if (atprotoActorDesktopList.status === "fulfilled") {
87
+ for (const record of atprotoActorDesktopList.value) {
88
+ const rkey = record.uri.split("/").pop();
89
+ const piniaKey = rkey === "self" ? "owd/desktop" : `owd/desktop/${rkey}`;
90
+ stateMap[piniaKey] = record.value;
91
+ }
92
+ }
93
+ if (atprotoApplicationWindowsList.status === "fulfilled") {
94
+ for (const record of atprotoApplicationWindowsList.value) {
95
+ const appId = record.uri.split("/").pop();
96
+ stateMap[`owd/application/${appId}/windows`] = {
97
+ windows: record.value.windows
98
+ };
99
+ }
100
+ }
101
+ if (atprotoApplicationMetaList.status === "fulfilled") {
102
+ for (const record of atprotoApplicationMetaList.value) {
103
+ const appId = record.uri.split("/").pop();
104
+ stateMap[`owd/application/${appId}/meta`] = {
105
+ ...record.value
106
+ };
107
+ }
108
+ }
109
+ return stateMap;
110
+ }
@@ -0,0 +1,5 @@
1
+ /** Wait until the nuxt-atproto plugin has finished OAuth init (or timeout as guest). */
2
+ export declare function waitForAtprotoReady(nuxtApp: any): Promise<void>;
3
+ export declare function resolveRestoreActorDid(nuxtApp: any): Promise<string | undefined>;
4
+ /** One remote fetch per boot; subsequent getItem calls reuse the same promise. */
5
+ export declare function ensureActorStatesLoaded(nuxtApp: any): Promise<Record<string, unknown>>;
@@ -0,0 +1,56 @@
1
+ import { useAtprotoSession } from "#imports";
2
+ import { useRouter, useRuntimeConfig } from "nuxt/app";
3
+ import { loadActorDesktopStateMap } from "./utilAtprotoApplicationStates.js";
4
+ const ATPROTO_READY_TIMEOUT_MS = 2e3;
5
+ const ATPROTO_READY_POLL_MS = 10;
6
+ function sleep(ms) {
7
+ return new Promise((resolve) => setTimeout(resolve, ms));
8
+ }
9
+ export async function waitForAtprotoReady(nuxtApp) {
10
+ const deadline = Date.now() + ATPROTO_READY_TIMEOUT_MS;
11
+ while (Date.now() < deadline) {
12
+ const $atproto = nuxtApp.$atproto;
13
+ if ($atproto && $atproto.status.value !== "initializing") {
14
+ return;
15
+ }
16
+ await sleep(ATPROTO_READY_POLL_MS);
17
+ }
18
+ }
19
+ export async function resolveRestoreActorDid(nuxtApp) {
20
+ const router = nuxtApp.runWithContext(() => useRouter());
21
+ await router.isReady();
22
+ const routeDid = router.currentRoute.value.params.did;
23
+ if (typeof routeDid === "string" && routeDid.length > 0) {
24
+ return routeDid;
25
+ }
26
+ const { isLogged, session } = nuxtApp.runWithContext(() => useAtprotoSession());
27
+ if (isLogged.value && session.value?.sub) {
28
+ return session.value.sub;
29
+ }
30
+ const runtimeConfig = nuxtApp.runWithContext(() => useRuntimeConfig());
31
+ const desktop = runtimeConfig.public.desktop;
32
+ if (desktop.atprotoPersistence?.loadOwnerDesktopOnMounted) {
33
+ return desktop.atprotoDesktop?.owner?.did;
34
+ }
35
+ return void 0;
36
+ }
37
+ let actorStatesPromise = null;
38
+ async function loadActorStatesOnce(nuxtApp) {
39
+ await waitForAtprotoReady(nuxtApp);
40
+ const actorDid = await resolveRestoreActorDid(nuxtApp);
41
+ if (!actorDid) {
42
+ return {};
43
+ }
44
+ try {
45
+ const states = await loadActorDesktopStateMap(nuxtApp, actorDid);
46
+ return states;
47
+ } catch (err) {
48
+ return {};
49
+ }
50
+ }
51
+ export function ensureActorStatesLoaded(nuxtApp) {
52
+ if (!actorStatesPromise) {
53
+ actorStatesPromise = loadActorStatesOnce(nuxtApp);
54
+ }
55
+ return actorStatesPromise;
56
+ }
@@ -0,0 +1,7 @@
1
+ import type { NuxtModule } from '@nuxt/schema'
2
+
3
+ import type { default as Module } from './module.mjs'
4
+
5
+ export type ModuleOptions = typeof Module extends NuxtModule<infer O> ? Partial<O> : Record<string, any>
6
+
7
+ export { default } from './module.mjs'
package/package.json CHANGED
@@ -1,6 +1,67 @@
1
1
  {
2
2
  "name": "@owdproject/nuxt-module-atproto-persistence",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "4.0.0-alpha.3",
4
+ "description": "Pinia persistence via AT Protocol repository, ESM-friendly",
5
+ "license": "MIT",
6
+ "homepage": "https://github.com/atproto-os/module-atproto-persistence",
7
+ "author": {
8
+ "name": "Open Web Desktop Team",
9
+ "url": "https://github.com/owdproject"
10
+ },
11
+ "type": "module",
12
+ "exports": {
13
+ ".": {
14
+ "types": "./dist/types.d.mts",
15
+ "development": "./src/module.ts",
16
+ "import": "./dist/module.mjs",
17
+ "default": "./dist/module.mjs"
18
+ }
19
+ },
20
+ "main": "./dist/module.mjs",
21
+ "typesVersions": {
22
+ "*": {
23
+ ".": [
24
+ "./dist/types.d.mts"
25
+ ]
26
+ }
27
+ },
28
+ "files": [
29
+ "dist"
30
+ ],
31
+ "nx": {
32
+ "name": "module-atproto-persistence"
33
+ },
34
+ "scripts": {
35
+ "prepack": "nuxt-module-build build",
36
+ "dev": "pnpm run dev:prepare && cd playground && pnpm exec nuxt dev",
37
+ "dev:build": "nuxt build playground",
38
+ "dev:generate": "NUXT_APP_BASE_URL=${NUXT_APP_BASE_URL:-/module-atproto-persistence/} nuxt generate playground",
39
+ "dev:prepare": "nuxt-module-build build --stub && nuxt-module-build prepare && cd playground && pnpm exec nuxt prepare",
40
+ "validate": "desktop validate ."
41
+ },
42
+ "dependencies": {
43
+ "@nuxt/kit": "^4.6.2",
44
+ "idb-keyval": "^6.2.2",
45
+ "pinia-plugin-persistedstate-2": "^2.0.30",
46
+ "@owdproject/nuxt": "^4.0.0-alpha.3"
47
+ },
48
+ "devDependencies": {
49
+ "@nuxt/module-builder": "^1.0.2",
50
+ "@owdproject/nuxt-app-todo": "^4.0.0-alpha.3",
51
+ "@owdproject/core": "^4.0.0-alpha.3",
52
+ "nuxt": "^4.6.2",
53
+ "pinia": "^3.0.0",
54
+ "typescript": "~6.0.3"
55
+ },
56
+ "peerDependencies": {
57
+ "@owdproject/core": "^4.0.0-alpha.3",
58
+ "@owdproject/nuxt-module-atproto": "^4.0.0-alpha.3",
59
+ "pinia": "^3.0.0",
60
+ "@owdproject/nuxt": "^4.0.0-alpha.3"
61
+ },
62
+ "publishConfig": {
63
+ "access": "public",
64
+ "tag": "alpha",
65
+ "registry": "https://registry.npmjs.org/"
66
+ }
67
+ }