favicon-env 0.1.0 → 0.3.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
@@ -2,13 +2,13 @@
2
2
 
3
3
  Tint your favicon per environment so you can tell instances apart at a glance — no more staring at three identical tabs wondering which one is production.
4
4
 
5
- ![favicon-env — the same base icon per environment: prod, dev (hue-shift), staging (dot), a "#344" preview badge, a "#8790" URL-rule badge, and a custom image](docs/hero.png)
5
+ ![favicon-env — the same base icon per environment: prod, dev (hue-shift), dev (exact-colour tint), dev (invert), staging (dot), a "#344" preview cover, and a custom image](docs/hero.png)
6
6
 
7
7
  **[▶ Live, clickable demo](https://amir-abushanab.github.io/favicon-env/)**
8
8
 
9
- - **Runtime mode** — one import, any framework, any deploy. Detects the environment in the browser and re-tints the favicon on a `<canvas>`, so it works with whatever favicon you already have (svg / png / ico).
10
- - **Build-time mode** — a tiny SVG helper that bakes the tint in at build/SSR time, for zero first-paint flash.
11
- - **Zero dependencies.** ~2 kB min+gzip (the build-time SSR helper alone is ~1.5 kB).
9
+ - **Runtime mode** — tint an existing SVG, PNG, or ICO in the browser.
10
+ - **Build-time mode** — bake changes into an SVG during build or SSR.
11
+ - **Zero dependencies.** ~2.3 kB min+gzip and [tree-shakes to zero bytes in prod](#zero-bytes-in-prod).
12
12
 
13
13
  ## Install
14
14
 
@@ -16,42 +16,100 @@ Tint your favicon per environment so you can tell instances apart at a glance
16
16
  pnpm add favicon-env
17
17
  ```
18
18
 
19
- > **Using an AI coding agent?** favicon-env ships an [Agent Skill](https://tanstack.com/intent) (via TanStack Intent) — run `npx @tanstack/intent@latest install` and your agent picks up the correct patterns (framework placement, badges, runtime vs SSR) straight from the package, versioned with it.
19
+ > **Using an AI coding agent?** Install the bundled [Agent Skill](https://tanstack.com/intent) with `pnpm dlx @tanstack/intent@latest install`.
20
20
 
21
21
  ## Runtime mode
22
22
 
23
23
  ```js
24
- import { envFavicon } from 'favicon-env'
24
+ import { envFavicon } from 'favicon-env';
25
25
 
26
26
  envFavicon({
27
27
  environments: {
28
- dev: { hue: 130 }, // hue-rotate degrees
29
- staging: { badge: '#f59e0b' }, // …or a corner dot that keeps the logo intact
30
- // prod omitted → left untouched
28
+ dev: { tint: '#22c55e' },
29
+ staging: { badge: { text: 'S', color: '#f59e0b', shape: 'cover' } },
31
30
  },
32
- })
31
+ });
33
32
  ```
34
33
 
35
- Call it once on the client, as early as you can — it reads the current `<link rel="icon">`, redraws it tinted, and swaps it in. It's a no-op during SSR (it guards on `document`), so it's safe to import anywhere. Where it goes in the common setups:
34
+ ### Zero bytes in prod
35
+
36
+ An unconditional call stays bundled even when `prod` is absent from `environments`. To remove the runtime, put `import('favicon-env')` behind a compile-time environment check. The examples below use this pattern, and the framework matrix scans their emitted prod assets to verify exclusion.
37
+
38
+ Call it on the client after the favicon link exists:
36
39
 
37
40
  <details>
38
41
  <summary><b>Next.js</b> — App Router</summary>
39
42
 
40
43
  ```tsx
41
44
  // app/favicon-env.tsx — a client component
42
- 'use client'
43
- import { useEffect } from 'react'
44
- import { envFavicon } from 'favicon-env'
45
+ 'use client';
46
+ import { useEffect } from 'react';
47
+
48
+ const appEnv = process.env.NEXT_PUBLIC_APP_ENV ?? 'prod';
45
49
 
