@abraca/junis 2.88.0 → 2.90.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.
Files changed (30) hide show
  1. package/dist/module.d.mts +39 -2
  2. package/dist/module.json +1 -1
  3. package/dist/module.mjs +57 -0
  4. package/dist/runtime/components/JunNavMenu.client.vue +24 -1
  5. package/dist/runtime/components/JunOfflinePanel.client.d.vue.ts +3 -0
  6. package/dist/runtime/components/JunOfflinePanel.client.vue +293 -0
  7. package/dist/runtime/components/JunOfflinePanel.client.vue.d.ts +3 -0
  8. package/dist/runtime/components/renderers/JunConfigRenderer.vue +132 -0
  9. package/dist/runtime/composables/useJunCommands.d.ts +1 -1
  10. package/dist/runtime/composables/useJunCommands.js +14 -1
  11. package/dist/runtime/composables/useJunOffline.d.ts +109 -0
  12. package/dist/runtime/composables/useJunOffline.js +294 -0
  13. package/dist/runtime/composables/useJunSettings.d.ts +1 -1
  14. package/dist/runtime/composables/useJunSettings.js +2 -0
  15. package/dist/runtime/composables/useJunSiteConfig.d.ts +19 -0
  16. package/dist/runtime/layouts/jun.vue +12 -2
  17. package/dist/runtime/server/api/offline.get.d.ts +10 -0
  18. package/dist/runtime/server/api/offline.get.js +13 -0
  19. package/dist/runtime/server/plugins/jun-compress.d.ts +2 -0
  20. package/dist/runtime/server/plugins/jun-compress.js +76 -0
  21. package/dist/runtime/server/routes/jun-sw.js.get.js +66 -13
  22. package/dist/runtime/server/routes/sitemap.xml.get.js +5 -18
  23. package/dist/runtime/server/utils/junPages.d.ts +51 -0
  24. package/dist/runtime/server/utils/junPages.js +70 -0
  25. package/dist/runtime/types.d.ts +70 -0
  26. package/dist/runtime/utils/junOffline.d.ts +138 -0
  27. package/dist/runtime/utils/junOffline.js +73 -0
  28. package/dist/runtime/utils/junViewSpecs.d.ts +1 -1
  29. package/dist/types.d.mts +1 -1
  30. package/package.json +10 -8
@@ -9,6 +9,7 @@ import { useJunThemeTransition } from "./useJunThemeTransition.js";
9
9
  import { useJunPlayer } from "./useJunPlayer.js";
10
10
  import { useJunEffectiveConfig, useJunSiteConfig } from "./useJunSiteConfig.js";
11
11
  import { JUN_SETTINGS_SECTIONS, useJunSettings } from "./useJunSettings.js";
12
+ import { useJunOffline } from "./useJunOffline.js";
12
13
  const builders = [];
