@hagicode/hagilight-core 0.13.1-dev.142.1.f7670b5 → 0.14.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/README.md CHANGED
@@ -52,7 +52,9 @@ Create the destination page first, for example `src/pages/en-US/index.astro`.
52
52
  The component includes the official root transit's layout, dark/light colors,
53
53
  system font stacks, outline-to-solid route sweep, beam, staggered trace and
54
54
  continuation chip. It bundles its logo and favicon locally; no custom CSS,
55
- animation setup, feature package, third-party resource or analytics is required.
55
+ animation setup, feature package or analytics is required. By default it also
56
+ requests one image from `img-gen.hagicode.com`; the [splash image](#splash-image)
57
+ section describes that request and how to switch it off.
56
58
  The trace shows the actual configured destination, base and origin rather than
57
59
  performing the official website's locale detection. Installing core alone never
58
60
  changes routes. Consumers that do not import this page keep their current root.
@@ -101,6 +103,100 @@ official site's `dist` directory. Matching 1440/375 px captures at 625/1,250 ms
101
103
  are written to `HAGILIGHT_ARTIFACT_DIR` (default `/tmp/hagilight-root-transit`),
102
104
  alongside 320/375/1440 px light/dark, minimal-consumer and base-path captures.
103
105
 
106
+ ### Splash image
107
+
108
+ While the page forwards, `RootTransit` shows one image picked at random from the
109
+ img-gen `startup-splash` collection (`hagicode-splash-001` to `hagicode-splash-600`,
110
+ see [Image paths from img-gen](#image-paths-from-img-gen)). It is on by default. A
111
+ visit makes one request to `img-gen.hagicode.com` for an AVIF of about 20 to 50 KB,
112
+ after the page has mounted. The image is decorative, sits behind the content and takes
113
+ no layout space, so the heading, trace and links stay where they are. The splash never
114
+ delays the forward timer or a continuation click.
115
+
116
+ If the chosen image fails, one other key is tried. A second failure hides the image
117
+ with no visible message. A cache read waits at most 100 ms, and the page then
118
+ requests the network URL. The loaded image is stored in the Cache API for later
119
+ visits when the host sends CORS headers; without them the image still displays.
120
+
121
+ Pass `splash` to change it. `splash={false}` renders no splash markup and makes no request to
122
+ the image host. An object overrides any of these keys; other keys are rejected.
123
+
124
+ | Key | Default | Accepted values |
125
+ | --- | --- | --- |
126
+ | `baseUrl` | `https://img-gen.hagicode.com` | An HTTPS URL without credentials, query or fragment. A trailing slash is removed. |
127
+ | `prefix` | `startup-splash` | Letters, digits, `.`, `_` and `-` segments joined by `/`. No empty, `.` or `..` segment. |
128
+ | `count` | `600` | An integer from 1 to 9999. Keys are `hagicode-splash-001` upward. |
129
+ | `cacheName` | `hagilight.rootTransit.splash` | A non-empty string. |
130
+
131
+ The key pattern is the img-gen contract and cannot be changed. An invalid value throws a
132
+ `TypeError` prefixed `Hagilight RootTransit` during rendering.
133
+
134
+ ```astro
135
+ <RootTransit destination="/en-US/" siteName="My site" splash={false} />
136
+ <RootTransit destination="/en-US/" siteName="My site" splash={{ count: 120 }} />
137
+ ```
138
+
139
+ A site whose Content Security Policy blocks the image host should either set
140
+ `splash={false}` or allow `img-src https://img-gen.hagicode.com` and
141
+ `connect-src https://img-gen.hagicode.com`.
142
+
143
+ ## Image paths from img-gen
144
+
145
+ <!--
146
+ Checked 2026-10-20 (OpenSpec task 1.1): `https://img-gen.hagicode.com/startup-splash/manifest.json` lists 600
147
+ entries, `hagicode-splash-001` to `hagicode-splash-600`, all unique and all 1232 x 704. The manifest and an AVIF
148
+ response both send no `Access-Control-Allow-Origin` header. A Cache API write downloads with CORS, so it fails
149
+ until img-gen sends that header. `<img>` display needs no CORS and is unaffected.
150
+ -->
151
+
152
+ `@hagicode/hagilight-core/splash-images` gives other HagiCode sites the image paths of the img-gen
153
+ `startup-splash` collection. img-gen is read only here: the host serves what img-gen publishes.
154
+
155
+ | Part | Value |
156
+ | --- | --- |
157
+ | Base URL | `https://img-gen.hagicode.com` |
158
+ | Prefix | `startup-splash` |
159
+ | File name | `hagicode-splash-NNN.avif`, with NNN padded to three digits |
160
+ | Range | 1 to 600 |
161
+ | Size | 1232 x 704 AVIF |
162
+ | Authoritative list | `https://img-gen.hagicode.com/startup-splash/manifest.json` |
163
+
164
+ The manifest lists `entries[]`, each with `key`, `file`, `width`, `height` and `bytes`. A site that needs only the
165
+ images that exist should read it. A site that can tolerate a failed image may build paths from the key pattern
166
+ directly, as the relay page does. The key pattern is the img-gen contract, so `SPLASH_IMAGE_DEFAULTS` does not
167
+ change it.
168
+
169
+ Worked example: index 7 becomes key `hagicode-splash-007`, then the URL
170
+ `https://img-gen.hagicode.com/startup-splash/hagicode-splash-007.avif`.
171
+
172
+ ```js
173
+ import { pickSplashIndex, splashImageUrl } from '@hagicode/hagilight-core/splash-images';
174
+
175
+ splashImageUrl(7); // https://img-gen.hagicode.com/startup-splash/hagicode-splash-007.avif
176
+ splashImageUrl(pickSplashIndex()); // one of the 600 keys, at random
177
+ ```
178
+
179
+ Cache API example for another site. The loader reads the Cache API within 100 ms and never rejects. A miss or an
180
+ unavailable cache means the caller shows the network URL. A stored image is keyed by its full URL.
181
+
182
+ ```js
183
+ import { loadSplashImage, splashImageUrl, storeSplashImage } from '@hagicode/hagilight-core/splash-images';
184
+
185
+ const url = splashImageUrl(pickSplashIndex());
186
+ const loaded = await loadSplashImage(url);
187
+ if (loaded.source === 'cache') {
188
+ img.src = URL.createObjectURL(loaded.blob);
189
+ } else {
190
+ img.src = url;
191
+ img.addEventListener('load', () => storeSplashImage(url), { once: true });
192
+ }
193
+ ```
194
+
195
+ `storeSplashImage` downloads with a CORS `fetch` and keeps the 30 newest entries. It returns `false` when the host
196
+ sends no CORS header or the cache is unavailable, and the page still shows the image. A site with a Content
197
+ Security Policy needs `img-src https://img-gen.hagicode.com` to show the images, and `connect-src
198
+ https://img-gen.hagicode.com` for the store step.
199
+
104
200
  ## Build info
105
201
 
106
202
  `@hagicode/hagilight-core/build-info` is browser-safe. It exports the `BuildInfo` type, `normalizeBuildInfo`, `shortCommit`, and `buildInfoItems`, which turn a resolved value into the footer's Branch, Commit, and Built items. `@hagicode/hagilight-core/build-info-resolver` is Node-only: `resolveBuildInfo({ root, env, now })` reads the value for one project. Keep Node-only code out of any module that a browser bundle imports.
package/RootTransit.astro CHANGED
@@ -2,6 +2,7 @@
2
2
  import logo from './logo.png';
3
3
  import favicon from './favicon.ico';
4
4
  import { resolveTransitDestination } from './dist/root-transit.js';
5
+ import { resolveSplashConfig, type SplashOverrides } from './dist/splash-images.js';
5
6
 
6
7
  interface Props {
7
8
  destination: string;
@@ -11,6 +12,8 @@ interface Props {
11
12
  message?: string;
12
13
  continueLabel?: string;
13
14
  links?: { destination: string; label: string; lang?: string }[];
15
+ /** `false` turns the splash off; an object overrides its base URL, prefix, collection size or cache name. */
16
+ splash?: false | SplashOverrides;
14
17
  }
15
18
 
16
19
  const {
@@ -19,8 +22,10 @@ const {
19
22
  message = 'You will continue automatically. You can also continue now.',
20
23
  continueLabel = `Continue to ${siteName}`,
21
24
  links = [],
25
+ splash,
22
26
  } = Astro.props;
23
27
  if (!siteName?.trim()) throw new TypeError('Hagilight RootTransit: siteName is required.');
28
+ const splashConfig = resolveSplashConfig(splash);
24
29
  const base = import.meta.env.BASE_URL;
25
30
  const site = Astro.site ?? Astro.url;
26
31
  const href = resolveTransitDestination(destination, { site, base });
@@ -74,6 +79,8 @@ const trace = [
74
79
  --font-sans: "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei UI", "Microsoft YaHei", "Noto Sans CJK SC", "Noto Sans SC", "Source Han Sans SC", "WenQuanYi Micro Hei", "Segoe UI", system-ui, sans-serif;
75
80
  --font-mono: "SF Mono", Menlo, "Cascadia Code", Consolas, "Roboto Mono", "JetBrains Mono", monospace;
76
81
  --ease-out: cubic-bezier(0.16, 1, 0.3, 1);
82
+ /* Share of the page background laid over the splash image; keeps muted text readable on bright artwork. */
83
+ --splash-scrim: 84%;
77
84
  }
78
85
 
79
86
  :global(:root[data-hagilight-transit][data-theme='light']) {
@@ -137,8 +144,41 @@ const trace = [
137
144
  outline-offset: 3px;
138
145
  }
139
146
 
147
+ /* ── 启动图层:装饰性,在页面之后,不占布局空间;未显示时透明 ── */
148
+ .splash {
149
+ position: fixed;
150
+ inset: 0;
151
+ z-index: 0;
152
+ margin: 0;
153
+ overflow: hidden;
154
+ pointer-events: none;
155
+ opacity: 0;
156
+ transition: opacity 600ms var(--ease-out);
157
+ }
158
+
159
+ .splash[data-state='shown'] {
160
+ opacity: 1;
161
+ }
162
+
163
+ .splash img {
164
+ display: block;
165
+ width: 100%;
166
+ height: 100%;
167
+ object-fit: cover;
168
+ }
169
+
170
+ /* 遮罩:标题与轨迹压在亮图上时仍保持可读 */
171
+ .splash::after {
172
+ content: '';
173
+ position: absolute;
174
+ inset: 0;
175
+ background: color-mix(in srgb, var(--bg) var(--splash-scrim), transparent);
176
+ }
177
+
140
178
  /* ── 页面骨架 ── */
141
179
  .page {
180
+ position: relative;
181
+ z-index: 1;
142
182
  display: grid;
143
183
  grid-template-rows: auto 1fr auto;
144
184
  gap: clamp(1.5rem, 5vh, 3rem);
@@ -503,6 +543,7 @@ const trace = [
503
543
 
504
544
  @media (prefers-reduced-motion: reduce) {
505
545
  *, *::before, *::after { animation: none !important; transition: none !important; }
546
+ .splash { transition: none; }
506
547
  .run { --run: 1; }
507
548
  .locales a:hover {
508
549
  transform: none;
@@ -510,6 +551,7 @@ const trace = [
510
551
  }
511
552
 
512
553
  @media (forced-colors: active) {
554
+ .splash { display: none; }
513
555
  .locales a[aria-current='true'] {
514
556
  outline: 2px solid Highlight;
515
557
  forced-color-adjust: none;
@@ -522,6 +564,11 @@ const trace = [
522
564
  </style>
523
565
  </head>
524
566
  <body>
567
+ {splashConfig && (
568
+ <figure class="splash" data-splash aria-hidden="true" data-splash-base={splashConfig.baseUrl} data-splash-prefix={splashConfig.prefix} data-splash-count={splashConfig.count} data-splash-cache={splashConfig.cacheName}>
569
+ <img alt="" decoding="async" fetchpriority="low" />
570
+ </figure>
571
+ )}
525
572
  <div class="page" data-root-transit data-base={base}>
526
573
  <header>
527
574
  <span class="brand"><img src={logo.src} width="28" height="28" alt="" />{siteName}</span>
@@ -346,5 +346,33 @@
346
346
  "ru-RU": "Пошаговое руководство по становлению full-stack инженером в эпоху ИИ."
347
347
  },
348
348
  "url": "https://fullstack.hagicode.com/"
349
+ },
350
+ {
351
+ "id": "gallery",
352
+ "name": {
353
+ "zh-CN": "HagiCode Gallery",
354
+ "zh-Hant": "HagiCode Gallery",
355
+ "en-US": "HagiCode Gallery",
356
+ "ja-JP": "HagiCode Gallery",
357
+ "ko-KR": "HagiCode Gallery",
358
+ "de-DE": "HagiCode Gallery",
359
+ "fr-FR": "HagiCode Gallery",
360
+ "es-ES": "HagiCode Gallery",
361
+ "pt-BR": "HagiCode Gallery",
362
+ "ru-RU": "HagiCode Gallery"
363
+ },
364
+ "description": {
365
+ "zh-CN": "HagiCode 作品的静态展示画廊。",
366
+ "zh-Hant": "HagiCode 作品的靜態展示畫廊。",
367
+ "en-US": "A gallery of HagiCode work, shared as static pages.",
368
+ "ja-JP": "HagiCode の作品を静的ページで紹介するギャラリーです。",
369
+ "ko-KR": "HagiCode 작업물을 정적 페이지로 공유하는 갤러리입니다.",
370
+ "de-DE": "Galerie mit HagiCode-Arbeiten als statische Seiten.",
371
+ "fr-FR": "Galerie de réalisations HagiCode, partagée sous forme de pages statiques.",
372
+ "es-ES": "Galería de trabajos de HagiCode, compartida como páginas estáticas.",
373
+ "pt-BR": "Galeria de trabalhos do HagiCode, compartilhada como páginas estáticas.",
374
+ "ru-RU": "Галерея работ HagiCode в виде статических страниц."
375
+ },
376
+ "url": "https://gallery.hagicode.com/"
349
377
  }
350
378
  ]
@@ -1,5 +1,8 @@
1
+ import { SPLASH_IMAGE_DEFAULTS, loadSplashImage, pickSplashIndex, splashImageUrl, storeSplashImage, } from './splash-images.js';
1
2
  /** The reference route sweep (1,250 ms) and finished-state hold (320 ms). */
2
3
  export const ROOT_TRANSIT_DELAY_MS = 1570;
4
+ /** Idle-time limit for storing a loaded splash image, so the store never waits on the page. */
5
+ const SPLASH_STORE_IDLE_TIMEOUT_MS = 1000;
3
6
  /** Resolve a configured local route, applying the deployment base at most once. */
4
7
  export function resolveTransitDestination(destination, { site, base = '/' }) {
5
8
  const fail = (reason) => { throw new TypeError(`Hagilight RootTransit: ${reason}`); };
@@ -53,6 +56,112 @@ export function resolveTransitNavigation(destination, current, base = '/') {
53
56
  return `${target.pathname}${target.search}${target.hash}`;
54
57
  }
55
58
  const mounted = new WeakMap();
59
+ /**
60
+ * The decorative splash: one random image, started from a macrotask after the page is mounted. Nothing awaits it.
61
+ * A failed first image is retried once with another key; a second failure removes the figure. Every path ends in
62
+ * `release`, which drops the handlers, revokes any object URL and detaches the image.
63
+ */
64
+ function mountSplash(win, doc) {
65
+ const figure = doc.querySelector('[data-splash]');
66
+ const img = figure?.querySelector('img');
67
+ if (!figure || !img)
68
+ return () => { };
69
+ const config = {
70
+ baseUrl: figure.dataset.splashBase ?? '',
71
+ prefix: figure.dataset.splashPrefix ?? '',
72
+ count: Number(figure.dataset.splashCount),
73
+ cacheName: figure.dataset.splashCache ?? '',
74
+ };
75
+ const storage = win.caches ?? null;
76
+ const fetchImage = (target) => win.fetch(target, { mode: 'cors', credentials: 'omit' });
77
+ let active = true;
78
+ let index = 0;
79
+ let retried = false;
80
+ let networkUrl;
81
+ let objectUrl;
82
+ let startTimer;
83
+ const forgetObjectUrl = () => {
84
+ if (objectUrl)
85
+ URL.revokeObjectURL(objectUrl);
86
+ objectUrl = undefined;
87
+ };
88
+ const release = () => {
89
+ if (!active)
90
+ return;
91
+ active = false;
92
+ win.clearTimeout(startTimer);
93
+ img.removeEventListener('load', onLoad);
94
+ img.removeEventListener('error', onError);
95
+ forgetObjectUrl();
96
+ img.removeAttribute('src');
97
+ };
98
+ const attempt = (step) => {
99
+ try {
100
+ step();
101
+ }
102
+ catch {
103
+ figure.remove();
104
+ release();
105
+ }
106
+ };
107
+ const whenIdle = (task) => {
108
+ if (typeof win.requestIdleCallback === 'function')
109
+ win.requestIdleCallback(task, { timeout: SPLASH_STORE_IDLE_TIMEOUT_MS });
110
+ else
111
+ win.setTimeout(task, 0);
112
+ };
113
+ const onLoad = () => attempt(() => {
114
+ if (!active)
115
+ return;
116
+ figure.dataset.state = 'shown';
117
+ const url = networkUrl;
118
+ if (url)
119
+ whenIdle(() => { if (active)
120
+ void storeSplashImage(url, { storage, fetchImage, cacheName: config.cacheName }); });
121
+ });
122
+ const onError = () => attempt(() => {
123
+ if (!active)
124
+ return;
125
+ if (!retried && config.count > 1) {
126
+ retried = true;
127
+ const next = pickSplashIndex(Math.random, config.count - 1);
128
+ index = next >= index ? next + 1 : next;
129
+ forgetObjectUrl();
130
+ networkUrl = splashImageUrl(index, config);
131
+ img.src = networkUrl;
132
+ return;
133
+ }
134
+ figure.remove();
135
+ release();
136
+ });
137
+ const load = async (picked) => {
138
+ index = picked;
139
+ const url = splashImageUrl(picked, config);
140
+ const loaded = await loadSplashImage(url, { storage, cacheName: config.cacheName, budgetMs: SPLASH_IMAGE_DEFAULTS.readBudgetMs });
141
+ if (!active)
142
+ return;
143
+ if (loaded.source === 'cache') {
144
+ objectUrl = URL.createObjectURL(loaded.blob);
145
+ img.src = objectUrl;
146
+ }
147
+ else {
148
+ networkUrl = url;
149
+ img.src = url;
150
+ }
151
+ };
152
+ img.addEventListener('load', onLoad);
153
+ img.addEventListener('error', onError);
154
+ startTimer = win.setTimeout(() => {
155
+ startTimer = undefined;
156
+ try {
157
+ load(pickSplashIndex(Math.random, config.count)).catch(release);
158
+ }
159
+ catch {
160
+ release();
161
+ }
162
+ }, 0);
163
+ return release;
164
+ }
56
165
  /** Mount once per rendered root; decoration never controls the navigation clock. */
57
166
  export function mountRootTransit(win = window) {
58
167
  const doc = win.document;
@@ -73,9 +182,11 @@ export function mountRootTransit(win = window) {
73
182
  }
74
183
  let finished = false;
75
184
  let timer;
185
+ let releaseSplash = () => { };
76
186
  const cleanup = () => {
77
187
  finished = true;
78
188
  win.clearTimeout(timer);
189
+ releaseSplash();
79
190
  win.removeEventListener('pagehide', cleanup);
80
191
  doc.removeEventListener('astro:before-swap', cleanup);
81
192
  for (const link of links)
@@ -99,6 +210,12 @@ export function mountRootTransit(win = window) {
99
210
  link.addEventListener('click', continueNow);
100
211
  win.addEventListener('pagehide', cleanup);
101
212
  doc.addEventListener('astro:before-swap', cleanup);
213
+ try {
214
+ releaseSplash = mountSplash(win, doc);
215
+ }
216
+ catch {
217
+ releaseSplash = () => { };
218
+ }
102
219
  doc.documentElement.dataset.transitReady = 'true';
103
220
  return cleanup;
104
221
  }
@@ -0,0 +1,75 @@
1
+ /**
2
+ * Public image contract for the img-gen `startup-splash` collection.
3
+ *
4
+ * Browser-safe: no `node:` import and no file system access. The cache storage, fetch and random source are
5
+ * parameters so tests can replace them. The loaders never reject: any failure reads as a miss.
6
+ */
7
+ export interface SplashConfig {
8
+ readonly baseUrl: string;
9
+ readonly prefix: string;
10
+ readonly count: number;
11
+ readonly cacheName: string;
12
+ }
13
+ /** The overridable keys. `readBudgetMs` and `maxEntries` are fixed defaults, not consumer options. */
14
+ export interface SplashOverrides {
15
+ readonly baseUrl?: string;
16
+ readonly prefix?: string;
17
+ readonly count?: number;
18
+ readonly cacheName?: string;
19
+ }
20
+ export declare const SPLASH_IMAGE_DEFAULTS: Readonly<{
21
+ baseUrl: "https://img-gen.hagicode.com";
22
+ prefix: "startup-splash";
23
+ count: 600;
24
+ cacheName: "hagilight.rootTransit.splash";
25
+ readBudgetMs: 100;
26
+ maxEntries: 30;
27
+ }>;
28
+ /**
29
+ * Resolves the `splash` option. `false` disables the splash (returns null); `undefined` gives the defaults; an
30
+ * object overrides the listed keys. Throws a `TypeError` for any invalid value, so bad config fails the build.
31
+ */
32
+ export declare function resolveSplashConfig(input?: false | SplashOverrides): SplashConfig | null;
33
+ /** Maps an index from 1 to `count` to its key, for example 7 to `hagicode-splash-007`. */
34
+ export declare function splashKey(index: number, count?: number): string;
35
+ /**
36
+ * The path below the base URL, `<prefix>/<key>.avif`, for a key or an index. A string must be a key of the
37
+ * collection: `hagicode-splash-` followed by its number, padded to three digits, within the count.
38
+ */
39
+ export declare function splashImagePath(keyOrIndex: number | string, config?: SplashConfig): string;
40
+ /** The full image URL: the base URL joined with `splashImagePath`. */
41
+ export declare function splashImageUrl(keyOrIndex: number | string, config?: SplashConfig): string;
42
+ /**
43
+ * A 1-based index from `random`, which returns a value in [0, 1). Out-of-range or non-finite results are clamped,
44
+ * so the result is always within 1 to `count`.
45
+ */
46
+ export declare function pickSplashIndex(random?: () => number, count?: number): number;
47
+ export interface SplashStorageOptions {
48
+ /** `undefined` uses the global `caches`; `null` means no cache (every read is a miss). */
49
+ readonly storage?: CacheStorage | null;
50
+ readonly cacheName?: string;
51
+ readonly budgetMs?: number;
52
+ readonly maxEntries?: number;
53
+ }
54
+ export type SplashLoad = {
55
+ readonly source: 'cache';
56
+ readonly blob: Blob;
57
+ } | {
58
+ readonly source: 'miss';
59
+ };
60
+ /**
61
+ * Reads `url` from the Cache API within the read budget. A hit gives the cached blob; anything else (no cache, no
62
+ * entry, a read error or a read that is not done within the budget) gives `miss`, and the caller loads the URL
63
+ * from the network. Keyed by the full URL, so a changed host or prefix never reads an old entry. Never rejects.
64
+ */
65
+ export declare function loadSplashImage(url: string, options?: SplashStorageOptions): Promise<SplashLoad>;
66
+ export interface SplashStoreOptions extends SplashStorageOptions {
67
+ /** Defaults to a CORS `fetch` with no credentials. */
68
+ readonly fetchImage?: (url: string) => Promise<Response>;
69
+ }
70
+ /**
71
+ * Downloads `url` and stores the image under that URL, then trims the cache to `maxEntries`, oldest first. A
72
+ * response that is not OK, or has an empty body, stores nothing. Returns whether an entry was written. Never
73
+ * rejects, so a missing CORS header or an unavailable cache is a `false`, not an error.
74
+ */
75
+ export declare function storeSplashImage(url: string, options?: SplashStoreOptions): Promise<boolean>;
@@ -0,0 +1,186 @@
1
+ /**
2
+ * Public image contract for the img-gen `startup-splash` collection.
3
+ *
4
+ * Browser-safe: no `node:` import and no file system access. The cache storage, fetch and random source are
5
+ * parameters so tests can replace them. The loaders never reject: any failure reads as a miss.
6
+ */
7
+ export const SPLASH_IMAGE_DEFAULTS = Object.freeze({
8
+ baseUrl: 'https://img-gen.hagicode.com',
9
+ prefix: 'startup-splash',
10
+ count: 600,
11
+ cacheName: 'hagilight.rootTransit.splash',
12
+ readBudgetMs: 100,
13
+ maxEntries: 30,
14
+ });
15
+ const KEY_PREFIX = 'hagicode-splash-';
16
+ const KEY_PATTERN = /^hagicode-splash-(\d{3,4})$/u;
17
+ const PREFIX_PATTERN = /^[A-Za-z0-9._-]+(?:\/[A-Za-z0-9._-]+)*$/u;
18
+ const MAX_COUNT = 9999;
19
+ const fail = (reason) => {
20
+ throw new TypeError(`Hagilight RootTransit: ${reason}`);
21
+ };
22
+ const DEFAULT_CONFIG = Object.freeze({
23
+ baseUrl: SPLASH_IMAGE_DEFAULTS.baseUrl,
24
+ prefix: SPLASH_IMAGE_DEFAULTS.prefix,
25
+ count: SPLASH_IMAGE_DEFAULTS.count,
26
+ cacheName: SPLASH_IMAGE_DEFAULTS.cacheName,
27
+ });
28
+ /**
29
+ * Resolves the `splash` option. `false` disables the splash (returns null); `undefined` gives the defaults; an
30
+ * object overrides the listed keys. Throws a `TypeError` for any invalid value, so bad config fails the build.
31
+ */
32
+ export function resolveSplashConfig(input) {
33
+ if (input === false)
34
+ return null;
35
+ if (input === undefined)
36
+ return DEFAULT_CONFIG;
37
+ if (typeof input !== 'object' || input === null)
38
+ fail('splash must be false or an options object.');
39
+ const allowed = new Set(['baseUrl', 'prefix', 'count', 'cacheName']);
40
+ for (const key of Object.keys(input)) {
41
+ if (!allowed.has(key))
42
+ fail(`splash has an unknown option "${key}".`);
43
+ }
44
+ const baseUrl = input.baseUrl ?? DEFAULT_CONFIG.baseUrl;
45
+ let url;
46
+ try {
47
+ url = new URL(baseUrl);
48
+ }
49
+ catch {
50
+ return fail('splash baseUrl must be an absolute URL.');
51
+ }
52
+ if (url.protocol !== 'https:' || url.username || url.password || url.search || url.hash) {
53
+ fail('splash baseUrl must be HTTPS without credentials, query or fragment.');
54
+ }
55
+ const prefix = input.prefix ?? DEFAULT_CONFIG.prefix;
56
+ if (!PREFIX_PATTERN.test(prefix) || prefix.split('/').some((segment) => segment === '.' || segment === '..')) {
57
+ fail('splash prefix must be letters, digits, dots, underscores and hyphens joined by slashes.');
58
+ }
59
+ const count = input.count ?? DEFAULT_CONFIG.count;
60
+ if (!Number.isInteger(count) || count < 1 || count > MAX_COUNT) {
61
+ fail(`splash count must be an integer from 1 to ${MAX_COUNT}.`);
62
+ }
63
+ const cacheName = input.cacheName ?? DEFAULT_CONFIG.cacheName;
64
+ if (typeof cacheName !== 'string' || !cacheName.trim())
65
+ fail('splash cacheName must be a non-empty string.');
66
+ return Object.freeze({
67
+ baseUrl: `${url.origin}${url.pathname.replace(/\/+$/u, '')}`,
68
+ prefix,
69
+ count,
70
+ cacheName,
71
+ });
72
+ }
73
+ /** Maps an index from 1 to `count` to its key, for example 7 to `hagicode-splash-007`. */
74
+ export function splashKey(index, count = SPLASH_IMAGE_DEFAULTS.count) {
75
+ if (!Number.isInteger(index) || index < 1 || index > count) {
76
+ fail(`splash index must be an integer from 1 to ${count}.`);
77
+ }
78
+ return `${KEY_PREFIX}${String(index).padStart(3, '0')}`;
79
+ }
80
+ /**
81
+ * The path below the base URL, `<prefix>/<key>.avif`, for a key or an index. A string must be a key of the
82
+ * collection: `hagicode-splash-` followed by its number, padded to three digits, within the count.
83
+ */
84
+ export function splashImagePath(keyOrIndex, config = DEFAULT_CONFIG) {
85
+ const key = typeof keyOrIndex === 'number' ? splashKey(keyOrIndex, config.count) : canonicalKey(keyOrIndex, config.count);
86
+ return `${config.prefix}/${key}.avif`;
87
+ }
88
+ /** The full image URL: the base URL joined with `splashImagePath`. */
89
+ export function splashImageUrl(keyOrIndex, config = DEFAULT_CONFIG) {
90
+ return `${config.baseUrl}/${splashImagePath(keyOrIndex, config)}`;
91
+ }
92
+ function canonicalKey(key, count) {
93
+ const match = KEY_PATTERN.exec(key);
94
+ if (!match || splashKey(Number(match[1]), count) !== key) {
95
+ fail(`splash key must be ${KEY_PREFIX}NNN within 1 to ${count}.`);
96
+ }
97
+ return key;
98
+ }
99
+ /**
100
+ * A 1-based index from `random`, which returns a value in [0, 1). Out-of-range or non-finite results are clamped,
101
+ * so the result is always within 1 to `count`.
102
+ */
103
+ export function pickSplashIndex(random = Math.random, count = SPLASH_IMAGE_DEFAULTS.count) {
104
+ const value = random();
105
+ const fraction = Number.isFinite(value) ? Math.min(Math.max(value, 0), 1 - Number.EPSILON) : 0;
106
+ return 1 + Math.floor(fraction * count);
107
+ }
108
+ const MISS = Object.freeze({ source: 'miss' });
109
+ function resolveStorage(storage) {
110
+ if (storage !== undefined)
111
+ return storage;
112
+ try {
113
+ return typeof caches === 'undefined' ? null : caches;
114
+ }
115
+ catch {
116
+ return null;
117
+ }
118
+ }
119
+ /**
120
+ * Reads `url` from the Cache API within the read budget. A hit gives the cached blob; anything else (no cache, no
121
+ * entry, a read error or a read that is not done within the budget) gives `miss`, and the caller loads the URL
122
+ * from the network. Keyed by the full URL, so a changed host or prefix never reads an old entry. Never rejects.
123
+ */
124
+ export async function loadSplashImage(url, options = {}) {
125
+ const storage = resolveStorage(options.storage);
126
+ if (!storage)
127
+ return MISS;
128
+ const cacheName = options.cacheName ?? SPLASH_IMAGE_DEFAULTS.cacheName;
129
+ const lookup = (async () => {
130
+ try {
131
+ const cache = await storage.open(cacheName);
132
+ const response = await cache.match(url);
133
+ if (!response?.ok)
134
+ return MISS;
135
+ const blob = await response.blob();
136
+ return blob.size > 0 ? { source: 'cache', blob } : MISS;
137
+ }
138
+ catch {
139
+ return MISS;
140
+ }
141
+ })();
142
+ let timer;
143
+ const budget = new Promise((resolve) => {
144
+ timer = setTimeout(() => resolve(MISS), options.budgetMs ?? SPLASH_IMAGE_DEFAULTS.readBudgetMs);
145
+ });
146
+ try {
147
+ return await Promise.race([lookup, budget]);
148
+ }
149
+ finally {
150
+ clearTimeout(timer);
151
+ }
152
+ }
153
+ /**
154
+ * Downloads `url` and stores the image under that URL, then trims the cache to `maxEntries`, oldest first. A
155
+ * response that is not OK, or has an empty body, stores nothing. Returns whether an entry was written. Never
156
+ * rejects, so a missing CORS header or an unavailable cache is a `false`, not an error.
157
+ */
158
+ export async function storeSplashImage(url, options = {}) {
159
+ const storage = resolveStorage(options.storage);
160
+ if (!storage)
161
+ return false;
162
+ try {
163
+ const fetchImage = options.fetchImage ?? ((target) => fetch(target, { mode: 'cors', credentials: 'omit' }));
164
+ const response = await fetchImage(url);
165
+ if (!response.ok)
166
+ return false;
167
+ const blob = await response.blob();
168
+ if (blob.size === 0)
169
+ return false;
170
+ const cache = await storage.open(options.cacheName ?? SPLASH_IMAGE_DEFAULTS.cacheName);
171
+ // Delete first so a re-stored entry moves to the end of the insertion order that trimming relies on.
172
+ await cache.delete(url);
173
+ await cache.put(url, new Response(blob));
174
+ await trimCache(cache, options.maxEntries ?? SPLASH_IMAGE_DEFAULTS.maxEntries);
175
+ return true;
176
+ }
177
+ catch {
178
+ return false;
179
+ }
180
+ }
181
+ async function trimCache(cache, maxEntries) {
182
+ const keys = await cache.keys();
183
+ for (const oldest of keys.slice(0, Math.max(0, keys.length - maxEntries))) {
184
+ await cache.delete(oldest);
185
+ }
186
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hagicode/hagilight-core",
3
- "version": "0.13.1-dev.142.1.f7670b5",
3
+ "version": "0.14.0",
4
4
  "type": "module",
5
5
  "description": "Shared TypeScript utilities, components, and assets for HagiCode Astro and Starlight sites",
6
6
  "repository": {
@@ -22,6 +22,10 @@
22
22
  "types": "./dist/root-transit.d.ts",
23
23
  "default": "./dist/root-transit.js"
24
24
  },
25
+ "./splash-images": {
26
+ "types": "./dist/splash-images.d.ts",
27
+ "default": "./dist/splash-images.js"
28
+ },
25
29
  "./Footer": "./Footer.astro",
26
30
  "./links": {
27
31
  "types": "./dist/links.d.ts",