46
50
  export function FaviconEnv() {
47
51
  useEffect(() => {
48
- void envFavicon({ /* …environments, as above… */ })
49
- }, [])
50
- return null
52
+ if (appEnv !== 'dev' && appEnv !== 'staging') return;
53
+
54
+ let queued = false;
55
+ const apply = async () => {
56
+ queued = false;
57
+ const { envFavicon } = await import('favicon-env');
58
+ await envFavicon({
59
+ environments: {
60
+ dev: { tint: '#22c55e' },
61
+ staging: { badge: { text: 'S', color: '#f59e0b', shape: 'cover' } },
62
+ },
63
+ detect: () => appEnv,
64
+ });
65
+ };
66
+ const schedule = () => {
67
+ if (queued) return;
68
+ queued = true;
69
+ queueMicrotask(apply);
70
+ };
71
+ // Next can restore metadata-managed icons during hydration or navigation.
72
+ const observer = new MutationObserver(() => {
73
+ if (document.head.querySelector('link[rel~="icon"]:not([data-favicon-env])')) {
74
+ schedule();
75
+ }
76
+ });
77
+ observer.observe(document.head, {
78
+ childList: true,
79
+ subtree: true,
80
+ attributes: true,
81
+ attributeFilter: ['href', 'rel'],
82
+ });
83
+ schedule();
84
+ return () => observer.disconnect();
85
+ }, []);
86
+ return null;
87
+ }
88
+ ```
89
+
90
+ ```tsx
91
+ // app/layout.tsx
92
+ import type { Metadata } from 'next';
93
+ import type { ReactNode } from 'react';
94
+ import { FaviconEnv } from './favicon-env';
95
+
96
+ export const metadata: Metadata = {
97
+ icons: { icon: '/favicon.svg' },
98
+ };
99
+
100
+ export default function RootLayout({ children }: { children: ReactNode }) {
101
+ return (
102
+ <html lang="en">
103
+ <body>
104
+ <FaviconEnv />
105
+ {children}
106
+ </body>
107
+ </html>
108
+ );
51
109
  }
52
110
  ```
53
111
 
54
- Then render `<FaviconEnv />` once inside `<body>` in `app/layout.tsx`. `useEffect` is the right hook here — a run-once, client-only side effect, safe under React StrictMode's double-invoke (re-tinting is idempotent). (Next ≥ 15.3: drop the call into `instrumentation-client.ts` and skip the component entirely. Pages Router: put the `useEffect` in `pages/_app.tsx`.)
112
+ The observer handles metadata reconciliation during hydration and navigation. Pages Router: render the component from `pages/_app.tsx`.
55
113
 
56
114
  </details>
57
115
 
@@ -59,13 +117,54 @@ Then render `<FaviconEnv />` once inside `<body>` in `app/layout.tsx`. `useEffec
59
117
  <summary><b>TanStack Router / Start</b></summary>
60
118
 
61
119
  ```tsx
62
- // src/main.tsx — your client entry, before you render the router
63
- import { envFavicon } from 'favicon-env'
120
+ // src/client.tsx
121
+ import { StartClient } from '@tanstack/react-start/client';
122
+ import { StrictMode } from 'react';
123
+ import { hydrateRoot } from 'react-dom/client';
124
+
125
+ const appEnv = import.meta.env.VITE_APP_ENV ?? 'prod';
126
+
127
+ if (appEnv === 'dev' || appEnv === 'staging') {
128
+ let queued = false;
129
+ const apply = async () => {
130
+ queued = false;
131
+ const { envFavicon } = await import('favicon-env');
132
+ await envFavicon({
133
+ environments: {
134
+ dev: { tint: '#22c55e' },
135
+ staging: { badge: { text: 'S', color: '#f59e0b', shape: 'cover' } },
136
+ },
137
+ detect: () => appEnv,
138
+ });
139
+ };
140
+ const schedule = () => {
141
+ if (queued) return;
142
+ queued = true;
143
+ queueMicrotask(apply);
144
+ };
145
+ const observer = new MutationObserver(() => {
146
+ if (document.head.querySelector('link[rel~="icon"]:not([data-favicon-env])')) {
147
+ schedule();
148
+ }
149
+ });
150
+ observer.observe(document.head, {
151
+ childList: true,
152
+ subtree: true,
153
+ attributes: true,
154
+ attributeFilter: ['href', 'rel'],
155
+ });
156
+ schedule();
157
+ }
64
158
 
65
- void envFavicon({ /* …environments, as above… */ })
159
+ hydrateRoot(
160
+ document,
161
+ <StrictMode>
162
+ <StartClient />
163
+ </StrictMode>,
164
+ );
66
165
  ```
67
166
 
68
- The entry runs on the client, so no `useEffect` is needed. (TanStack Start / SSR: the same call in your client entry is a no-op on the server, thanks to the `document` guard.)
167
+ Create the optional `src/client.tsx` entry. For a TanStack Router SPA, use the same observer in `src/main.tsx` before rendering the app.
69
168
 
70
169
  </details>
71
170
 
