@abraca/nuxt 2.85.0 → 2.87.0
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/dist/module.json +1 -1
- package/dist/runtime/components/ADocRenderer.d.vue.ts +9 -0
- package/dist/runtime/components/ADocRenderer.vue +26 -7
- package/dist/runtime/components/ADocRenderer.vue.d.ts +9 -0
- package/dist/runtime/components/AEditor.vue +22 -0
- package/dist/runtime/components/shell/AUserMenu.d.vue.ts +2 -2
- package/dist/runtime/components/shell/AUserMenu.vue.d.ts +2 -2
- package/dist/runtime/components/shell/AUserProfilePopover.d.vue.ts +1 -1
- package/dist/runtime/components/shell/AUserProfilePopover.vue.d.ts +1 -1
- package/dist/runtime/composables/useAAFollowPeer.js +1 -1
- package/dist/runtime/composables/useChildTree.js +8 -1
- package/dist/runtime/composables/useDocSlugs.js +9 -2
- package/dist/runtime/composables/useDocTree.d.ts +1 -0
- package/dist/runtime/composables/useDocTree.js +11 -3
- package/dist/runtime/composables/useDocTreeSnapshot.d.ts +8 -0
- package/dist/runtime/composables/useDocTreeSnapshot.js +5 -0
- package/dist/runtime/composables/useSsrBodyHtml.d.ts +43 -0
- package/dist/runtime/composables/useSsrBodyHtml.js +14 -0
- package/dist/runtime/plugin-abracadabra.server.js +10 -2
- package/dist/runtime/server/plugins/abracadabra-service.js +235 -213
- package/dist/runtime/server/utils/authRetry.d.ts +93 -0
- package/dist/runtime/server/utils/authRetry.js +84 -0
- package/package.json +4 -4
package/dist/module.json
CHANGED
|
@@ -34,6 +34,15 @@ type __VLS_Props = {
|
|
|
34
34
|
label?: string;
|
|
35
35
|
meta?: Record<string, unknown>;
|
|
36
36
|
} | null;
|
|
37
|
+
/**
|
|
38
|
+
* Rendered HTML of this document's BODY from the app's server-side cache.
|
|
39
|
+
*
|
|
40
|
+
* Provided to descendants (see `useSsrBodyHtml`) so `<AEditor>` — which may be
|
|
41
|
+
* several renderer-specific components deep — can paint real prose during SSR
|
|
42
|
+
* instead of its skeleton. Falls back to `/api/_abracadabra/render/:docId`
|
|
43
|
+
* when the app does not pass one.
|
|
44
|
+
*/
|
|
45
|
+
ssrHtml?: string | null;
|
|
37
46
|
/**
|
|
38
47
|
* Forward to editor-type renderers (`doc`/`prose` → <AEditor>): show the
|
|
39
48
|
* built-in sub-page list (<ADocSubPageList>) below the body. Default: true.
|
|
@@ -2,6 +2,8 @@
|
|
|
2
2
|
import { computed, watch, shallowRef } from "vue";
|
|
3
3
|
import { useFetch } from "#imports";
|
|
4
4
|
import { useAbracadabra } from "../composables/useAbracadabra";
|
|
5
|
+
import { useDocTreeSnapshot } from "../composables/useDocTreeSnapshot";
|
|
6
|
+
import { provideSsrBodyHtml } from "../composables/useSsrBodyHtml";
|
|
5
7
|
import { useSpaceConnections } from "../composables/useSpaceConnections";
|
|
6
8
|
import { usePluginRegistry } from "../composables/usePluginRegistry";
|
|
7
9
|
import { useDocumentPermissions } from "../composables/useDocumentPermissions";
|
|
@@ -15,14 +17,26 @@ const props = defineProps({
|
|
|
15
17
|
rendererClass: { type: String, required: false },
|
|
16
18
|
canvasClass: { type: String, required: false, default: "flex flex-col w-full h-[70vh] min-h-[420px]" },
|
|
17
19
|
entry: { type: [Object, null], required: false },
|
|
20
|
+
ssrHtml: { type: [String, null], required: false },
|
|
18
21
|
showSubPages: { type: Boolean, required: false, default: true }
|
|
19
22
|
});
|
|
20
23
|
const abra = useAbracadabra();
|
|
21
24
|
const { resolveEntry, findDocSpaceId, getProviderForDoc, connectSpace, connections } = useSpaceConnections();
|
|
22
25
|
const resolvedEntry = computed(() => resolveEntry(props.docId));
|
|
23
|
-
const
|
|
24
|
-
const
|
|
25
|
-
|
|
26
|
+
const snapshot = useDocTreeSnapshot();
|
|
27
|
+
const snapshotEntry = computed(
|
|
28
|
+
() => snapshot.value?.entries?.[props.docId]
|
|
29
|
+
);
|
|
30
|
+
const docTitle = computed(
|
|
31
|
+
() => props.entry?.label ?? snapshotEntry.value?.label ?? resolvedEntry.value?.label ?? "Untitled"
|
|
32
|
+
);
|
|
33
|
+
const docType = computed(
|
|
34
|
+
() => props.entry?.type ?? snapshotEntry.value?.type ?? resolvedEntry.value?.type ?? "doc"
|
|
35
|
+
);
|
|
36
|
+
const docMeta = computed(
|
|
37
|
+
() => props.entry?.meta ?? snapshotEntry.value?.meta ?? resolvedEntry.value?.meta ?? {}
|
|
38
|
+
);
|
|
39
|
+
const canRenderOffline = computed(() => !!(props.entry?.type ?? snapshotEntry.value?.type));
|
|
26
40
|
const registry = usePluginRegistry();
|
|
27
41
|
const docTypeDef = computed(() => resolveDocType(docType.value, registry));
|
|
28
42
|
const childProvider = shallowRef(null);
|
|
@@ -59,6 +73,10 @@ const { data: ssrContent } = useFetch(
|
|
|
59
73
|
() => `/api/_abracadabra/render/${props.docId}`,
|
|
60
74
|
{ key: `render-${props.docId}`, server: true, lazy: true }
|
|
61
75
|
);
|
|
76
|
+
provideSsrBodyHtml(computed(() => {
|
|
77
|
+
const html = props.ssrHtml || ssrContent.value?.html || "";
|
|
78
|
+
return html ? { docId: props.docId, html } : null;
|
|
79
|
+
}));
|
|
62
80
|
const resolvedClass = computed(
|
|
63
81
|
() => docTypeDef.value.hasEditor ? props.editorClass ?? void 0 : props.rendererClass ?? void 0
|
|
64
82
|
);
|
|
@@ -71,8 +89,8 @@ const wrapperClass = computed(
|
|
|
71
89
|
</script>
|
|
72
90
|
|
|
73
91
|
<template>
|
|
74
|
-
<!-- Loading state -->
|
|
75
|
-
<div v-if="!abra.isReady.value">
|
|
92
|
+
<!-- Loading state — only when we cannot draw the real thing yet. -->
|
|
93
|
+
<div v-if="!abra.isReady.value && !canRenderOffline">
|
|
76
94
|
<!-- SSR: show pre-rendered HTML while client hydrates -->
|
|
77
95
|
<!-- eslint-disable vue/no-v-html -->
|
|
78
96
|
<div
|
|
@@ -94,9 +112,10 @@ const wrapperClass = computed(
|
|
|
94
112
|
</slot>
|
|
95
113
|
</div>
|
|
96
114
|
|
|
97
|
-
<!-- Connection error
|
|
115
|
+
<!-- Connection error. Not while we can still draw from a snapshot: a page
|
|
116
|
+
that renders is better than an alert, and the socket may yet arrive. -->
|
|
98
117
|
<slot
|
|
99
|
-
v-else-if="abra.connectionError.value && !abra.synced.value"
|
|
118
|
+
v-else-if="abra.connectionError.value && !abra.synced.value && !canRenderOffline"
|
|
100
119
|
name="error"
|
|
101
120
|
:error="abra.connectionError.value"
|
|
102
121
|
>
|
|
@@ -34,6 +34,15 @@ type __VLS_Props = {
|
|
|
34
34
|
label?: string;
|
|
35
35
|
meta?: Record<string, unknown>;
|
|
36
36
|
} | null;
|
|
37
|
+
/**
|
|
38
|
+
* Rendered HTML of this document's BODY from the app's server-side cache.
|
|
39
|
+
*
|
|
40
|
+
* Provided to descendants (see `useSsrBodyHtml`) so `<AEditor>` — which may be
|
|
41
|
+
* several renderer-specific components deep — can paint real prose during SSR
|
|
42
|
+
* instead of its skeleton. Falls back to `/api/_abracadabra/render/:docId`
|
|
43
|
+
* when the app does not pass one.
|
|
44
|
+
*/
|
|
45
|
+
ssrHtml?: string | null;
|
|
37
46
|
/**
|
|
38
47
|
* Forward to editor-type renderers (`doc`/`prose` → <AEditor>): show the
|
|
39
48
|
* built-in sub-page list (<ADocSubPageList>) below the body. Default: true.
|
|
@@ -3,6 +3,8 @@ import { shallowRef, ref, watch, watchEffect, computed, nextTick, onBeforeUnmoun
|
|
|
3
3
|
import { useNuxtApp, navigateTo, useRuntimeConfig } from "#imports";
|
|
4
4
|
import { Fragment } from "@tiptap/pm/model";
|
|
5
5
|
import { useSyncedMap } from "../composables/useYDoc";
|
|
6
|
+
import { useSsrBodyHtmlFor } from "../composables/useSsrBodyHtml";
|
|
7
|
+
import { useDocTreeSnapshot } from "../composables/useDocTreeSnapshot";
|
|
6
8
|
import { resolveDocType, GEO_TYPE_META_SCHEMAS } from "../utils/docTypes";
|
|
7
9
|
import { schemaFieldToAttrs, userFieldToAttrs, inferFieldAttrs, AUTO_DETECT_EXCLUDED } from "../extensions/meta-field";
|
|
8
10
|
import { DATE_SIBLING_KEY } from "../utils/dateField";
|
|
@@ -58,6 +60,8 @@ const emit = defineEmits(["ready", "update", "rename", "updateMeta"]);
|
|
|
58
60
|
const model = defineModel({ type: null });
|
|
59
61
|
const { doc, provider, registry, effectiveRole, client } = useNuxtApp().$abracadabra;
|
|
60
62
|
const { connections, getProviderForDoc, getDocForDoc } = useSpaceConnections();
|
|
63
|
+
const ssrBodyHtml = useSsrBodyHtmlFor(() => props.docId);
|
|
64
|
+
const hasSsrDocContext = useDocTreeSnapshot();
|
|
61
65
|
const ownerProvider = computed(() => getProviderForDoc(props.docId) ?? provider.value);
|
|
62
66
|
const ownerDoc = shallowRef(getDocForDoc(props.docId) ?? doc.value);
|
|
63
67
|
watch(() => [doc.value, connections.size], () => {
|
|
@@ -1211,7 +1215,25 @@ function onPlusClick(e, onClick) {
|
|
|
1211
1215
|
</div>
|
|
1212
1216
|
|
|
1213
1217
|
<template #fallback>
|
|
1218
|
+
<!-- The document's real prose, from the app's server-side cache. This
|
|
1219
|
+
is what a crawler indexes and what a cold reader sees first: the
|
|
1220
|
+
body lives in a Y.XmlFragment, which is empty for the whole of SSR,
|
|
1221
|
+
so without it every prose page server-rendered three pulsing grey
|
|
1222
|
+
bars. Falls back to the skeleton only when no cache is available. -->
|
|
1223
|
+
<!-- eslint-disable vue/no-v-html -->
|
|
1214
1224
|
<div
|
|
1225
|
+
v-if="ssrBodyHtml"
|
|
1226
|
+
class="p-6"
|
|
1227
|
+
:class="{ 'prose-variant': variant === 'prose' }"
|
|
1228
|
+
>
|
|
1229
|
+
<div
|
|
1230
|
+
class="prose dark:prose-invert max-w-none"
|
|
1231
|
+
v-html="ssrBodyHtml"
|
|
1232
|
+
/>
|
|
1233
|
+
</div>
|
|
1234
|
+
<!-- eslint-enable vue/no-v-html -->
|
|
1235
|
+
<div
|
|
1236
|
+
v-else-if="!hasSsrDocContext"
|
|
1215
1237
|
class="p-6 space-y-3"
|
|
1216
1238
|
:class="{ 'prose-variant': variant === 'prose' }"
|
|
1217
1239
|
>
|
|
@@ -14,13 +14,13 @@ type __VLS_Props = {
|
|
|
14
14
|
extraItems?: DropdownMenuItem[][];
|
|
15
15
|
};
|
|
16
16
|
declare const __VLS_export: import("vue").DefineComponent<__VLS_Props, {}, {}, {}, {}, import("vue").ComponentOptionsMixin, import("vue").ComponentOptionsMixin, {
|
|
17
|
+
logout: () => any;
|
|
17
18
|
"open-settings": () => any;
|
|
18
19
|
"open-account": () => any;
|
|
19
|
-
logout: () => any;
|
|
20
20
|
}, string, import("vue").PublicProps, Readonly<__VLS_Props> & Readonly<{
|
|
21
|
+
onLogout?: (() => any) | undefined;
|
|
21
22
|
"onOpen-settings"?: (() => any) | undefined;
|
|
22
23
|
"onOpen-account"?: (() => any) | undefined;
|
|
23
|
-
onLogout?: (() => any) | undefined;
|
|
24
24
|
}>, {
|
|
25
25
|
color: string;
|
|
26
26
|
collapsed: boolean;
|
|
@@ -14,13 +14,13 @@ type __VLS_Props = {
|
|
|
14
14
|
extraItems?: DropdownMenuItem[][];
|
|
15
15
|
};
|
|
16
16
|
declare const __VLS_export: import("vue").DefineComponent<__VLS_Props, {}, {}, {}, {}, import("vue").ComponentOptionsMixin, import("vue").ComponentOptionsMixin, {
|
|
17
|
+
logout: () => any;
|
|
17
18
|
"open-settings": () => any;
|
|
18
19
|
"open-account": () => any;
|
|
19
|
-
logout: () => any;
|
|
20
20
|
}, string, import("vue").PublicProps, Readonly<__VLS_Props> & Readonly<{
|
|
21
|
+
onLogout?: (() => any) | undefined;
|
|
21
22
|
"onOpen-settings"?: (() => any) | undefined;
|
|
22
23
|
"onOpen-account"?: (() => any) | undefined;
|
|
23
|
-
onLogout?: (() => any) | undefined;
|
|
24
24
|
}>, {
|
|
25
25
|
color: string;
|
|
26
26
|
collapsed: boolean;
|
|
@@ -36,10 +36,10 @@ declare const __VLS_base: import("vue").DefineComponent<__VLS_Props, {}, {}, {},
|
|
|
36
36
|
name: string;
|
|
37
37
|
color: string;
|
|
38
38
|
online: boolean | null;
|
|
39
|
+
isFollowing: boolean;
|
|
39
40
|
currentDocId: string | null;
|
|
40
41
|
isSelf: boolean;
|
|
41
42
|
avatarStyle: string;
|
|
42
|
-
isFollowing: boolean;
|
|
43
43
|
showFollow: boolean;
|
|
44
44
|
currentDocLabel: string | null;
|
|
45
45
|
currentDocIcon: string;
|
|
@@ -36,10 +36,10 @@ declare const __VLS_base: import("vue").DefineComponent<__VLS_Props, {}, {}, {},
|
|
|
36
36
|
name: string;
|
|
37
37
|
color: string;
|
|
38
38
|
online: boolean | null;
|
|
39
|
+
isFollowing: boolean;
|
|
39
40
|
currentDocId: string | null;
|
|
40
41
|
isSelf: boolean;
|
|
41
42
|
avatarStyle: string;
|
|
42
|
-
isFollowing: boolean;
|
|
43
43
|
showFollow: boolean;
|
|
44
44
|
currentDocLabel: string | null;
|
|
45
45
|
currentDocIcon: string;
|
|
@@ -34,7 +34,7 @@ export function useAAFollowPeer(options = {}) {
|
|
|
34
34
|
return followingUserCache.value;
|
|
35
35
|
});
|
|
36
36
|
watch(followingUser, (user) => {
|
|
37
|
-
if (user) followingUserCache.value = { ...user };
|
|
37
|
+
if (user && user !== followingUserCache.value) followingUserCache.value = { ...user };
|
|
38
38
|
}, { flush: "post" });
|
|
39
39
|
watch(isFollowing, (active) => {
|
|
40
40
|
if (!active) followingUserCache.value = null;
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { computed } from "vue";
|
|
2
2
|
import { useSyncedMap } from "./useYDoc.js";
|
|
3
3
|
import { useAbracadabra } from "./useAbracadabra.js";
|
|
4
|
+
import { useDocTreeSnapshot } from "./useDocTreeSnapshot.js";
|
|
4
5
|
import { isDescendantInMap } from "../utils/docDragDrop.js";
|
|
5
6
|
export function useChildTree(rootDoc, parentDocId, options) {
|
|
6
7
|
const abraState = (() => {
|
|
@@ -12,9 +13,15 @@ export function useChildTree(rootDoc, parentDocId, options) {
|
|
|
12
13
|
})();
|
|
13
14
|
const treeMap = useSyncedMap(rootDoc, "doc-tree");
|
|
14
15
|
const trashMap = useSyncedMap(rootDoc, "doc-trash");
|
|
16
|
+
const snapshot = useDocTreeSnapshot();
|
|
17
|
+
const source = computed(() => {
|
|
18
|
+
const live = treeMap.data;
|
|
19
|
+
if (live && Object.keys(live).length > 0) return live;
|
|
20
|
+
return snapshot.value?.entries ?? {};
|
|
21
|
+
});
|
|
15
22
|
const entries = computed(() => {
|
|
16
23
|
const result = [];
|
|
17
|
-
for (const [id, v] of Object.entries(
|
|
24
|
+
for (const [id, v] of Object.entries(source.value)) {
|
|
18
25
|
if (id === parentDocId && options?.isSpaceRoot) continue;
|
|
19
26
|
let pid = v.parentId ?? null;
|
|
20
27
|
if (options?.isSpaceRoot && pid === null) pid = parentDocId;
|
|
@@ -3,16 +3,23 @@ import { buildSlugMap } from "../utils/slugify.js";
|
|
|
3
3
|
import { useRuntimeConfig } from "#imports";
|
|
4
4
|
import { useAbracadabra } from "./useAbracadabra.js";
|
|
5
5
|
import { useSyncedMap } from "./useYDoc.js";
|
|
6
|
+
import { useDocTreeSnapshot } from "./useDocTreeSnapshot.js";
|
|
6
7
|
export function useDocSlugs() {
|
|
7
8
|
const abra = useAbracadabra();
|
|
8
9
|
const config = useRuntimeConfig();
|
|
9
10
|
const docBasePath = config.public?.abracadabra?.docBasePath ?? "/doc";
|
|
10
11
|
const treeMap = useSyncedMap(abra.doc, "doc-tree");
|
|
12
|
+
const snapshot = useDocTreeSnapshot();
|
|
13
|
+
const source = computed(() => {
|
|
14
|
+
const live = treeMap.data;
|
|
15
|
+
if (live && Object.keys(live).length > 0) return live;
|
|
16
|
+
return snapshot.value?.entries ?? {};
|
|
17
|
+
});
|
|
11
18
|
const entries = computed(
|
|
12
|
-
() => Object.entries(
|
|
19
|
+
() => Object.entries(source.value).map(([id, entry]) => ({ id, ...entry }))
|
|
13
20
|
);
|
|
14
21
|
const slugMap = computed(
|
|
15
|
-
() => buildSlugMap(entries.value, abra.spaceDocId?.value ?? null)
|
|
22
|
+
() => buildSlugMap(entries.value, abra.spaceDocId?.value ?? snapshot.value?.rootId ?? null)
|
|
16
23
|
);
|
|
17
24
|
const getSlug = (docId) => slugMap.value.idToSlug[docId] ?? docId;
|
|
18
25
|
const getDocId = (slug) => slugMap.value.slugToId[slug] ?? null;
|
|
@@ -8,6 +8,7 @@
|
|
|
8
8
|
import { type ComputedRef } from 'vue';
|
|
9
9
|
import type { TreeEntry } from '../types.js';
|
|
10
10
|
import { useSyncedMap } from './useYDoc.js';
|
|
11
|
+
export { useDocTreeSnapshot, ABRA_DOC_TREE_SNAPSHOT_STATE, type DocTreeSnapshot } from './useDocTreeSnapshot.js';
|
|
11
12
|
export interface DocTreeReturn {
|
|
12
13
|
/** All tree entries with `id` populated from map keys */
|
|
13
14
|
entries: ComputedRef<(TreeEntry & {
|
|
@@ -2,9 +2,11 @@ import { computed, shallowRef, watch } from "vue";
|
|
|
2
2
|
import { resolveDocType } from "../utils/docTypes.js";
|
|
3
3
|
import { buildSlugMap } from "../utils/slugify.js";
|
|
4
4
|
import { useRuntimeConfig } from "#imports";
|
|
5
|
+
import { useDocTreeSnapshot } from "./useDocTreeSnapshot.js";
|
|
5
6
|
import { useAbracadabra } from "./useAbracadabra.js";
|
|
6
7
|
import { useSpaceConnections } from "./useSpaceConnections.js";
|
|
7
8
|
import { useSyncedMap } from "./useYDoc.js";
|
|
9
|
+
export { useDocTreeSnapshot, ABRA_DOC_TREE_SNAPSHOT_STATE } from "./useDocTreeSnapshot.js";
|
|
8
10
|
export function useDocTree(docId) {
|
|
9
11
|
const abra = useAbracadabra();
|
|
10
12
|
const { connections, getDocForDoc, findDocSpaceId } = useSpaceConnections();
|
|
@@ -27,11 +29,17 @@ export function useDocTree(docId) {
|
|
|
27
29
|
}, { immediate: true });
|
|
28
30
|
}
|
|
29
31
|
const treeMap = useSyncedMap(boundDoc, "doc-tree");
|
|
32
|
+
const snapshot = useDocTreeSnapshot();
|
|
33
|
+
const source = computed(() => {
|
|
34
|
+
const live = treeMap.data;
|
|
35
|
+
if (live && Object.keys(live).length > 0) return live;
|
|
36
|
+
return snapshot.value?.entries ?? {};
|
|
37
|
+
});
|
|
30
38
|
const spaceDocId = computed(
|
|
31
|
-
() => docId ? findDocSpaceId(docId) ?? abra.spaceDocId.value : abra.spaceDocId.value
|
|
39
|
+
() => (docId ? findDocSpaceId(docId) ?? abra.spaceDocId.value : abra.spaceDocId.value) ?? snapshot.value?.rootId ?? null
|
|
32
40
|
);
|
|
33
41
|
const entries = computed(
|
|
34
|
-
() => Object.entries(
|
|
42
|
+
() => Object.entries(source.value).filter(([id]) => id !== spaceDocId.value).map(([id, entry]) => ({ id, ...entry }))
|
|
35
43
|
);
|
|
36
44
|
const topLevelDocs = computed(
|
|
37
45
|
() => entries.value.filter(
|
|
@@ -40,7 +48,7 @@ export function useDocTree(docId) {
|
|
|
40
48
|
);
|
|
41
49
|
const firstDocId = computed(() => topLevelDocs.value[0]?.id ?? null);
|
|
42
50
|
const getEntry = (id) => {
|
|
43
|
-
const raw =
|
|
51
|
+
const raw = source.value[id];
|
|
44
52
|
return raw ? { id, ...raw } : void 0;
|
|
45
53
|
};
|
|
46
54
|
const slugMap = computed(() => buildSlugMap(entries.value, spaceDocId.value ?? null));
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
export interface DocTreeSnapshot {
|
|
2
|
+
/** The space document's id — what "top level" is measured against. */
|
|
3
|
+
rootId?: string | null;
|
|
4
|
+
/** Tree entries by id, in the same shape the `doc-tree` map holds. */
|
|
5
|
+
entries: Record<string, unknown>;
|
|
6
|
+
}
|
|
7
|
+
export declare const ABRA_DOC_TREE_SNAPSHOT_STATE = "abracadabra:doc-tree-snapshot";
|
|
8
|
+
export declare function useDocTreeSnapshot(): import("vue").Ref<DocTreeSnapshot | null, DocTreeSnapshot | null>;
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The cached HTML of a document's BODY, for the window before the CRDT arrives.
|
|
3
|
+
*
|
|
4
|
+
* ## Why
|
|
5
|
+
*
|
|
6
|
+
* A document's prose lives in a Y.XmlFragment, which is empty for the whole of
|
|
7
|
+
* SSR — so `<AEditor>` renders a skeleton on the server, and any page whose
|
|
8
|
+
* content is prose shipped three pulsing grey bars to a crawler. Apps papered
|
|
9
|
+
* over this by wrapping the whole page in `<ClientOnly>` and putting cached HTML
|
|
10
|
+
* in the fallback, which works right up until you want the RENDERER to server-
|
|
11
|
+
* render too: then the renderer draws, the editor inside it draws a skeleton,
|
|
12
|
+
* and the prose is gone.
|
|
13
|
+
*
|
|
14
|
+
* So the cached body travels as context instead. `<ADocRenderer>` provides it,
|
|
15
|
+
* `<AEditor>` consumes it, and nothing in between has to thread a prop through
|
|
16
|
+
* — which matters because the editor is often several renderer-specific
|
|
17
|
+
* components deep (a collection's intro, an item's body).
|
|
18
|
+
*
|
|
19
|
+
* ## Keyed by docId, deliberately
|
|
20
|
+
*
|
|
21
|
+
* A page can host editors for OTHER documents — a mosaic pane, an embedded
|
|
22
|
+
* child, a preview. An unkeyed provide would hand every one of them the host
|
|
23
|
+
* page's prose, which is worse than a skeleton: it is confidently wrong content
|
|
24
|
+
* under someone else's title. Consumers must compare `docId` before using
|
|
25
|
+
* `html`, and `useSsrBodyHtmlFor()` does that for them.
|
|
26
|
+
*/
|
|
27
|
+
import { type ComputedRef, type InjectionKey } from 'vue';
|
|
28
|
+
export interface SsrBodyHtml {
|
|
29
|
+
/** The document this HTML belongs to. */
|
|
30
|
+
docId: string;
|
|
31
|
+
/** Rendered body HTML from the app's server-side document cache. */
|
|
32
|
+
html: string;
|
|
33
|
+
}
|
|
34
|
+
export declare const ABRA_SSR_BODY_HTML: InjectionKey<ComputedRef<SsrBodyHtml | null>>;
|
|
35
|
+
/** Publish the cached body for `docId` to descendants. */
|
|
36
|
+
export declare function provideSsrBodyHtml(value: ComputedRef<SsrBodyHtml | null>): void;
|
|
37
|
+
/**
|
|
38
|
+
* The cached body for THIS document, or `''` when there is none for it.
|
|
39
|
+
*
|
|
40
|
+
* Returns `''` rather than the ancestor's HTML when the ids differ — see the
|
|
41
|
+
* keying note above.
|
|
42
|
+
*/
|
|
43
|
+
export declare function useSsrBodyHtmlFor(docId: () => string | undefined | null): ComputedRef<string>;
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { computed, inject, provide } from "vue";
|
|
2
|
+
export const ABRA_SSR_BODY_HTML = Symbol("abracadabra:ssr-body-html");
|
|
3
|
+
export function provideSsrBodyHtml(value) {
|
|
4
|
+
provide(ABRA_SSR_BODY_HTML, value);
|
|
5
|
+
}
|
|
6
|
+
export function useSsrBodyHtmlFor(docId) {
|
|
7
|
+
const provided = inject(ABRA_SSR_BODY_HTML, null);
|
|
8
|
+
return computed(() => {
|
|
9
|
+
const v = provided?.value;
|
|
10
|
+
if (!v || !v.html) return "";
|
|
11
|
+
const id = docId();
|
|
12
|
+
return id && v.docId === id ? v.html : "";
|
|
13
|
+
});
|
|
14
|
+
}
|
|
@@ -1,20 +1,28 @@
|
|
|
1
1
|
import { shallowRef, ref, computed } from "vue";
|
|
2
2
|
import { defineNuxtPlugin } from "#imports";
|
|
3
3
|
import { PluginRegistry } from "./plugin-registry.js";
|
|
4
|
+
import { useDocTreeSnapshot } from "./composables/useDocTreeSnapshot.js";
|
|
4
5
|
export default defineNuxtPlugin({
|
|
5
6
|
name: "abracadabra:server-stub",
|
|
6
7
|
enforce: "post",
|
|
7
|
-
setup(nuxtApp) {
|
|
8
|
+
async setup(nuxtApp) {
|
|
8
9
|
const registry = new PluginRegistry();
|
|
10
|
+
const { _collectSchemaRegistries } = await import("./composables/useAbracadabraSchema.js");
|
|
11
|
+
const { plugins: inlinePlugins } = await _collectSchemaRegistries(nuxtApp);
|
|
12
|
+
for (const plugin of inlinePlugins) {
|
|
13
|
+
registry.register(plugin);
|
|
14
|
+
}
|
|
9
15
|
registry.freeze();
|
|
10
16
|
const noop = () => {
|
|
11
17
|
};
|
|
12
18
|
const noopAsync = async () => {
|
|
13
19
|
};
|
|
20
|
+
const snapshot = useDocTreeSnapshot();
|
|
21
|
+
const spaceDocId = computed(() => snapshot.value?.rootId ?? null);
|
|
14
22
|
nuxtApp.provide("abracadabra", {
|
|
15
23
|
// CRDT objects — null on server
|
|
16
24
|
doc: shallowRef(null),
|
|
17
|
-
spaceDocId
|
|
25
|
+
spaceDocId,
|
|
18
26
|
provider: shallowRef(null),
|
|
19
27
|
client: shallowRef(null),
|
|
20
28
|
keystore: shallowRef(null),
|
|
@@ -8,6 +8,7 @@ import { buildServerSchemaValidator } from "../utils/schemaServerSupport.js";
|
|
|
8
8
|
import { createDocCacheAPI } from "../utils/docCache.js";
|
|
9
9
|
import { docTreeCacheRunner } from "../runners/doc-tree-cache.js";
|
|
10
10
|
import { initSlugMap, loadPersistedSlugMap } from "../utils/slugMap.js";
|
|
11
|
+
import { loginWithKeyRetrying, waitForBackendReady } from "../utils/authRetry.js";
|
|
11
12
|
function fromBase64Url(str) {
|
|
12
13
|
const b = atob(str.replace(/-/g, "+").replace(/_/g, "/").padEnd(str.length + (4 - str.length % 4) % 4, "="));
|
|
13
14
|
const a = new Uint8Array(b.length);
|
|
@@ -53,7 +54,7 @@ async function loadOrCreateAutoIdentity(opts) {
|
|
|
53
54
|
const pk = await opts.ed.getPublicKey(sk);
|
|
54
55
|
const publicKey = toBase64Url(pk);
|
|
55
56
|
const privateKey = toBase64Url(sk);
|
|
56
|
-
const username = `runner-${publicKey.replace(/[^a-
|
|
57
|
+
const username = `runner-${publicKey.replace(/[^a-z0-9]/gi, "").slice(0, 16).toLowerCase()}`;
|
|
57
58
|
console.log(`[abracadabra-service] auto-registering ${username} on ${opts.serverUrl}\u2026`);
|
|
58
59
|
const res = await fetch(`${opts.serverUrl}/auth/register`, {
|
|
59
60
|
method: "POST",
|
|
@@ -187,57 +188,64 @@ export default defineNitroPlugin(async (nitroApp) => {
|
|
|
187
188
|
return;
|
|
188
189
|
}
|
|
189
190
|
let wsp = null;
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
;
|
|
208
|
-
globalThis.WebSocket
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
throw new Error("@noble/ed25519 v3: `hashes` export missing \u2014 check Vite optimizeDeps");
|
|
212
|
-
}
|
|
213
|
-
ed.hashes.sha512 = sha512;
|
|
214
|
-
ed.hashes.sha512Async = (m) => Promise.resolve(sha512(m));
|
|
215
|
-
let pubKeyB64 = explicitPubKey;
|
|
216
|
-
let privKeyB64 = explicitPrivKey;
|
|
217
|
-
if (!pubKeyB64 || !privKeyB64) {
|
|
218
|
-
const cachePath = join(process.cwd(), ".data", "abracadabra-runner-identity.json");
|
|
219
|
-
const id = await loadOrCreateAutoIdentity({ serverUrl, cachePath, ed });
|
|
220
|
-
if (!id) {
|
|
221
|
-
return;
|
|
191
|
+
const INIT_BACKOFF_CAP_MS = 3e4;
|
|
192
|
+
for (let initAttempt = 1; ; initAttempt++) {
|
|
193
|
+
try {
|
|
194
|
+
const [
|
|
195
|
+
{ AbracadabraClient, AbracadabraProvider, AbracadabraWS },
|
|
196
|
+
edModule,
|
|
197
|
+
{ sha512 },
|
|
198
|
+
Y,
|
|
199
|
+
wsModule
|
|
200
|
+
] = await Promise.all([
|
|
201
|
+
import("@abraca/dabra"),
|
|
202
|
+
import("@noble/ed25519"),
|
|
203
|
+
import("@noble/hashes/sha2.js"),
|
|
204
|
+
import("yjs"),
|
|
205
|
+
import("ws")
|
|
206
|
+
]);
|
|
207
|
+
const ed = edModule.default ?? edModule;
|
|
208
|
+
const WSImpl = wsModule.WebSocket ?? wsModule.default;
|
|
209
|
+
if (typeof globalThis.WebSocket === "undefined" && WSImpl) {
|
|
210
|
+
;
|
|
211
|
+
globalThis.WebSocket = WSImpl;
|
|
222
212
|
}
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
const
|
|
213
|
+
if (!ed.hashes) {
|
|
214
|
+
throw new Error("@noble/ed25519 v3: `hashes` export missing \u2014 check Vite optimizeDeps");
|
|
215
|
+
}
|
|
216
|
+
ed.hashes.sha512 = sha512;
|
|
217
|
+
ed.hashes.sha512Async = (m) => Promise.resolve(sha512(m));
|
|
218
|
+
let pubKeyB64 = explicitPubKey;
|
|
219
|
+
let privKeyB64 = explicitPrivKey;
|
|
220
|
+
if (!pubKeyB64 || !privKeyB64) {
|
|
221
|
+
const cachePath = join(process.cwd(), ".data", "abracadabra-runner-identity.json");
|
|
222
|
+
const id = await loadOrCreateAutoIdentity({ serverUrl, cachePath, ed });
|
|
223
|
+
if (!id) {
|
|
224
|
+
return;
|
|
225
|
+
}
|
|
226
|
+
pubKeyB64 = id.publicKey;
|
|
227
|
+
privKeyB64 = id.privateKey;
|
|
228
|
+
}
|
|
229
|
+
const privKey = fromBase64Url(privKeyB64);
|
|
230
|
+
const client = new AbracadabraClient({
|
|
231
|
+
url: serverUrl,
|
|
232
|
+
persistAuth: false
|
|
233
|
+
});
|
|
234
|
+
await waitForBackendReady({ serverUrl });
|
|
235
|
+
await loginWithKeyRetrying({
|
|
236
|
+
client,
|
|
237
|
+
publicKey: pubKeyB64,
|
|
238
|
+
sign: async (challenge) => {
|
|
239
|
+
const sig = await ed.sign(fromBase64Url(challenge), privKey);
|
|
240
|
+
return toBase64Url(sig);
|
|
241
|
+
}
|
|
242
|
+
});
|
|
243
|
+
const actualRole = await resolveActualRole(serverUrl, client.token);
|
|
244
|
+
console.log(
|
|
245
|
+
`[abracadabra-service] authenticated \u2014 role: ${actualRole ?? "unknown"}`
|
|
246
|
+
);
|
|
247
|
+
if (actualRole !== "service") {
|
|
248
|
+
const detail = `[abracadabra-service] this runner is "${actualRole ?? "unknown"}", not "service".
|
|
241
249
|
Consequence: writes are refused ON THE WIRE with no thrown error \u2014 seeding,
|
|
242
250
|
the SSR doc cache and RPC handlers will appear to run and change nothing.
|
|
243
251
|
Runner public key: ${pubKeyB64}
|
|
@@ -247,183 +255,197 @@ export default defineNitroPlugin(async (nitroApp) => {
|
|
|
247
255
|
password = "<rotate-me>"
|
|
248
256
|
public_key = "${pubKeyB64}"
|
|
249
257
|
(env equivalent: ABRA_USERS_SYSTEM_USERS='[{"username":"app-runner","password":"<rotate-me>","public_key":"${pubKeyB64}"}]')`;
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
258
|
+
if (requireServiceRole) {
|
|
259
|
+
console.error(detail);
|
|
260
|
+
console.error(
|
|
261
|
+
"[abracadabra-service] refusing to boot runners (service.requireServiceRole). A runner that cannot write is worse than none: it looks healthy and does nothing."
|
|
262
|
+
);
|
|
263
|
+
return;
|
|
264
|
+
}
|
|
265
|
+
console.warn(detail);
|
|
266
|
+
}
|
|
267
|
+
const wsUrl = client.wsUrl;
|
|
268
|
+
wsp = new AbracadabraWS({
|
|
269
|
+
url: wsUrl,
|
|
270
|
+
delay: 1e3,
|
|
271
|
+
minDelay: 1e3,
|
|
272
|
+
maxDelay: 3e4,
|
|
273
|
+
factor: 2,
|
|
274
|
+
jitter: true,
|
|
275
|
+
maxAttempts: 50,
|
|
276
|
+
WebSocketPolyfill: WSImpl
|
|
277
|
+
});
|
|
278
|
+
let rootDocId = rootDocIdOverride;
|
|
279
|
+
let rootDocFromSentinel = false;
|
|
280
|
+
if (!rootDocId) {
|
|
281
|
+
try {
|
|
282
|
+
const info = await $fetch(`${serverUrl}/info`);
|
|
283
|
+
rootDocId = info?.root_doc_id ?? "";
|
|
284
|
+
rootDocFromSentinel = !!rootDocId;
|
|
285
|
+
} catch {
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
if (!rootDocId) {
|
|
289
|
+
console.warn("[abracadabra-service] Could not determine root doc ID. Set service.rootDocId in module options.");
|
|
290
|
+
wsp.destroy?.();
|
|
255
291
|
return;
|
|
256
292
|
}
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
url: wsUrl,
|
|
262
|
-
delay: 1e3,
|
|
263
|
-
minDelay: 1e3,
|
|
264
|
-
maxDelay: 3e4,
|
|
265
|
-
factor: 2,
|
|
266
|
-
jitter: true,
|
|
267
|
-
maxAttempts: 50,
|
|
268
|
-
WebSocketPolyfill: WSImpl
|
|
269
|
-
});
|
|
270
|
-
let rootDocId = rootDocIdOverride;
|
|
271
|
-
let rootDocFromSentinel = false;
|
|
272
|
-
if (!rootDocId) {
|
|
273
|
-
try {
|
|
274
|
-
const info = await $fetch(`${serverUrl}/info`);
|
|
275
|
-
rootDocId = info?.root_doc_id ?? "";
|
|
276
|
-
rootDocFromSentinel = !!rootDocId;
|
|
277
|
-
} catch {
|
|
293
|
+
if (rootDocFromSentinel) {
|
|
294
|
+
console.warn(
|
|
295
|
+
`[abracadabra-service] no service.rootDocId / entryDocId configured \u2014 falling back to the server's reserved root (${rootDocId}). That is a shared sentinel, not this app's space: expect an empty doc tree and no SSR content. Set abracadabra.entryDocId (or service.rootDocId) to your space's id.`
|
|
296
|
+
);
|
|
278
297
|
}
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
token: client.token,
|
|
294
|
-
role: actualRole,
|
|
295
|
-
label: rootDocLabel,
|
|
296
|
-
publicAccess: rootDocPublicAccess,
|
|
297
|
-
// Never auto-create the shared sentinel: it always exists, and creating
|
|
298
|
-
// "the root" is not what an operator who forgot to set an id wants.
|
|
299
|
-
enabled: ensureRootDoc && !rootDocFromSentinel
|
|
300
|
-
});
|
|
301
|
-
if (!rootReady) {
|
|
302
|
-
wsp.destroy?.();
|
|
303
|
-
return;
|
|
304
|
-
}
|
|
305
|
-
const rootDoc = new Y.Doc();
|
|
306
|
-
const rootProvider = new AbracadabraProvider({
|
|
307
|
-
client,
|
|
308
|
-
document: rootDoc,
|
|
309
|
-
name: rootDocId,
|
|
310
|
-
websocketProvider: wsp,
|
|
311
|
-
disableOfflineStore: true,
|
|
312
|
-
cryptoIdentity: { publicKey: pubKeyB64 },
|
|
313
|
-
signChallenge: async (challenge) => {
|
|
314
|
-
const sig = await ed.sign(fromBase64Url(challenge), privKey);
|
|
315
|
-
return toBase64Url(sig);
|
|
298
|
+
const rootReady = await ensureRootDocument({
|
|
299
|
+
serverUrl,
|
|
300
|
+
rootDocId,
|
|
301
|
+
token: client.token,
|
|
302
|
+
role: actualRole,
|
|
303
|
+
label: rootDocLabel,
|
|
304
|
+
publicAccess: rootDocPublicAccess,
|
|
305
|
+
// Never auto-create the shared sentinel: it always exists, and creating
|
|
306
|
+
// "the root" is not what an operator who forgot to set an id wants.
|
|
307
|
+
enabled: ensureRootDoc && !rootDocFromSentinel
|
|
308
|
+
});
|
|
309
|
+
if (!rootReady) {
|
|
310
|
+
wsp.destroy?.();
|
|
311
|
+
return;
|
|
316
312
|
}
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
if (rootProvider.isSynced) {
|
|
329
|
-
resolve();
|
|
330
|
-
return;
|
|
313
|
+
const rootDoc = new Y.Doc();
|
|
314
|
+
const rootProvider = new AbracadabraProvider({
|
|
315
|
+
client,
|
|
316
|
+
document: rootDoc,
|
|
317
|
+
name: rootDocId,
|
|
318
|
+
websocketProvider: wsp,
|
|
319
|
+
disableOfflineStore: true,
|
|
320
|
+
cryptoIdentity: { publicKey: pubKeyB64 },
|
|
321
|
+
signChallenge: async (challenge) => {
|
|
322
|
+
const sig = await ed.sign(fromBase64Url(challenge), privKey);
|
|
323
|
+
return toBase64Url(sig);
|
|
331
324
|
}
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
325
|
+
});
|
|
326
|
+
rootProvider.on("writeRejected", ({ documentName, reason, kind }) => {
|
|
327
|
+
console.error(
|
|
328
|
+
`[abracadabra-service] server REFUSED a write to ${documentName} (${kind}): ${reason}. This runner's changes are not being persisted.`
|
|
329
|
+
);
|
|
330
|
+
});
|
|
331
|
+
rootProvider.attach();
|
|
332
|
+
const SYNC_ATTEMPTS = 3;
|
|
333
|
+
const SYNC_TIMEOUT_MS = 3e4;
|
|
334
|
+
const waitForSync = () => Promise.race([
|
|
335
|
+
new Promise((resolve) => {
|
|
336
|
+
if (rootProvider.isSynced) {
|
|
335
337
|
resolve();
|
|
338
|
+
return;
|
|
336
339
|
}
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
340
|
+
const handler = ({ state }) => {
|
|
341
|
+
if (state) {
|
|
342
|
+
rootProvider.off("synced", handler);
|
|
343
|
+
resolve();
|
|
344
|
+
}
|
|
345
|
+
};
|
|
346
|
+
rootProvider.on("synced", handler);
|
|
347
|
+
}),
|
|
348
|
+
new Promise(
|
|
349
|
+
(_, reject) => setTimeout(() => reject(new Error("sync timeout")), SYNC_TIMEOUT_MS)
|
|
350
|
+
)
|
|
351
|
+
]);
|
|
352
|
+
let synced = false;
|
|
353
|
+
for (let attempt = 1; attempt <= SYNC_ATTEMPTS && !synced; attempt++) {
|
|
351
354
|
try {
|
|
352
|
-
await
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
restStatus = "
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
355
|
+
await waitForSync();
|
|
356
|
+
synced = true;
|
|
357
|
+
} catch {
|
|
358
|
+
let restStatus = "unreachable";
|
|
359
|
+
try {
|
|
360
|
+
await $fetch(`${serverUrl}/docs/${rootDocId}`, {
|
|
361
|
+
headers: client.token ? { Authorization: `Bearer ${client.token}` } : void 0
|
|
362
|
+
});
|
|
363
|
+
restStatus = "exists over REST";
|
|
364
|
+
} catch (e) {
|
|
365
|
+
const status = e?.status ?? e?.statusCode;
|
|
366
|
+
restStatus = status === 404 ? "DOES NOT EXIST (404)" : `REST error ${status ?? "?"}`;
|
|
367
|
+
}
|
|
368
|
+
console.warn(
|
|
369
|
+
`[abracadabra-service] root doc ${rootDocId} did not sync within ${SYNC_TIMEOUT_MS}ms (attempt ${attempt}/${SYNC_ATTEMPTS}) \u2014 document: ${restStatus}; role: ${actualRole ?? "unknown"}; socket: ${rootProvider.connectionStatus ?? "unknown"}`
|
|
370
|
+
);
|
|
359
371
|
}
|
|
360
|
-
|
|
361
|
-
|
|
372
|
+
}
|
|
373
|
+
if (!synced) {
|
|
374
|
+
console.error(
|
|
375
|
+
`[abracadabra-service] giving up on the initial sync of ${rootDocId}. Runners will boot anyway and recover as sync lands \u2014 SSR content will be missing until then.`
|
|
362
376
|
);
|
|
377
|
+
} else {
|
|
378
|
+
console.log("[abracadabra-service] Root doc synced");
|
|
363
379
|
}
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
const ctx = {
|
|
374
|
-
client,
|
|
375
|
-
wsp,
|
|
376
|
-
rootDoc,
|
|
377
|
-
rootDocId,
|
|
378
|
-
rootProvider,
|
|
379
|
-
storage: storage2,
|
|
380
|
-
docCache: createDocCacheAPI(rootDoc)
|
|
381
|
-
};
|
|
382
|
-
const publicConfig = config.public?.abracadabra;
|
|
383
|
-
if (publicConfig?.features?.serverCache !== false) {
|
|
384
|
-
const coreServerPlugin = {
|
|
385
|
-
name: "abracadabra:core-server",
|
|
386
|
-
serverRunners: [docTreeCacheRunner]
|
|
380
|
+
const storage2 = useStorage();
|
|
381
|
+
const ctx = {
|
|
382
|
+
client,
|
|
383
|
+
wsp,
|
|
384
|
+
rootDoc,
|
|
385
|
+
rootDocId,
|
|
386
|
+
rootProvider,
|
|
387
|
+
storage: storage2,
|
|
388
|
+
docCache: createDocCacheAPI(rootDoc)
|
|
387
389
|
};
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
390
|
+
const publicConfig = config.public?.abracadabra;
|
|
391
|
+
if (publicConfig?.features?.serverCache !== false) {
|
|
392
|
+
const coreServerPlugin = {
|
|
393
|
+
name: "abracadabra:core-server",
|
|
394
|
+
serverRunners: [docTreeCacheRunner]
|
|
395
|
+
};
|
|
396
|
+
registerServerPlugin(coreServerPlugin);
|
|
397
|
+
}
|
|
398
|
+
const attachedSchemas = [];
|
|
399
|
+
const schemaCfg = publicConfig?.schema ?? {};
|
|
400
|
+
if (schemaCfg.bundleDir) {
|
|
401
|
+
console.log(
|
|
402
|
+
`[abracadabra-service] schema bundle_dir advertised: ${schemaCfg.bundleDir} (server-side bundle_dir = same path; informational only \u2014 server is authoritative)`
|
|
403
|
+
);
|
|
404
|
+
}
|
|
405
|
+
Object.assign(ctx, {
|
|
406
|
+
attachSchema: (registry) => {
|
|
407
|
+
if (!registry || typeof registry !== "object") return;
|
|
408
|
+
if (typeof registry.validateMeta !== "function") {
|
|
409
|
+
console.warn("[abracadabra-service] attachSchema received a value missing validateMeta() \u2014 skipping");
|
|
410
|
+
return;
|
|
411
|
+
}
|
|
412
|
+
attachedSchemas.push(registry);
|
|
403
413
|
}
|
|
404
|
-
|
|
414
|
+
});
|
|
415
|
+
await nitroApp.hooks.callHook("abracadabra:before-runners", ctx);
|
|
416
|
+
delete ctx.attachSchema;
|
|
417
|
+
if (attachedSchemas.length > 0) {
|
|
418
|
+
const validator = buildServerSchemaValidator(attachedSchemas);
|
|
419
|
+
if (validator) ctx.validateMeta = validator;
|
|
420
|
+
const advertisedTypes = /* @__PURE__ */ new Set();
|
|
421
|
+
for (const r of attachedSchemas) for (const t of r.types.keys()) advertisedTypes.add(t);
|
|
422
|
+
console.log(
|
|
423
|
+
`[abracadabra-service] ${attachedSchemas.length} schema registr${attachedSchemas.length === 1 ? "y" : "ies"} attached covering types: [${[...advertisedTypes].sort().join(", ")}]`
|
|
424
|
+
);
|
|
405
425
|
}
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
426
|
+
await bootRunners(ctx);
|
|
427
|
+
console.log("[abracadabra-service] All runners started");
|
|
428
|
+
nitroApp.hooks.hook("close", async () => {
|
|
429
|
+
await shutdownAllRunners();
|
|
430
|
+
wsp?.destroy?.();
|
|
431
|
+
console.log("[abracadabra-service] Shutdown complete");
|
|
432
|
+
});
|
|
433
|
+
return;
|
|
434
|
+
} catch (err) {
|
|
435
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
436
|
+
wsp?.destroy?.();
|
|
437
|
+
wsp = null;
|
|
438
|
+
const delay = Math.min(1e3 * 2 ** (initAttempt - 1), INIT_BACKOFF_CAP_MS);
|
|
439
|
+
if (initAttempt === 1) {
|
|
440
|
+
console.error(`[abracadabra-service] Failed to initialize: ${message}`);
|
|
441
|
+
console.error(
|
|
442
|
+
"[abracadabra-service] NO SERVER RUNNER IS RUNNING YET. Until one does, this deployment cannot server-render: no SSR document cache, no RPC handlers, no seeding, no background jobs. Browsers sync the CRDT tree themselves, so the site will still LOOK correct \u2014 check this log, not the site. Retrying until it succeeds."
|
|
443
|
+
);
|
|
444
|
+
}
|
|
445
|
+
console.warn(
|
|
446
|
+
`[abracadabra-service] init attempt ${initAttempt} failed (${message}) \u2014 retrying in ${delay}ms.`
|
|
416
447
|
);
|
|
448
|
+
await new Promise((resolve) => setTimeout(resolve, delay));
|
|
417
449
|
}
|
|
418
|
-
await bootRunners(ctx);
|
|
419
|
-
console.log("[abracadabra-service] All runners started");
|
|
420
|
-
nitroApp.hooks.hook("close", async () => {
|
|
421
|
-
await shutdownAllRunners();
|
|
422
|
-
wsp?.destroy?.();
|
|
423
|
-
console.log("[abracadabra-service] Shutdown complete");
|
|
424
|
-
});
|
|
425
|
-
} catch (err) {
|
|
426
|
-
console.error("[abracadabra-service] Failed to initialize:", err instanceof Error ? err.message : err);
|
|
427
|
-
wsp?.destroy?.();
|
|
428
450
|
}
|
|
429
451
|
});
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The Ed25519 challenge-response handshake, retried — and importable, so it
|
|
3
|
+
* can be TESTED.
|
|
4
|
+
*
|
|
5
|
+
* ── Why this file exists as its own module ───────────────────────────────────
|
|
6
|
+
* This logic used to be four lines inside `plugins/abracadabra-service.ts`.
|
|
7
|
+
* That file imports `nitropack/runtime/*`, which cannot load outside a built
|
|
8
|
+
* Nitro app, so nothing in it was reachable from a unit test — which is
|
|
9
|
+
* exactly why a one-shot, un-retried auth call survived in the single most
|
|
10
|
+
* deploy-critical path in the module. Anything here worth asserting on belongs
|
|
11
|
+
* in a util with **zero imports**, the same split the doc cache and the
|
|
12
|
+
* activity ledger already use.
|
|
13
|
+
*
|
|
14
|
+
* ── What it is defending against ─────────────────────────────────────────────
|
|
15
|
+
* `POST /auth/verify` answers **410** `{"error":"challenge expired","retry":true}`
|
|
16
|
+
* whenever the process receiving the verify is not the process that ISSUED the
|
|
17
|
+
* challenge. The server's challenge store is an in-memory `DashMap` per
|
|
18
|
+
* process (`identity.rs` → `issue_challenge` / `consume_challenge`) and
|
|
19
|
+
* nothing shares it between replicas. So the handshake breaks whenever:
|
|
20
|
+
*
|
|
21
|
+
* • a rolling deploy briefly runs the old and the new backend container
|
|
22
|
+
* behind one service name (Docker DNS round-robins between them, and the
|
|
23
|
+
* two halves of one handshake take two different connections);
|
|
24
|
+
* • the backend restarts between the challenge and the verify;
|
|
25
|
+
* • the deployment genuinely runs more than one replica, which the server's
|
|
26
|
+
* own `.env.postgres.example` documents as supported.
|
|
27
|
+
*
|
|
28
|
+
* **"Expired" is a misnomer** and it is why this cost days of debugging.
|
|
29
|
+
* Reproduced against two 3.1.0 containers sharing one database, the split
|
|
30
|
+
* handshake fails in **4 ms** against a 60 s `auth.challenge_ttl_secs`.
|
|
31
|
+
*
|
|
32
|
+
* A FRESH challenge per attempt is the whole point — a consumed challenge is
|
|
33
|
+
* the other way to earn a 410, so a retry that reused it would fail
|
|
34
|
+
* identically forever. `loginWithKey` re-runs challenge→sign→verify in full.
|
|
35
|
+
*
|
|
36
|
+
* Responses carrying `retry: false` (403 bad signature, unknown public key)
|
|
37
|
+
* are CONFIGURATION errors and fail immediately: retrying those only buries
|
|
38
|
+
* the one log line that names the fix.
|
|
39
|
+
*/
|
|
40
|
+
/**
|
|
41
|
+
* Wait until the backend is actually answering before starting the handshake.
|
|
42
|
+
*
|
|
43
|
+
* Compose's `depends_on: { condition: service_healthy }` is supposed to make
|
|
44
|
+
* this unnecessary. It measurably does not hold on every orchestrator: on a
|
|
45
|
+
* real Dokploy deploy the app logged `Listening` at 10:12:21.362 and failed
|
|
46
|
+
* its handshake 193ms later, while the backend that would serve it did not
|
|
47
|
+
* finish booting until 10:12:35.384 — **14 seconds after the app had already
|
|
48
|
+
* given up**. The app had handshaked against the outgoing container.
|
|
49
|
+
*
|
|
50
|
+
* Polling `/health` first turns that race into a wait. It is deliberately
|
|
51
|
+
* NON-fatal: a budget exhaustion returns `false` and lets the caller try the
|
|
52
|
+
* handshake anyway, because a readiness probe that can block boot is another
|
|
53
|
+
* way to never start.
|
|
54
|
+
*/
|
|
55
|
+
export declare function waitForBackendReady(opts: {
|
|
56
|
+
serverUrl: string;
|
|
57
|
+
fetchImpl?: typeof globalThis.fetch;
|
|
58
|
+
/** Total wall-clock budget. Default 120s — longer than any cold start. */
|
|
59
|
+
timeoutMs?: number;
|
|
60
|
+
now?: () => number;
|
|
61
|
+
sleep?: (ms: number) => Promise<void>;
|
|
62
|
+
onLog?: (level: 'warn' | 'info', message: string) => void;
|
|
63
|
+
}): Promise<boolean>;
|
|
64
|
+
/** The slice of `AbracadabraClient` this needs — kept structural so tests need no SDK. */
|
|
65
|
+
export interface LoginCapableClient {
|
|
66
|
+
loginWithKey: (publicKey: string, signChallenge: (challenge: string) => Promise<string>) => Promise<string>;
|
|
67
|
+
}
|
|
68
|
+
export interface LoginRetryOptions {
|
|
69
|
+
client: LoginCapableClient;
|
|
70
|
+
publicKey: string;
|
|
71
|
+
sign: (challenge: string) => Promise<string>;
|
|
72
|
+
/** Total attempts including the first. Default 5. */
|
|
73
|
+
attempts?: number;
|
|
74
|
+
/** Injected for tests so a retry suite runs in microseconds, not seconds. */
|
|
75
|
+
sleep?: (ms: number) => Promise<void>;
|
|
76
|
+
onLog?: (level: 'warn' | 'error' | 'info', message: string) => void;
|
|
77
|
+
}
|
|
78
|
+
/**
|
|
79
|
+
* Is this failure worth another attempt with a fresh challenge?
|
|
80
|
+
*
|
|
81
|
+
* - `410` — this backend process did not issue our challenge. Transient by
|
|
82
|
+
* construction: the next attempt gets a challenge from whichever process
|
|
83
|
+
* answers, and only needs the verify to land on that same one.
|
|
84
|
+
* - `undefined` — no HTTP status at all: a socket error, DNS mid-rollover, a
|
|
85
|
+
* container that is listening but not yet accepting. Always transient.
|
|
86
|
+
* - `5xx` — the backend is up but unwell.
|
|
87
|
+
* - `401` / `403` — the key is not registered, or the signature is wrong.
|
|
88
|
+
* **Never retried.** The server itself answers these with `retry: false`.
|
|
89
|
+
*/
|
|
90
|
+
export declare function isRetryableAuthStatus(status: number | undefined): boolean;
|
|
91
|
+
/** Exponential backoff, capped. Exported so a test can pin the schedule. */
|
|
92
|
+
export declare function authRetryDelayMs(attempt: number): number;
|
|
93
|
+
export declare function loginWithKeyRetrying(opts: LoginRetryOptions): Promise<void>;
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
export async function waitForBackendReady(opts) {
|
|
2
|
+
const doFetch = opts.fetchImpl ?? globalThis.fetch;
|
|
3
|
+
const timeoutMs = opts.timeoutMs ?? 12e4;
|
|
4
|
+
const now = opts.now ?? (() => Date.now());
|
|
5
|
+
const sleep = opts.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
|
|
6
|
+
const log = opts.onLog ?? ((level, message) => {
|
|
7
|
+
if (level === "warn") console.warn(message);
|
|
8
|
+
else console.log(message);
|
|
9
|
+
});
|
|
10
|
+
const started = now();
|
|
11
|
+
let attempt = 0;
|
|
12
|
+
let warned = false;
|
|
13
|
+
for (; ; ) {
|
|
14
|
+
attempt += 1;
|
|
15
|
+
try {
|
|
16
|
+
const res = await doFetch(`${opts.serverUrl}/health`);
|
|
17
|
+
if (res.ok) {
|
|
18
|
+
if (warned) {
|
|
19
|
+
log("info", `[abracadabra-service] backend ready after ${Math.round((now() - started) / 1e3)}s`);
|
|
20
|
+
}
|
|
21
|
+
return true;
|
|
22
|
+
}
|
|
23
|
+
} catch {
|
|
24
|
+
}
|
|
25
|
+
if (now() - started >= timeoutMs) {
|
|
26
|
+
log(
|
|
27
|
+
"warn",
|
|
28
|
+
`[abracadabra-service] ${opts.serverUrl}/health did not answer within ${Math.round(timeoutMs / 1e3)}s \u2014 attempting the handshake anyway.`
|
|
29
|
+
);
|
|
30
|
+
return false;
|
|
31
|
+
}
|
|
32
|
+
if (!warned) {
|
|
33
|
+
warned = true;
|
|
34
|
+
log(
|
|
35
|
+
"warn",
|
|
36
|
+
`[abracadabra-service] waiting for ${opts.serverUrl} to become ready \u2014 the backend is not answering /health yet.`
|
|
37
|
+
);
|
|
38
|
+
}
|
|
39
|
+
await sleep(Math.min(500 * 2 ** (attempt - 1), 5e3));
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
export function isRetryableAuthStatus(status) {
|
|
43
|
+
if (status === void 0) return true;
|
|
44
|
+
if (status === 410) return true;
|
|
45
|
+
return status >= 500 && status < 600;
|
|
46
|
+
}
|
|
47
|
+
export function authRetryDelayMs(attempt) {
|
|
48
|
+
return Math.min(250 * 2 ** (attempt - 1), 4e3);
|
|
49
|
+
}
|
|
50
|
+
export async function loginWithKeyRetrying(opts) {
|
|
51
|
+
const attempts = opts.attempts ?? 5;
|
|
52
|
+
const sleep = opts.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
|
|
53
|
+
const log = opts.onLog ?? ((level, message) => {
|
|
54
|
+
if (level === "error") console.error(message);
|
|
55
|
+
else if (level === "warn") console.warn(message);
|
|
56
|
+
else console.log(message);
|
|
57
|
+
});
|
|
58
|
+
for (let attempt = 1; ; attempt++) {
|
|
59
|
+
try {
|
|
60
|
+
await opts.client.loginWithKey(opts.publicKey, opts.sign);
|
|
61
|
+
if (attempt > 1) {
|
|
62
|
+
log("info", `[abracadabra-service] handshake succeeded on attempt ${attempt}`);
|
|
63
|
+
}
|
|
64
|
+
return;
|
|
65
|
+
} catch (err) {
|
|
66
|
+
const status = err?.status;
|
|
67
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
68
|
+
if (!isRetryableAuthStatus(status)) {
|
|
69
|
+
log("error", `[abracadabra-service] handshake refused (${message}) \u2014 not retrying. This is a credential problem, not a transient one: the runner's public key is not the key the backend registered for its service account. The backend only registers a key at ITS OWN boot, so after rotating one, recreate the backend container too.`);
|
|
70
|
+
throw err;
|
|
71
|
+
}
|
|
72
|
+
if (attempt >= attempts) {
|
|
73
|
+
log("error", `[abracadabra-service] handshake still failing after ${attempts} attempts: ${message}`);
|
|
74
|
+
throw err;
|
|
75
|
+
}
|
|
76
|
+
const delay = authRetryDelayMs(attempt);
|
|
77
|
+
log(
|
|
78
|
+
"warn",
|
|
79
|
+
`[abracadabra-service] handshake attempt ${attempt}/${attempts} failed (${message}) \u2014 retrying with a fresh challenge in ${delay}ms.` + (status === 410 ? " A 410 here means the backend process that answered /auth/verify never issued the challenge \u2014 expected while a deploy is still swapping backend containers." : "")
|
|
80
|
+
);
|
|
81
|
+
await sleep(delay);
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@abraca/nuxt",
|
|
3
|
-
"version": "2.
|
|
3
|
+
"version": "2.87.0",
|
|
4
4
|
"description": "First-class Nuxt module for the Abracadabra CRDT collaboration platform",
|
|
5
5
|
"repository": "abracadabra/abracadabra-nuxt",
|
|
6
6
|
"license": "MIT",
|
|
@@ -173,9 +173,9 @@
|
|
|
173
173
|
}
|
|
174
174
|
},
|
|
175
175
|
"devDependencies": {
|
|
176
|
-
"@abraca/convert": "^2.
|
|
177
|
-
"@abraca/dabra": "^2.
|
|
178
|
-
"@abraca/plugin": "^2.
|
|
176
|
+
"@abraca/convert": "^2.86.0",
|
|
177
|
+
"@abraca/dabra": "^2.86.0",
|
|
178
|
+
"@abraca/plugin": "^2.86.0",
|
|
179
179
|
"@codemirror/autocomplete": "^6.18.0",
|
|
180
180
|
"@codemirror/commands": "^6.7.0",
|
|
181
181
|
"@codemirror/lang-css": "^6.3.1",
|