13
14
  export function registerJunCommands(builder) {
14
15
  builders.push(builder);
@@ -32,7 +33,7 @@ const PLACEMENTS = [
32
33
  ];
33
34
  export function useJunCommands() {
34
35
  const router = useRouter();
35
- const { features, navigation } = useJunOptions();
36
+ const { features, navigation, offline, pwa } = useJunOptions();
36
37
  const { canEdit, editMode, toggleEdit, openLogin } = useJunStudio();
37
38
  const { toggle: toggleTheme, isDark } = useJunThemeTransition();
38
39
  const player = useJunPlayer();
@@ -47,6 +48,7 @@ export function useJunCommands() {
47
48
  const currentSurface = computed(() => effective.value.themeSurface ?? SURFACE_DEFAULT);
48
49
  const currentPlacement = computed(() => effective.value.navPlacement ?? navigation.placement);
49
50
  const { openSettings } = useJunSettings();
51
+ const { openOffline } = useJunOffline();
50
52
  async function copyLink() {
51
53
  const url = new URL(router.currentRoute.value.fullPath, window.location.origin).href;
52
54
  try {
@@ -208,6 +210,17 @@ export function useJunCommands() {
208
210
  run: () => player.stop()
209
211
  });
210
212
  }
213
+ if (pwa && offline.enabled && effective.value.offlineOffer !== false) {
214
+ out.push({
215
+ key: "offline:panel",
216
+ label: "Save this site for offline",
217
+ icon: "i-lucide-cloud-download",
218
+ group: "This device",
219
+ hint: "Read with no connection",
220
+ keywords: ["offline", "download", "save", "cache", "storage", "pwa", "plane", "tunnel", "data"],
221
+ run: () => openOffline()
222
+ });
223
+ }
211
224
  out.push({
212
225
  key: "share:copy",
213
226
  label: "Copy link to this page",
@@ -0,0 +1,109 @@
1
+ import { type JunOfflineMode, type JunOfflineSection } from '../utils/junOffline.js';
2
+ /** What the last save actually stored, kept so the panel can say how old it is. */
3
+ export interface JunOfflineReceipt {
4
+ at: number;
5
+ pages: number;
6
+ assets: number;
7
+ bytes: number;
8
+ /**
9
+ * The build the copy was made from.
10
+ *
11
+ * The cache is named after the build, so a DEPLOY orphans a saved copy and
12
+ * the worker's `activate` deletes it. That is correct — a copy of pages whose
13
+ * assets no longer exist is not a copy — but it is invisible, and a visitor
14
+ * whose saved site quietly evaporated deserves to be told rather than to find
15
+ * out in a tunnel.
16
+ */
17
+ build: string;
18
+ /** Set when the save stopped early: `'budget'`. */
19
+ stopped?: string;
20
+ }
21
+ export interface JunOfflineManifest {
22
+ pages: string[];
23
+ sections: JunOfflineSection[];
24
+ count: number;
25
+ }
26
+ export declare function useJunOffline(): {
27
+ open: import("vue").Ref<boolean, boolean>;
28
+ openOffline: () => void;
29
+ /** Deferred to mount — every reader below is client-only state. */
30
+ mounted: import("vue").Ref<boolean, boolean>;
31
+ mode: import("vue").Ref<JunOfflineMode, JunOfflineMode>;
32
+ media: import("vue").Ref<boolean, boolean>;
33
+ policy: import("vue").ComputedRef<{
34
+ enabled: boolean;
35
+ fullSite: boolean;
36
+ media: boolean;
37
+ docSync: boolean;
38
+ budgetBytes: number;
39
+ defaultMode: JunOfflineMode;
40
+ }>;
41
+ manifest: import("vue").Ref<{
42
+ pages: string[];
43
+ sections: {
44
+ path: string;
45
+ label: string;
46
+ pages: {
47
+ path: string;
48
+ label: string;
49
+ section: string;
50
+ }[];
51
+ }[];
52
+ count: number;
53
+ } | null, JunOfflineManifest | {
54
+ pages: string[];
55
+ sections: {
56
+ path: string;
57
+ label: string;
58
+ pages: {
59
+ path: string;
60
+ label: string;
61
+ section: string;
62
+ }[];
63
+ }[];
64
+ count: number;
65
+ } | null>;
66
+ usage: import("vue").Ref<{
67
+ used: number;
68
+ quota: number;
69
+ } | null, {
70
+ used: number;
71
+ quota: number;
72
+ } | {
73
+ used: number;
74
+ quota: number;
75
+ } | null>;
76
+ receipt: import("vue").Ref<{
77
+ at: number;
78
+ pages: number;
79
+ assets: number;
80
+ bytes: number;
81
+ build: string;
82
+ stopped?: string | undefined;
83
+ } | null, JunOfflineReceipt | {
84
+ at: number;
85
+ pages: number;
86
+ assets: number;
87
+ bytes: number;
88
+ build: string;
89
+ stopped?: string | undefined;
90
+ } | null>;
91
+ receiptStale: import("vue").ComputedRef<boolean>;
92
+ saving: import("vue").Ref<boolean, boolean>;
93
+ savedCount: import("vue").Ref<number, number>;
94
+ savedTotal: import("vue").Ref<number, number>;
95
+ savedBytes: import("vue").Ref<number, number>;
96
+ progress: import("vue").ComputedRef<number>;
97
+ lastError: import("vue").Ref<string | null, string | null>;
98
+ syncing: import("vue").Ref<boolean, boolean>;
99
+ syncedDocs: import("vue").Ref<number, number>;
100
+ syncTotal: import("vue").Ref<number, number>;
101
+ syncDocuments: () => Promise<void>;
102
+ setMode: (next: JunOfflineMode) => Promise<void>;
103
+ setMedia: (next: boolean) => Promise<void>;
104
+ loadManifest: () => Promise<JunOfflineManifest | null>;
105
+ estimate: () => Promise<number>;
106
+ save: (paths?: string[]) => Promise<JunOfflineReceipt | null>;
107
+ purge: () => Promise<void>;
108
+ refreshUsage: () => Promise<void>;
109
+ };
@@ -0,0 +1,294 @@
1
+ import { computed, onMounted, ref } from "vue";
2
+ import { useRuntimeConfig } from "#app";
3
+ import { useAbracadabra, useJunEffectiveConfig, useJunOptions } from "#imports";
4
+ import {
5
+ JUN_OFFLINE_MEDIA_KEY,
6
+ JUN_OFFLINE_MODE_KEY,
7
+ JUN_OFFLINE_MODE_URL,
8
+ JUN_OFFLINE_SAVED_KEY,
9
+ junEstimateCopyBytes,
10
+ junOfflineBudgetBytes,
11
+ junOfflineCacheName,
12
+ junOfflineSavable,
13
+ junPageAssets,
14
+ junReadOfflineMode
15
+ } from "../utils/junOffline.js";
16
+ const open = ref(false);
17
+ const mounted = ref(false);
18
+ const mode = ref("visited");
19
+ const media = ref(false);
20
+ const receipt = ref(null);
21
+ const manifest = ref(null);
22
+ const usage = ref(null);
23
+ const syncing = ref(false);
24
+ const syncedDocs = ref(0);
25
+ const syncTotal = ref(0);
26
+ const saving = ref(false);
27
+ const savedCount = ref(0);
28
+ const savedTotal = ref(0);
29
+ const savedBytes = ref(0);
30
+ const lastError = ref(null);
31
+ let hydrated = false;
32
+ function readJson(key) {
33
+ try {
34
+ const raw = localStorage.getItem(key);
35
+ return raw ? JSON.parse(raw) : null;
36
+ } catch {
37
+ return null;
38
+ }
39
+ }
40
+ export function useJunOffline() {
41
+ const options = useJunOptions();
42
+ const config = useJunEffectiveConfig();
43
+ const runtime = useRuntimeConfig();
44
+ const build = runtime.app?.buildId ?? "dev";
45
+ const cacheName = junOfflineCacheName(build);
46
+ const apiBase = options.apiBase;
47
+ const policy = computed(() => {
48
+ const site = config.value;
49
+ const ceiling = options.offline;
50
+ return {
51
+ enabled: ceiling.enabled && site.offlineOffer !== false,
52
+ fullSite: ceiling.fullSite && site.offlineFullSite !== false,
53
+ media: site.offlineMedia ?? ceiling.media,
54
+ docSync: site.offlineDocSync ?? ceiling.docSync,
55
+ budgetBytes: junOfflineBudgetBytes(site.offlineBudgetMb ?? ceiling.budgetMb),
56
+ defaultMode: site.offlineDefault ?? ceiling.defaultMode
57
+ };
58
+ });
59
+ onMounted(() => {
60
+ mounted.value = true;
61
+ if (hydrated) return;
62
+ hydrated = true;
63
+ mode.value = junReadOfflineMode(localStorage.getItem(JUN_OFFLINE_MODE_KEY), policy.value.defaultMode);
64
+ media.value = localStorage.getItem(JUN_OFFLINE_MEDIA_KEY) === "1";
65
+ receipt.value = readJson(JUN_OFFLINE_SAVED_KEY);
66
+ void refreshUsage();
67
+ });
68
+ async function refreshUsage() {
69
+ try {
70
+ const estimate2 = await navigator.storage?.estimate?.();
71
+ if (estimate2) usage.value = { used: estimate2.usage ?? 0, quota: estimate2.quota ?? 0 };
72
+ } catch {
73
+ usage.value = null;
74
+ }
75
+ }
76
+ async function cache() {
77
+ return caches.open(cacheName);
78
+ }
79
+ function nudgeWorker() {
80
+ try {
81
+ navigator.serviceWorker?.controller?.postMessage("jun:mode-changed");
82
+ } catch {
83
+ }
84
+ }
85
+ async function writeMode(next) {
86
+ if (!("caches" in globalThis)) return;
87
+ const store = await cache();
88
+ await store.put(
89
+ JUN_OFFLINE_MODE_URL,
90
+ new Response(JSON.stringify({ mode: next }), { headers: { "content-type": "application/json" } })
91
+ );
92
+ }
93
+ async function setMode(next) {
94
+ mode.value = next;
95
+ try {
96
+ localStorage.setItem(JUN_OFFLINE_MODE_KEY, next);
97
+ } catch {
98
+ }
99
+ await writeMode(next);
100
+ nudgeWorker();
101
+ if (next === "off") await purge();
102
+ await refreshUsage();
103
+ }
104
+ async function setMedia(next) {
105
+ media.value = next;
106
+ try {
107
+ localStorage.setItem(JUN_OFFLINE_MEDIA_KEY, next ? "1" : "0");
108
+ } catch {
109
+ }
110
+ }
111
+ async function loadManifest() {
112
+ try {
113
+ const res = await fetch(`${apiBase}/offline`);
114
+ if (!res.ok) return null;
115
+ const body = await res.json();
116
+ if (!body || !Array.isArray(body.pages)) return null;
117
+ manifest.value = body;
118
+ return body;
119
+ } catch {
120
+ return null;
121
+ }
122
+ }
123
+ async function estimate() {
124
+ const list = manifest.value ?? await loadManifest();
125
+ if (!list?.count) return 0;
126
+ try {
127
+ const res = await fetch("/", { headers: { accept: "text/html" } });
128
+ const sample = (await res.arrayBuffer()).byteLength;
129
+ return junEstimateCopyBytes(sample, list.count);
130
+ } catch {
131
+ return 0;
132
+ }
133
+ }
134
+ async function save(paths) {
135
+ if (saving.value) return null;
136
+ if (!("caches" in globalThis)) {
137
+ lastError.value = "This browser has no Cache Storage.";
138
+ return null;
139
+ }
140
+ const list = paths ?? (manifest.value ?? await loadManifest())?.pages;
141
+ if (!list?.length) {
142
+ lastError.value = "Could not read the list of pages.";
143
+ return null;
144
+ }
145
+ const wanted = list.filter(junOfflineSavable);
146
+ saving.value = true;
147
+ lastError.value = null;
148
+ savedCount.value = 0;
149
+ savedTotal.value = wanted.length;
150
+ savedBytes.value = 0;
151
+ const store = await cache();
152
+ const budget = policy.value.budgetBytes;
153
+ const withMedia = media.value && policy.value.media;
154
+ const assets = /* @__PURE__ */ new Set();
155
+ let stopped;
156
+ let assetCount = 0;
157
+ try {
158
+ for (const path of wanted) {
159
+ if (savedBytes.value >= budget) {
160
+ stopped = "budget";
161
+ break;
162
+ }
163
+ try {
164
+ const res = await fetch(path, { headers: { accept: "text/html" } });
165
+ if (!res.ok || res.type !== "basic") continue;
166
+ const html = await res.clone().text();
167
+ savedBytes.value += new Blob([html]).size;
168
+ await store.put(path, res);
169
+ for (const asset of junPageAssets(html, { media: withMedia })) assets.add(asset);
170
+ } catch {
171
+ }
172
+ savedCount.value++;
173
+ }
174
+ for (const asset of assets) {
175
+ if (savedBytes.value >= budget) {
176
+ stopped = "budget";
177
+ break;
178
+ }
179
+ if (await store.match(asset)) continue;
180
+ try {
181
+ const res = await fetch(asset);
182
+ if (!res.ok || res.type !== "basic") continue;
183
+ savedBytes.value += Number(res.headers.get("content-length")) || 0;
184
+ await store.put(asset, res);
185
+ assetCount++;
186
+ } catch {
187
+ }
188
+ }
189
+ const saved = {
190
+ at: Date.now(),
191
+ pages: savedCount.value,
192
+ assets: assetCount,
193
+ bytes: savedBytes.value,
194
+ build,
195
+ ...stopped ? { stopped } : {}
196
+ };
197
+ receipt.value = saved;
198
+ try {
199
+ localStorage.setItem(JUN_OFFLINE_SAVED_KEY, JSON.stringify(saved));
200
+ } catch {
201
+ }
202
+ if (mode.value !== "site") await setMode("site");
203
+ await refreshUsage();
204
+ return saved;
205
+ } finally {
206
+ saving.value = false;
207
+ }
208
+ }
209
+ async function purge() {
210
+ if (!("caches" in globalThis)) return;
211
+ await caches.delete(cacheName);
212
+ receipt.value = null;
213
+ try {
214
+ localStorage.removeItem(JUN_OFFLINE_SAVED_KEY);
215
+ } catch {
216
+ }
217
+ await writeMode(mode.value);
218
+ nudgeWorker();
219
+ await refreshUsage();
220
+ }
221
+ async function syncDocuments() {
222
+ if (syncing.value) return;
223
+ const { provider, client } = useAbracadabra();
224
+ if (!provider.value || !client.value) {
225
+ lastError.value = "Not connected yet.";
226
+ return;
227
+ }
228
+ syncing.value = true;
229
+ syncedDocs.value = 0;
230
+ syncTotal.value = 0;
231
+ try {
232
+ const { BackgroundSyncManager } = await import("@abraca/dabra");
233
+ const manager = new BackgroundSyncManager(provider.value, client.value, null, {
234
+ // Two at a time, with a gap. This opens a real WebSocket per document
235
+ // against the site's own backend; a visitor's button press must not
236
+ // look like a load test, and the server caps connections per IP —
237
+ // everything past the cap gets 429 and never syncs at all.
238
+ concurrency: 2,
239
+ throttleMs: 200,
240
+ // Files are the heavy half here exactly as images are for the pages,
241
+ // and the panel's media switch is about the PAGE copy. Prefetching
242
+ // every upload from a button labelled "keep the documents" would be
243
+ // the same silent download wearing a different name.
244
+ prefetchFiles: false
245
+ });
246
+ await manager.init();
247
+ const states = manager.getSyncStatus();
248
+ syncTotal.value = states.size;
249
+ await manager.syncAll();
250
+ syncedDocs.value = [...manager.getSyncStatus().values()].filter((state) => state.status === "synced").length;
251
+ syncTotal.value = manager.getSyncStatus().size;
252
+ manager.destroy();
253
+ await refreshUsage();
254
+ } catch (err) {
255
+ lastError.value = err instanceof Error ? err.message : "Could not sync the documents.";
256
+ } finally {
257
+ syncing.value = false;
258
+ }
259
+ }
260
+ const receiptStale = computed(() => !!receipt.value && receipt.value.build !== build);
261
+ const progress = computed(() => savedTotal.value > 0 ? Math.min(1, savedCount.value / savedTotal.value) : 0);
262
+ return {
263
+ open,
264
+ openOffline: () => {
265
+ open.value = true;
266
+ },
267
+ /** Deferred to mount — every reader below is client-only state. */
268
+ mounted,
269
+ mode,
270
+ media,
271
+ policy,
272
+ manifest,
273
+ usage,
274
+ receipt,
275
+ receiptStale,
276
+ saving,
277
+ savedCount,
278
+ savedTotal,
279
+ savedBytes,
280
+ progress,
281
+ lastError,
282
+ syncing,
283
+ syncedDocs,
284
+ syncTotal,
285
+ syncDocuments,
286
+ setMode,
287
+ setMedia,
288
+ loadManifest,
289
+ estimate,
290
+ save,
291
+ purge,
292
+ refreshUsage
293
+ };
294
+ }
@@ -1,4 +1,4 @@
1
- export type JunSettingsSection = 'identity' | 'navigation' | 'mark' | 'theme' | 'announcement' | 'campfire' | 'footer' | 'visitors' | 'renderers';
1
+ export type JunSettingsSection = 'identity' | 'navigation' | 'mark' | 'theme' | 'announcement' | 'campfire' | 'footer' | 'visitors' | 'offline' | 'renderers';
2
2
  export interface JunSettingsSectionDef {
3
3
  id: JunSettingsSection;
4
4
  label: string;
@@ -8,6 +8,8 @@ export const JUN_SETTINGS_SECTIONS = [
8
8
  { id: "campfire", label: "User center", icon: "i-lucide-flame", hint: "Chat, presence, reactions" },
9
9
  { id: "footer", label: "Footer", icon: "i-lucide-panel-bottom", hint: "The line at the bottom" },
10
10
  { id: "visitors", label: "Visitors", icon: "i-lucide-users", hint: "Guestbook, feeds, people" },
11
+ // After Visitors, because it is about what a visitor may take away with them.
12
+ { id: "offline", label: "Offline", icon: "i-lucide-cloud-download", hint: "What a reader may keep on their device" },
11
13
  // Last, because it is the only section that configures CONTENT rather than
12
14
  // chrome — and the only one whose controls are generated from the renderers'
13
15
  // own specs rather than written out here.
@@ -86,6 +86,25 @@ export interface JunSiteConfig {
86
86
  seoSiteUrl?: string;
87
87
  /** The site's language for `<html lang>` — a BCP-47 tag. */
88
88
  seoLang?: string;
89
+ /**
90
+ * Offline — what a visitor may keep on their own device.
91
+ *
92
+ * Every key here LOWERS a ceiling the build already set (`jun.offline`), and
93
+ * none of them downloads anything: the default posture is "the pages this
94
+ * reader opened", and a whole-site copy is something they press a button for.
95
+ * Unset means the build's answer throughout.
96
+ */
97
+ offlineOffer?: boolean;
98
+ /** May a visitor save the whole site in one press? */
99
+ offlineFullSite?: boolean;
100
+ /** May images be part of a saved copy? The heavy half — off by default. */
101
+ offlineMedia?: boolean;
102
+ /** Ceiling on one saved copy, in megabytes. */
103
+ offlineBudgetMb?: number;
104
+ /** Offer the CRDT half: every document into IndexedDB. Owner-only. */
105
+ offlineDocSync?: boolean;
106
+ /** What a device that has never chosen gets. Never `site` — see the option type. */
107
+ offlineDefault?: 'off' | 'visited';
89
108
  /** Swipe left/right to reach the next or previous page. Unset means on. */
90
109
  gesturePages?: boolean;
91
110
  /** Swipe in from a screen edge to open the navigation menu. Unset means on. */
@@ -15,7 +15,7 @@ import {
15
15
  useJunStudio,
16
16
  useJunThemeApply
17
17
  } from "#imports";
18
- const { features, contextMenu } = useJunOptions();
18
+ const { features, contextMenu, offline, pwa } = useJunOptions();
19
19
  const { kind: backdropKind } = useJunBackdrop();
20
20
  const backdropComponent = computed(() => {
21
21
  if (backdropKind.value === "shader") return resolveComponent("JunShaderBackdrop");
@@ -31,6 +31,7 @@ const campfireLit = computed(() => campfireSettings.value.enabled);
31
31
  const { contentVeiled } = useJunIntro();
32
32
  if (features.presence) useJunPresenceBroadcast();
33
33
  const effectiveConfig = useJunEffectiveConfig();
34
+ const offlineOffered = computed(() => pwa && offline.enabled && effectiveConfig.value.offlineOffer !== false);
34
35
  const presenceBlobsLit = computed(() => {
35
36
  if (!features.presence || !features.awareBlobs) return false;
36
37
  const stored = effectiveConfig.value.presenceBlobs;
@@ -111,7 +112,10 @@ if (import.meta.client && contextMenu.suppressNative) {
111
112
  :class="contentVeiled ? 'jun-content-veiled' : ''"
112
113
  >
113
114
  <JunShell>
114
- <UMain id="jun-main" tabindex="-1">
115
+ <UMain
116
+ id="jun-main"
117
+ tabindex="-1"
118
+ >
115
119
  <slot />
116
120
  </UMain>
117
121
 
@@ -177,6 +181,12 @@ if (import.meta.client && contextMenu.suppressNative) {
177
181
  > which is what pointed at shared state rather than node position. -->
178
182
  <JunSettings />
179
183
 
184
+ <!-- The visitor's own panel — what this SITE keeps on THIS device. Mounted
185
+ beside the settings for the same reason: the palette and the navigation
186
+ menu both open it, and neither is inside it. Renders nothing until
187
+ somebody asks, and not at all on a site with the PWA switched off. -->
188
+ <JunOfflinePanel v-if="offlineOffered" />
189
+
180
190
  <!-- Every renderer's media taps route here. Mounted once. -->
181
191
  <JunImagePopup v-if="features.lightbox" />
182
192
 
@@ -0,0 +1,10 @@
1
+ import { type JunOfflineSection } from '../../utils/junOffline.js';
2
+ export interface JunOfflineManifest {
3
+ /** Every savable path, in navigation order, front page first. */
4
+ pages: string[];
5
+ /** The same pages grouped under their top-level section, for the panel. */
6
+ sections: JunOfflineSection[];
7
+ count: number;
8
+ }
9
+ declare const _default: import("h3").EventHandler<import("h3").EventHandlerRequest, Promise<JunOfflineManifest>>;
10
+ export default _default;
@@ -0,0 +1,13 @@
1
+ import { defineEventHandler, setResponseHeader } from "h3";
2
+ import { junPublicPages } from "../utils/junPages.js";
3
+ import { junGroupOfflinePages } from "../../utils/junOffline.js";
4
+ export default defineEventHandler(async (event) => {
5
+ const pages = await junPublicPages();
6
+ setResponseHeader(event, "cache-control", "public, max-age=30");
7
+ const flat = pages.map((p) => ({ path: p.path, label: p.label, section: p.section }));
8
+ return {
9
+ pages: flat.map((p) => p.path),
10
+ sections: junGroupOfflinePages(flat),
11
+ count: flat.length
12
+ };
13
+ });
@@ -0,0 +1,2 @@
1
+ declare const _default: import("nitropack").NitroAppPlugin;
2
+ export default _default;
@@ -0,0 +1,76 @@
1
+ import { defineNitroPlugin } from "nitropack/runtime";
2
+ import { promisify } from "node:util";
3
+ import { brotliCompress, constants, gzip } from "node:zlib";
4
+ const brotli = promisify(brotliCompress);
5
+ const gzipAsync = promisify(gzip);
6
+ const MIN_BYTES = 1024;
7
+ function isCompressible(type) {
8
+ if (!type) return false;
9
+ const value = type.toLowerCase();
10
+ return value.startsWith("text/") || value.includes("json") || value.includes("javascript") || value.includes("xml") || value.includes("+html") || value.includes("manifest");
11
+ }
12
+ function pickEncoding(accept) {
13
+ if (!accept) return null;
14
+ const value = accept.toLowerCase();
15
+ if (value.includes("br")) return "br";
16
+ if (value.includes("gzip")) return "gzip";
17
+ return null;
18
+ }
19
+ function isPlainData(body) {
20
+ if (typeof body !== "object" || body === null) return false;
21
+ if (Buffer.isBuffer(body)) return false;
22
+ if (body instanceof Error) return false;
23
+ const candidate = body;
24
+ if (typeof candidate.arrayBuffer === "function") return false;
25
+ if (typeof candidate.pipe === "function" || typeof candidate.pipeTo === "function") return false;
26
+ if (typeof candidate.end === "function") return false;
27
+ if (candidate.buffer !== void 0) return false;
28
+ if (Symbol.asyncIterator in candidate) return false;
29
+ return true;
30
+ }
31
+ export default defineNitroPlugin((nitroApp) => {
32
+ nitroApp.hooks.hook("beforeResponse", async (event, response) => {
33
+ const body = response?.body;
34
+ const res = event.node.res;
35
+ if (res.headersSent) return;
36
+ if (res.getHeader("content-encoding")) return;
37
+ let raw;
38
+ if (typeof body === "string" || Buffer.isBuffer(body)) {
39
+ if (!isCompressible(String(res.getHeader("content-type") ?? ""))) return;
40
+ raw = Buffer.isBuffer(body) ? body : Buffer.from(body, "utf8");
41
+ } else if (isPlainData(body)) {
42
+ const existing = String(res.getHeader("content-type") ?? "");
43
+ if (existing && !isCompressible(existing)) return;
44
+ try {
45
+ raw = Buffer.from(JSON.stringify(body), "utf8");
46
+ } catch {
47
+ return;
48
+ }
49
+ if (!existing) res.setHeader("content-type", "application/json;charset=utf-8");
50
+ } else {
51
+ return;
52
+ }
53
+ if (raw.byteLength < MIN_BYTES) return;
54
+ const encoding = pickEncoding(event.node.req.headers["accept-encoding"]);
55
+ if (!encoding) return;
56
+ try {
57
+ const packed = encoding === "br" ? await brotli(raw, {
58
+ // Quality 4 — this is on the request's critical path. See the
59
+ // header: 11 is a build-time setting and costs tens of ms here.
60
+ params: {
61
+ [constants.BROTLI_PARAM_QUALITY]: 4,
62
+ [constants.BROTLI_PARAM_SIZE_HINT]: raw.byteLength
63
+ }
64
+ }) : await gzipAsync(raw, { level: 6 });
65
+ if (packed.byteLength >= raw.byteLength) return;
66
+ res.setHeader("content-encoding", encoding);
67
+ res.setHeader("content-length", packed.byteLength);
68
+ const vary = String(res.getHeader("vary") ?? "");
69
+ if (!vary.toLowerCase().includes("accept-encoding")) {
70
+ res.setHeader("vary", vary ? `${vary}, Accept-Encoding` : "Accept-Encoding");
71
+ }
72
+ response.body = packed;
73
+ } catch {
74
+ }
75
+ });
76
+ });