@@ -74,29 +173,373 @@ The entry runs on the client, so no `useEffect` is needed. (TanStack Start / SSR
74
173
 
75
174
  ```astro
76
175
  ---
77
- // src/layouts/Layout.astro — a client <script>, bundled and run in the browser
176
+ // src/layouts/Layout.astro
78
177
  ---
79
- <script>
80
- import { envFavicon } from 'favicon-env'
81
- void envFavicon({ /* …environments, as above… */ })
178
+ <html lang="en">
179
+ <head>
180
+ <link rel="icon" type="image/svg+xml" href="/favicon.svg" />
181
+ </head>
182
+ <body>
183
+ <slot />
184
+ <script>
185
+ const appEnv = import.meta.env.PUBLIC_APP_ENV ?? 'prod';
186
+ if (appEnv === 'dev' || appEnv === 'staging') {
187
+ void import('favicon-env').then(({ envFavicon }) =>
188
+ envFavicon({
189
+ environments: {
190
+ dev: { tint: '#22c55e' },
191
+ staging: { badge: { text: 'S', color: '#f59e0b', shape: 'cover' } },
192
+ },
193
+ detect: () => appEnv,
194
+ }),
195
+ );
196
+ }
197
+ </script>
198
+ </body>
199
+ </html>
200
+ ```
201
+
202
+ For an SVG with no first-paint flash, use the build-time helper below.
203
+
204
+ </details>
205
+
206
+ <details>
207
+ <summary><b>SvelteKit</b></summary>
208
+
209
+ ```svelte
210
+ <!-- src/routes/+layout.svelte -->
211
+ <script lang="ts">
212
+ import { onMount } from 'svelte';
213
+
214
+ let { children } = $props();
215
+
216
+ onMount(() => {
217
+ const appEnv = __FAVICON_ENV_APP_ENV__;
218
+ if (appEnv !== 'dev' && appEnv !== 'staging') return;
219
+
220
+ let queued = false;
221
+ const apply = async () => {
222
+ queued = false;
223
+ const { envFavicon } = await import('favicon-env');
224
+ await envFavicon({
225
+ environments: {
226
+ dev: { tint: '#22c55e' },
227
+ staging: { badge: { text: 'S', color: '#f59e0b', shape: 'cover' } },
228
+ },
229
+ detect: () => appEnv,
230
+ });
231
+ };
232
+ const schedule = () => {
233
+ if (queued) return;
234
+ queued = true;
235
+ queueMicrotask(apply);
236
+ };
237
+ const observer = new MutationObserver(() => {
238
+ if (document.head.querySelector('link[rel~="icon"]:not([data-favicon-env])')) {
239
+ schedule();
240
+ }
241
+ });
242
+
243
+ observer.observe(document.head, {
244
+ childList: true,
245
+ subtree: true,
246
+ attributes: true,
247
+ attributeFilter: ['href', 'rel'],
248
+ });
249
+ schedule();
250
+
251
+ return () => observer.disconnect();
252
+ });
82
253
  </script>
254
+
255
+ <svelte:head>
256
+ <link rel="icon" type="image/svg+xml" href="/favicon.svg" />
257
+ </svelte:head>
258
+
259
+ {@render children()}
83
260
  ```
84
261
 
85
- For Astro you can also bake the tint straight into the HTML for **zero first-paint flash** — see the *Build-time / SSR mode* section below, which is the recommended path when you control the favicon SVG.
262
+ ```ts
263
+ // vite.config.ts
264
+ import { sveltekit } from '@sveltejs/kit/vite';
265
+ import { defineConfig } from 'vite';
266
+
267
+ export default defineConfig({
268
+ define: {
269
+ __FAVICON_ENV_APP_ENV__: JSON.stringify(process.env.PUBLIC_APP_ENV ?? 'prod'),
270
+ },
271
+ plugins: [sveltekit()],
272
+ });
273
+ ```
274
+
275
+ ```ts
276
+ // src/app.d.ts
277
+ declare const __FAVICON_ENV_APP_ENV__: string;
278
+ ```
279
+
280
+ The explicit build constant lets Vite remove the import from prod output.
86
281
 
87
282
  </details>
88
283
 
89
284
  <details>
90
- <summary><b>Vite SPA · Vue · Svelte · vanilla</b></summary>
285
+ <summary><b>SolidStart</b></summary>
91
286
 
92
- ```js
93
- // your client entry — src/main.ts, main.js, …
94
- import { envFavicon } from 'favicon-env'
287
+ ```tsx
288
+ // src/app.tsx
289
+ import { Link, MetaProvider } from '@solidjs/meta';
290
+ import { Router } from '@solidjs/router';
291
+ import { FileRoutes } from '@solidjs/start/router';
292
+ import { onCleanup, onMount, Suspense } from 'solid-js';
293
+
294
+ export default function App() {
295
+ onMount(() => {
296
+ const appEnv = import.meta.env.VITE_APP_ENV ?? 'prod';
297
+ if (appEnv !== 'dev' && appEnv !== 'staging') return;
298
+
299
+ let queued = false;
300
+ const apply = async () => {
301
+ queued = false;
302
+ const { envFavicon } = await import('favicon-env');
303
+ await envFavicon({
304
+ environments: {
305
+ dev: { tint: '#22c55e' },
306
+ staging: { badge: { text: 'S', color: '#f59e0b', shape: 'cover' } },
307
+ },
308
+ detect: () => appEnv,
309
+ });
310
+ };
311
+ const schedule = () => {
312
+ if (queued) return;
313
+ queued = true;
314
+ queueMicrotask(apply);
315
+ };
316
+ const observer = new MutationObserver(() => {
317
+ if (document.head.querySelector('link[rel~="icon"]:not([data-favicon-env])')) {
318
+ schedule();
319
+ }
320
+ });
321
+
322
+ observer.observe(document.head, {
323
+ childList: true,
324
+ subtree: true,
325
+ attributes: true,
326
+ attributeFilter: ['href', 'rel'],
327
+ });
328
+ schedule();
329
+ onCleanup(() => observer.disconnect());
330
+ });
331
+
332
+ return (
333
+ <Router
334
+ root={(props) => (
335
+ <MetaProvider>
336
+ <Link rel="icon" type="image/svg+xml" href="/favicon.svg" />
337
+ <Suspense>{props.children}</Suspense>
338
+ </MetaProvider>
339
+ )}
340
+ >
341
+ <FileRoutes />
342
+ </Router>
343
+ );
344
+ }
345
+ ```
346
+
347
+ Keep the hook in the app root so it survives route changes.
348
+
349
+ </details>
350
+
351
+ <details>
352
+ <summary><b>Angular SSR</b> — standalone application</summary>
353
+
354
+ ```ts
355
+ // src/app/app.ts
356
+ import { Component, DestroyRef, afterNextRender, inject } from '@angular/core';
357
+ import { loadEnvFavicon } from './favicon-env-loader';
358
+
359
+ declare const APP_ENV: string;
360
+
361
+ @Component({ selector: 'app-root', template: '<main>App</main>', imports: [] })
362
+ export class App {
363
+ private readonly destroyRef = inject(DestroyRef);
364
+
365
+ constructor() {
366
+ afterNextRender(() => {
367
+ if (APP_ENV !== 'dev' && APP_ENV !== 'staging') return;
368
+
369
+ let queued = false;
370
+ const apply = async () => {
371
+ queued = false;
372
+ const envFavicon = await loadEnvFavicon();
373
+ if (!envFavicon) return;
374
+ await envFavicon({
375
+ environments: {
376
+ dev: { tint: '#22c55e' },
377
+ staging: { badge: { text: 'S', color: '#f59e0b', shape: 'cover' } },
378
+ },
379
+ detect: () => APP_ENV,
380
+ });
381
+ };
382
+ const schedule = () => {
383
+ if (queued) return;
384
+ queued = true;
385
+ queueMicrotask(apply);
386
+ };
387
+ const observer = new MutationObserver(() => {
388
+ if (document.head.querySelector('link[rel~="icon"]:not([data-favicon-env])')) {
389
+ schedule();
390
+ }
391
+ });
392
+
393
+ observer.observe(document.head, {
394
+ childList: true,
395
+ subtree: true,
396
+ attributes: true,
397
+ attributeFilter: ['href', 'rel'],
398
+ });
399
+ schedule();
400
+ this.destroyRef.onDestroy(() => observer.disconnect());
401
+ });
402
+ }
403
+ }
404
+ ```
405
+
406
+ ```ts
407
+ // src/app/favicon-env-loader.ts
408
+ export async function loadEnvFavicon() {
409
+ return (await import('favicon-env')).envFavicon;
410
+ }
411
+ ```
412
+
413
+ ```ts
414
+ // src/app/favicon-env-loader.prod.ts
415
+ import type { EnvFaviconOptions } from 'favicon-env';
416
+
417
+ type EnvFavicon = (options?: EnvFaviconOptions) => Promise<void>;
418
+
419
+ export async function loadEnvFavicon(): Promise<EnvFavicon | null> {
420
+ return null;
421
+ }
422
+ ```
423
+
424
+ In the production build configuration in `angular.json`:
425
+
426
+ ```json
427
+ {
428
+ "define": { "APP_ENV": "'prod'" },
429
+ "fileReplacements": [
430
+ {
431
+ "replace": "src/app/favicon-env-loader.ts",
432
+ "with": "src/app/favicon-env-loader.prod.ts"
433
+ }
434
+ ]
435
+ }
436
+ ```
437
+
438
+ Use the real loader for dev/staging. Angular's file replacement prevents it from emitting an unused lazy chunk in prod.
439
+
440
+ </details>
441
+
442
+ <details>
443
+ <summary><b>Nuxt</b></summary>
444
+
445
+ ```ts
446
+ // app/plugins/favicon-env.client.ts
447
+ export default defineNuxtPlugin(() => {
448
+ const appEnv = __FAVICON_ENV_APP_ENV__;
449
+ if (appEnv !== 'dev' && appEnv !== 'staging') return;
450
+
451
+ let queued = false;
452
+ const apply = async () => {
453
+ queued = false;
454
+ const { envFavicon } = await import('favicon-env');
455
+ await envFavicon({
456
+ environments: {
457
+ dev: { tint: '#22c55e' },
458
+ staging: { badge: { text: 'S', color: '#f59e0b', shape: 'cover' } },
459
+ },
460
+ detect: () => appEnv,
461
+ });
462
+ };
463
+ const schedule = () => {
464
+ if (queued) return;
465
+ queued = true;
466
+ queueMicrotask(apply);
467
+ };
468
+ const observer = new MutationObserver(() => {
469
+ if (document.head.querySelector('link[rel~="icon"]:not([data-favicon-env])')) {
470
+ schedule();
471
+ }
472
+ });
473
+
474
+ observer.observe(document.head, {
475
+ childList: true,
476
+ subtree: true,
477
+ attributes: true,
478
+ attributeFilter: ['href', 'rel'],
479
+ });
480
+ schedule();
481
+ });
482
+ ```
483
+
484
+ ```ts
485
+ // nuxt.config.ts
486
+ export default defineNuxtConfig({
487
+ vite: {
488
+ define: {
489
+ __FAVICON_ENV_APP_ENV__: JSON.stringify(process.env.NUXT_PUBLIC_APP_ENV ?? 'prod'),
490
+ },
491
+ },
492
+ app: {
493
+ head: {
494
+ link: [{ rel: 'icon', type: 'image/svg+xml', href: '/favicon.svg' }],
495
+ },
496
+ },
497
+ });
498
+ ```
95
499
 
96
- void envFavicon({ /* …environments, as above… */ })
500
+ ```ts
501
+ // app/types.d.ts
502
+ declare const __FAVICON_ENV_APP_ENV__: string;
97
503
  ```
98
504
 
99
- The entry module already runs in the browser, so no framework hook is needed. (In Vue you could equally call it from `onMounted` in your root component.)
505
+ The explicit build constant lets Vite remove the import from prod output.
506
+
507
+ </details>
508
+
509
+ <details>
510
+ <summary><b>Plain HTML</b> — ESM and global builds</summary>
511
+
512
+ ```html
513
+ <!-- Native ESM through an ESM-aware CDN -->
514
+ <link rel="icon" href="/favicon.svg" />
515
+ <script type="module">
516
+ import { envFavicon } from 'https://esm.sh/favicon-env';
517
+
518
+ void envFavicon({
519
+ environments: {
520
+ dev: { tint: '#22c55e' },
521
+ staging: { badge: { text: 'S', color: '#f59e0b', shape: 'cover' } },
522
+ },
523
+ });
524
+ </script>
525
+ ```
526
+
527
+ ```html
528
+ <!-- Classic global build -->
529
+ <link rel="icon" href="/favicon.svg" />
530
+ <script src="https://unpkg.com/favicon-env/dist/favicon-env.global.js"></script>
531
+ <script>
532
+ void faviconEnv.envFavicon({
533
+ environments: {
534
+ dev: { tint: '#22c55e' },
535
+ staging: { badge: { text: 'S', color: '#f59e0b', shape: 'cover' } },
536
+ },
537
+ });
538
+ </script>
539
+ ```
540
+
541
+ The global script can also auto-run with `data-auto` or `data-dev`/`data-staging` attributes.
542
+ For a zero-byte prod page, have the HTML build/template omit these scripts when the app environment is `prod`.
100
543
 
101
544
  </details>
102
545
 
@@ -104,52 +547,84 @@ By default the environment is guessed from the hostname (`localhost` / `*.local`
104
547
 
105
548
  ```js
106
549
  envFavicon({
107
- environments: { /* … */ },
550
+ environments: {
551
+ dev: { tint: '#22c55e' },
552
+ staging: { badge: { text: 'S', color: '#f59e0b', shape: 'cover' } },
553
+ },
108
554
  detect: () => (location.port === '4000' ? 'staging' : 'prod'),
109
- })
555
+ });
110
556
  ```
111
557
 
112
- Environment **names are arbitrary** they're just keys into `environments`, so you aren't limited to `dev`/`staging`/`prod`. Define your own and return them from `detect` (the built-in heuristic only emits the three defaults, so custom names need a custom `detect`):
558
+ Environment names are arbitrary. Custom names require a custom `detect`:
113
559
 
114
560
  ```js
115
561
  envFavicon({
116
562
  environments: {
117
563
  canary: { hue: 280 },
118
- demo: { badge: '#22c55e' },
564
+ demo: { badge: '#22c55e' },
119
565
  },
120
566
  detect: () => {
121
- if (location.hostname.startsWith('canary.')) return 'canary'
122
- if (location.hostname.endsWith('.demo.acme.com')) return 'demo'
123
- return 'prod' // not in the map → favicon left untouched
567
+ if (location.hostname.startsWith('canary.')) return 'canary';
568
+ if (location.hostname.endsWith('.demo.acme.com')) return 'demo';
569
+ return 'prod'; // not in the map → favicon left untouched
124
570
  },
125
- })
571
+ });
126
572
  ```
127
573
 
128
- `detect` can key off anything, not just the hostname — e.g. `detect: () => import.meta.env.MODE`.
574
+ `detect` can use any runtime value, such as `import.meta.env.MODE`.
575
+
576
+ ### Exact colours
577
+
578
+ Use `hue` for a relative colour shift or `tint` for a specific duotone colour:
579
+
580
+ ```js
581
+ envFavicon({
582
+ environments: {
583
+ dev: { tint: '#22c55e' },
584
+ staging: { tint: '#f59e0b' },
585
+ },
586
+ });
587
+ ```
588
+
589
+ Colour fields accept CSS colours, including `oklch()`, `lab()`, and `color(display-p3 …)` where supported.
590
+
591
+ ### Invert
592
+
593
+ Pass `true` for a full invert or `0`–`1` for a partial invert:
594
+
595
+ ```js
596
+ envFavicon({
597
+ environments: {
598
+ dev: { invert: true },
599
+ staging: { invert: 0.9 },
600
+ },
601
+ });
602
+ ```
603
+
604
+ `invert` composes with `hue`; `tint` takes precedence, and `filter` overrides both.
129
605
 
130
606
  ### Auto mode
131
607
 
132
- Don't want to name environments at all? Derive a **stable, unique hue from `location.host`**, so every origin *and port* automatically gets its own colour — perfect for telling several dev servers apart:
608
+ Derive a stable hue from `location.host`:
133
609
 
134
610
  ```js
135
- envFavicon({ auto: true })
611
+ envFavicon({ auto: true });
136
612
  ```
137
613
 
138
614
  ### Badges, PR numbers & URL rules
139
615
 
140
- A `badge` is either a colour (a dot) or an object with `text` — handy for preview deploys, where you want the **PR number** on the icon. The cleanest way is a `rules` list: match the URL with a `RegExp` and drop its captures straight into the text with `$1` / `$<name>`:
616
+ A `badge` can be a colour dot or an object with text. Rules can interpolate regex captures with `$1` or `$<name>`:
141
617
 
142
618
  ```js
143
619
  envFavicon({
144
620
  rules: [
145
- // e.g. a preview deploy at pr-344.myapp.dev → a "#344" pill
146
621
  { match: /^pr-(\d+)\./, badge: { text: '#$1', color: '#8b5cf6' } },
147
622
  { match: /staging\./, hue: 45 },
148
623
  ],
149
- })
624
+ });
150
625
  ```
151
626
 
152
- `match` is tested against `location.host` (so `:port` is included). Rules are tried in order — first match wins — then fall through to `auto` / `environments` if none match. Need more than the host? Use a function: it receives the full `URL`, and `text` can be a function too:
627
+ Regex rules test `location.host`, including the port. First match wins. Functions receive the full `URL`:
153
628
 
154
629
  ```js
155
630
  rules: [
@@ -157,12 +632,10 @@ rules: [
157
632
  match: (url) => url.searchParams.has('pr'),
158
633
  badge: { text: (match, url) => `#${url.searchParams.get('pr')}` },
159
634
  },
160
- ]
635
+ ];
161
636
  ```
162
637
 
163
- `textColor` defaults to auto (black/white by contrast with `color`).
164
-
165
- Multi-digit numbers get cramped in a corner at 16px. `shape: 'cover'` replaces the icon with a full-bleed number so it reads even in the tab (or keep the icon and just enlarge the pill with `size` + `corner: 'center'`):
638
+ Use `shape: 'cover'` to make multi-digit text readable at favicon size:
166
639
 
167
640
  ```js
168
641
  { badge: { text: '#344', color: '#8b5cf6', shape: 'cover' } }
@@ -170,7 +643,7 @@ Multi-digit numbers get cramped in a corner at 16px. `shape: 'cover'` replaces t
170
643
 
171
644
  ### A different image per environment
172
645
 
173
- Set `src` to swap the base image outright for an environment — e.g. a distinct staging logo. Any `hue` / `filter` / `badge` still composites on top:
646
+ Use `src` to replace the base image. Other effects still apply:
174
647
 
175
648
  ```js
176
649
  envFavicon({
@@ -178,30 +651,12 @@ envFavicon({
178
651
  staging: { src: '/favicon.staging.svg' },
179
652
  preview: { src: '/favicon.svg', badge: { text: '#344' } },
180
653
  },
181
- })
182
- ```
183
-
184
- A plain `src` with no recolour/badge is applied directly (no canvas), so cross-origin images and crisp vectors just work.
185
-
186
- ### No build step
187
-
188
- Drop in a `<script>` tag; it auto-runs from `data-*` attributes and also exposes `window.faviconEnv`:
189
-
190
- ```html
191
- <!-- unique colour per host, zero config -->
192
- <script src="https://unpkg.com/favicon-env/dist/favicon-env.global.js" data-auto></script>
193
-
194
- <!-- or name your environments (hue in degrees) -->
195
- <script
196
- src="https://unpkg.com/favicon-env/dist/favicon-env.global.js"
197
- data-dev="130"
198
- data-staging="45"
199
- ></script>
654
+ });
200
655
  ```
201
656
 
202
657
  ## Build-time / SSR mode
203
658
 
204
- If you control the favicon SVG and want **no flash**, bake the tint in at build time instead. `faviconDataUri` returns a ready `href`:
659
+ Use `faviconDataUri` to bake changes into an SVG:
205
660
 
206
661
  ```astro
207
662
  ---
@@ -215,78 +670,77 @@ const tint = { dev: { hue: 130 }, staging: { hue: 45 }, prod: false }[env]
215
670
  <link rel="icon" type="image/svg+xml" href={faviconDataUri(favicon, tint)} />
216
671
  ```
217
672
 
218
- `favicon-env/ssr` is pure string manipulation with no DOM dependency, so it's safe to run in Node during a build. Badges work here too — they're baked into the SVG (positioned via its `viewBox`), so you can stamp a PR number at build time with no flash:
673
+ The SSR entry has no DOM dependency and supports badges:
219
674
 
220
675
  ```js
221
- const pr = process.env.VERCEL_GIT_PULL_REQUEST_ID
222
- faviconDataUri(favicon, pr ? { badge: { text: `#${pr}` } } : { hue: 45 })
676
+ const pr = process.env.VERCEL_GIT_PULL_REQUEST_ID;
677
+ faviconDataUri(favicon, pr ? { badge: { text: `#${pr}` } } : { hue: 45 });
223
678
  ```
224
679
 
225
680
  ### Vite
226
681
 
227
- A plain Vite SPA has no template to bake the tint into — its `index.html` is static. Drop this small plugin into your `vite.config` to rewrite the `<link rel="icon">` at build time, choosing the tint from Vite's `mode`:
682
+ This Vite plugin rewrites an SVG favicon using the current mode:
228
683
 
229
684
  ```js
230
685
  // vite.config.js
231
- import { readFileSync } from 'node:fs'
232
- import path from 'node:path'
233
- import { defineConfig } from 'vite'
234
- import { faviconDataUri } from 'favicon-env/ssr'
686
+ import { readFileSync } from 'node:fs';
687
+ import path from 'node:path';
688
+ import { defineConfig } from 'vite';
689
+ import { faviconDataUri } from 'favicon-env/ssr';
235
690
 
236
- // keyed by Vite `mode` (e.g. `vite build --mode staging`); omit prod to leave it untouched
237
691
  const tints = {
238
692
  development: { hue: 130 },
239
693
  staging: { hue: 45 },
240
- }
694
+ };
241
695
 
242
696
  function faviconEnv() {
243
- let config
697
+ let config;
244
698
  return {
245
699
  name: 'favicon-env',
246
700
  configResolved(resolved) {
247
- config = resolved
701
+ config = resolved;
248
702
  },
249
703
  transformIndexHtml(html) {
250
- const tint = tints[config.mode]
251
- if (!tint) return // no rule for this mode → leave the icon alone
704
+ const tint = tints[config.mode];
705
+ if (!tint) return;
252
706
  return html.replace(/<link\b[^>]*\brel=["']icon["'][^>]*>/i, (tag) => {
253
- const href = tag.match(/\bhref=["']([^"']+)["']/i)?.[1]
254
- if (!href?.endsWith('.svg')) return tag // SVG only; skip png/ico
255
- let svg
707
+ const href = tag.match(/\bhref=["']([^"']+)["']/i)?.[1];
708
+ if (!href?.endsWith('.svg')) return tag;
709
+ let svg;
256
710
  try {
257
- svg = readFileSync(path.join(config.publicDir, href.replace(/^\//, '')), 'utf8')
711
+ svg = readFileSync(path.join(config.publicDir, href.replace(/^\//, '')), 'utf8');
258
712
  } catch {
259
- return tag // not in public/ (missing / bundled asset) → untouched
713
+ return tag;
260
714
  }
261
- return tag.replace(/\bhref=["'][^"']*["']/i, `href="${faviconDataUri(svg, tint)}"`)
262
- })
715
+ return tag.replace(/\bhref=["'][^"']*["']/i, `href="${faviconDataUri(svg, tint)}"`);
716
+ });
263
717
  },
264
- }
718
+ };
265
719
  }
266
720
 
267
721
  export default defineConfig({
268
722
  plugins: [faviconEnv()],
269
- })
723
+ });
270
724
  ```
271
725
 
272
- Now `vite dev` and `vite build` serve the tint baked into the initial HTML — no first-paint flash — reading your favicon from `public/` and falling through untouched for non-SVG icons or a missing file. Prefer env vars to `--mode`? Swap `tints[config.mode]` for a lookup keyed off `loadEnv(config.mode, config.root, 'PUBLIC_').PUBLIC_APP_ENV`.
726
+ The favicon must be an SVG in `public/`. Omit a mode to leave it unchanged.
273
727
 
274
728
  ## API
275
729
 
276
730
  ### `envFavicon(options?): Promise<void>` — runtime
277
731
 
278
- | option | type | default | description |
279
- | -------------- | ------------------------------------- | -------------------- | ------------------------------------------------------------------ |
280
- | `environments` | `Record<string, EnvTint \| false>` | — | Map of env name (any string) → tint. Missing/`false` = untouched. |
281
- | `rules` | `EnvRule[]` | — | URL-matched tints, checked first; regex captures fill `badge.text`.|
282
- | `detect` | `() => string \| undefined` | hostname heuristic | Return the current env name (a key of `environments`). |
283
- | `auto` | `boolean \| { offset?: number }` | `false` | Ignore `environments`; derive a unique hue from `location.host`. |
284
- | `source` | `string` | current icon / `.ico`| Favicon URL to tint. |
285
- | `size` | `number` | `64` | Canvas raster size in px. |
732
+ | option | type | default | description |
733
+ | -------------- | ---------------------------------- | --------------------- | ------------------------------------------------------------------- |
734
+ | `environments` | `Record<string, EnvTint \| false>` | — | Map of env name (any string) → tint. Missing/`false` = untouched. |
735
+ | `rules` | `EnvRule[]` | — | URL-matched tints, checked first; regex captures fill `badge.text`. |
736
+ | `detect` | `() => string \| undefined` | hostname heuristic | Return the current env name (a key of `environments`). |
737
+ | `auto` | `boolean \| { offset?: number }` | `false` | Ignore `environments`; derive a unique hue from `location.host`. |
738
+ | `source` | `string` | current icon / `.ico` | Favicon URL to tint. |
739
+ | `size` | `number` | `64` | Canvas raster size in px. |
286
740
 
287
- `EnvTint`: `{ hue?: number; filter?: string; src?: string; badge?: string | Badge }`. `filter` (any CSS filter) beats `hue`; `src` replaces the base image for that env; `badge` is a colour string (a dot) or a `Badge`.
741
+ `EnvTint`: `{ hue?: number; invert?: boolean | number; tint?: string; filter?: string; src?: string; badge?: string | Badge }`. Precedence is `filter` `tint` `hue`/`invert`; `src` replaces the base image.
288
742
 
289
- `Badge`: `{ text?: string | number; color?: string; textColor?: string; shape?: 'pill' | 'cover'; corner?: 'top-left' | 'top-right' | 'bottom-left' | 'bottom-right' | 'center'; size?: number; opacity?: number }`. Omit `text` for a dot; include it for a pill. `color` sets the background and `textColor` the text (default: auto black/white by contrast). Two styles: the default `'pill'` sits on top of your icon (placed by `corner`/`size`); `'cover'` replaces the whole icon with the colour + number, best for a multi-digit number that must read at 16px. `opacity` (0–1) fades the badge — with `'cover'`, below `1` it lets your icon show *through* the number (a watermark). Everything composites in one pass, so you can combine `src` + `hue`/`filter` + `badge`.
743
+ `Badge`: `{ text?: string | number; color?: string; textColor?: string; shape?: 'pill' | 'cover'; corner?: 'top-left' | 'top-right' | 'bottom-left' | 'bottom-right' | 'center'; size?: number; opacity?: number }`. Without text it renders a dot. `textColor` defaults to automatic black/white contrast.
290
744
 
291
745
  `EnvRule`: an `EnvTint` plus `match: RegExp | ((url: URL) => boolean)`. A `RegExp` is tested against `location.host` and its captures interpolate into `badge.text` (`$1`, `$<name>`); a function receives the `URL`, and in a rule `badge.text` may also be `(match, url) => string | number`.
292
746
 
@@ -302,12 +756,11 @@ Now `vite dev` and `vite build` serve the tint baked into the initial HTML — n
302
756
  - `defaultDetect(hostname?) => string` — the built-in `dev`/`staging`/`prod` heuristic.
303
757
  - `matchRules(rules, url) => EnvTint | null` — the pure rule matcher (first match wins, captures interpolated). Reuse it server-side with a request `URL` and feed the result to `favicon-env/ssr`'s `faviconDataUri`.
304
758
 
305
- ## How it works & caveats
759
+ ## Caveats
306
760
 
307
- - **Achromatic pixels barely move.** `hue-rotate` leaves white/black/grey roughly alone, so highlights and outlines survive; only the coloured parts shift.
308
- - **Runtime + cross-origin favicons.** Tinting draws to a canvas, so a cross-origin favicon served without CORS headers taints it — `envFavicon` catches that and leaves the icon untouched. Same-origin (the normal case) is fine.
309
- - **First-paint flash.** Runtime mode briefly shows the untinted icon before JS runs. Use the SSR helper if that matters.
310
- - **Browser support.** Runtime mode needs canvas `ctx.filter` (Baseline; unsupported browsers just get the untinted icon). SSR mode relies on SVG favicons honouring an embedded CSS `filter`, which all current evergreen browsers do.
761
+ - Cross-origin favicons need CORS permission for runtime canvas processing; failures leave the icon unchanged.
762
+ - Runtime mode may briefly show the original icon. Use the SSR helper to avoid this.
763
+ - Runtime mode requires canvas `ctx.filter`; unsupported browsers keep the original icon.
311
764
 
312
765
  ## License
313
766