@unocss/preset-web-fonts 0.61.2 → 0.61.4

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/index.d.mts CHANGED
@@ -1,76 +1,6 @@
1
1
  import * as _unocss_core from '@unocss/core';
2
-
3
- type WebFontsProviders = 'google' | 'bunny' | 'fontshare' | 'none' | Provider;
4
- interface WebFontMeta {
5
- name: string;
6
- weights?: (string | number)[];
7
- italic?: boolean;
8
- /**
9
- * Override the provider
10
- * @default <matches root config>
11
- */
12
- provider?: WebFontsProviders;
13
- }
14
- interface ResolvedWebFontMeta extends Omit<WebFontMeta, 'provider'> {
15
- provider: Provider;
16
- }
17
- interface WebFontsOptions {
18
- /**
19
- * Provider service of the web fonts
20
- * @default 'google'
21
- */
22
- provider?: WebFontsProviders;
23
- /**
24
- * The fonts
25
- */
26
- fonts?: Record<string, WebFontMeta | string | (WebFontMeta | string)[]>;
27
- /**
28
- * Extend fonts to the theme object
29
- * @default true
30
- */
31
- extendTheme?: boolean;
32
- /**
33
- * Key for the theme object
34
- *
35
- * @default 'fontFamily'
36
- */
37
- themeKey?: string;
38
- /**
39
- * Inline CSS @import()
40
- *
41
- * @default true
42
- */
43
- inlineImports?: boolean;
44
- /**
45
- * Custom fetch function
46
- *
47
- * @default undefined
48
- */
49
- customFetch?: (url: string) => Promise<any>;
50
- /**
51
- * Timeouts for fetching web fonts
52
- */
53
- timeouts?: false | {
54
- /**
55
- * Timeout for printing warning message
56
- *
57
- * @default 500
58
- */
59
- warning?: number;
60
- /**
61
- * Timeout for failing the fetch
62
- *
63
- * @default 2000
64
- */
65
- failure?: number;
66
- };
67
- }
68
- interface Provider {
69
- name: WebFontsProviders;
70
- getPreflight?: (fonts: WebFontMeta[]) => string;
71
- getImportUrl?: (fonts: WebFontMeta[]) => string | undefined;
72
- getFontName?: (font: WebFontMeta) => string;
73
- }
2
+ import { W as WebFontMeta, a as WebFontsProviders, R as ResolvedWebFontMeta, P as Provider, b as WebFontsOptions } from './shared/preset-web-fonts.DSrOMtoz.mjs';
3
+ export { c as WebFontProcessor } from './shared/preset-web-fonts.DSrOMtoz.mjs';
74
4
 
75
5
  declare function normalizedFontMeta(meta: WebFontMeta | string, defaultProvider: WebFontsProviders): ResolvedWebFontMeta;
76
6
 
@@ -83,4 +13,4 @@ declare function createGoogleCompatibleProvider(name: WebFontsProviders, host: s
83
13
  */
84
14
  declare const presetWebFonts: _unocss_core.PresetFactory<any, WebFontsOptions>;
85
15
 
86
- export { type Provider, type ResolvedWebFontMeta, type WebFontMeta, type WebFontsOptions, type WebFontsProviders, createGoogleCompatibleProvider as createGoogleProvider, presetWebFonts as default, normalizedFontMeta };
16
+ export { Provider, ResolvedWebFontMeta, WebFontMeta, WebFontsOptions, WebFontsProviders, createGoogleCompatibleProvider as createGoogleProvider, presetWebFonts as default, normalizedFontMeta };
package/dist/index.d.ts CHANGED
@@ -1,76 +1,6 @@
1
1
  import * as _unocss_core from '@unocss/core';
2
-
3
- type WebFontsProviders = 'google' | 'bunny' | 'fontshare' | 'none' | Provider;
4
- interface WebFontMeta {
5
- name: string;
6
- weights?: (string | number)[];
7
- italic?: boolean;
8
- /**
9
- * Override the provider
10
- * @default <matches root config>
11
- */
12
- provider?: WebFontsProviders;
13
- }
14
- interface ResolvedWebFontMeta extends Omit<WebFontMeta, 'provider'> {
15
- provider: Provider;
16
- }
17
- interface WebFontsOptions {
18
- /**
19
- * Provider service of the web fonts
20
- * @default 'google'
21
- */
22
- provider?: WebFontsProviders;
23
- /**
24
- * The fonts
25
- */
26
- fonts?: Record<string, WebFontMeta | string | (WebFontMeta | string)[]>;
27
- /**
28
- * Extend fonts to the theme object
29
- * @default true
30
- */
31
- extendTheme?: boolean;
32
- /**
33
- * Key for the theme object
34
- *
35
- * @default 'fontFamily'
36
- */
37
- themeKey?: string;
38
- /**
39
- * Inline CSS @import()
40
- *
41
- * @default true
42
- */
43
- inlineImports?: boolean;
44
- /**
45
- * Custom fetch function
46
- *
47
- * @default undefined
48
- */
49
- customFetch?: (url: string) => Promise<any>;
50
- /**
51
- * Timeouts for fetching web fonts
52
- */
53
- timeouts?: false | {
54
- /**
55
- * Timeout for printing warning message
56
- *
57
- * @default 500
58
- */
59
- warning?: number;
60
- /**
61
- * Timeout for failing the fetch
62
- *
63
- * @default 2000
64
- */
65
- failure?: number;
66
- };
67
- }
68
- interface Provider {
69
- name: WebFontsProviders;
70
- getPreflight?: (fonts: WebFontMeta[]) => string;
71
- getImportUrl?: (fonts: WebFontMeta[]) => string | undefined;
72
- getFontName?: (font: WebFontMeta) => string;
73
- }
2
+ import { W as WebFontMeta, a as WebFontsProviders, R as ResolvedWebFontMeta, P as Provider, b as WebFontsOptions } from './shared/preset-web-fonts.DSrOMtoz.js';
3
+ export { c as WebFontProcessor } from './shared/preset-web-fonts.DSrOMtoz.js';
74
4
 
75
5
  declare function normalizedFontMeta(meta: WebFontMeta | string, defaultProvider: WebFontsProviders): ResolvedWebFontMeta;
76
6
 
@@ -83,4 +13,4 @@ declare function createGoogleCompatibleProvider(name: WebFontsProviders, host: s
83
13
  */
84
14
  declare const presetWebFonts: _unocss_core.PresetFactory<any, WebFontsOptions>;
85
15
 
86
- export { type Provider, type ResolvedWebFontMeta, type WebFontMeta, type WebFontsOptions, type WebFontsProviders, createGoogleCompatibleProvider as createGoogleProvider, presetWebFonts as default, normalizedFontMeta };
16
+ export { Provider, ResolvedWebFontMeta, WebFontMeta, WebFontsOptions, WebFontsProviders, createGoogleCompatibleProvider as createGoogleProvider, presetWebFonts as default, normalizedFontMeta };
package/dist/index.mjs CHANGED
@@ -111,6 +111,7 @@ function createWebFontPreset(fetcher) {
111
111
  customFetch = fetcher,
112
112
  timeouts = {}
113
113
  } = options;
114
+ const processors = toArray(options.processors || []);
114
115
  const fontObject = Object.fromEntries(
115
116
  Object.entries(options.fonts || {}).map(([name, meta]) => [name, toArray(meta).map((m) => normalizedFontMeta(m, defaultProvider))])
116
117
  );
@@ -120,18 +121,24 @@ function createWebFontPreset(fetcher) {
120
121
  if (timeouts === false)
121
122
  return customFetch(url);
122
123
  const {
123
- warning = 500,
124
+ warning = 1e3,
124
125
  failure = 2e3
125
126
  } = timeouts;
127
+ let warned = false;
126
128
  const timer = setTimeout(() => {
127
129
  console.warn(`[unocss] Fetching web fonts: ${url}`);
130
+ warned = true;
128
131
  }, warning);
129
132
  return await Promise.race([
130
133
  customFetch(url),
131
134
  new Promise((_, reject) => {
132
135
  setTimeout(() => reject(new Error(`[unocss] Fetch web fonts timeout.`)), failure);
133
136
  })
134
- ]).finally(() => clearTimeout(timer));
137
+ ]).then((res) => {
138
+ if (warned)
139
+ console.info(`[unocss] Web fonts fetched.`);
140
+ return res;
141
+ }).finally(() => clearTimeout(timer));
135
142
  }
136
143
  async function importUrl(url) {
137
144
  if (inlineImports) {
@@ -148,23 +155,43 @@ function createWebFontPreset(fetcher) {
148
155
  return `@import url('${url}');`;
149
156
  }
150
157
  }
151
- const enabledProviders = new Set(fonts.map((i) => i.provider));
158
+ const enabledProviders = Array.from(new Set(fonts.map((i) => i.provider)));
159
+ async function getCSSDefault(fonts2, providers) {
160
+ const preflights = [];
161
+ for (const provider of providers) {
162
+ const fontsForProvider = fonts2.filter((i) => i.provider.name === provider.name);
163
+ if (provider.getImportUrl) {
164
+ const url = provider.getImportUrl(fontsForProvider);
165
+ if (url)
166
+ preflights.push(await importUrl(url));
167
+ }
168
+ preflights.push(provider.getPreflight?.(fontsForProvider));
169
+ }
170
+ const css = preflights.filter(Boolean).join("\n");
171
+ return css;
172
+ }
152
173
  const preset = {
153
174
  name: "@unocss/preset-web-fonts",
154
175
  preflights: [
155
176
  {
156
177
  async getCSS() {
157
- const preflights = [];
158
- for (const provider of enabledProviders) {
159
- const fontsForProvider = fonts.filter((i) => i.provider.name === provider.name);
160
- if (provider.getImportUrl) {
161
- const url = provider.getImportUrl(fontsForProvider);
162
- if (url)
163
- preflights.push(await importUrl(url));
178
+ let css;
179
+ for (const processor of processors) {
180
+ const result = await processor.getCSS?.(fonts, enabledProviders, getCSSDefault);
181
+ if (result) {
182
+ css = result;
183
+ break;
164
184
  }
165
- preflights.push(provider.getPreflight?.(fontsForProvider));
166
185
  }
167
- return preflights.filter(Boolean).join("\n");
186
+ if (!css) {
187
+ css = await getCSSDefault(
188
+ fonts,
189
+ enabledProviders
190
+ );
191
+ }
192
+ for (const processor of processors)
193
+ css = await processor.transformCSS?.(css) || css;
194
+ return css;
168
195
  },
169
196
  layer: inlineImports ? void 0 : LAYER_IMPORTS
170
197
  }
@@ -0,0 +1,32 @@
1
+ import { c as WebFontProcessor } from './shared/preset-web-fonts.DSrOMtoz.mjs';
2
+ import '@unocss/core';
3
+
4
+ interface LocalFontProcessorOptions {
5
+ /**
6
+ * Current working directory
7
+ *
8
+ * @default process.cwd()
9
+ */
10
+ cwd?: string;
11
+ /**
12
+ * Directory to cache the fonts
13
+ *
14
+ * @default 'node_modules/.cache/unocss/fonts'
15
+ */
16
+ cacheDir?: string;
17
+ /**
18
+ * Directory to save the fonts assets
19
+ *
20
+ * @default 'public/assets/fonts'
21
+ */
22
+ fontAssetsDir?: string;
23
+ /**
24
+ * Base URL to serve the fonts from the client
25
+ *
26
+ * @default '/assets/fonts'
27
+ */
28
+ fontServeBaseUrl?: string;
29
+ }
30
+ declare function createLocalFontProcessor(options?: LocalFontProcessorOptions): WebFontProcessor;
31
+
32
+ export { type LocalFontProcessorOptions, createLocalFontProcessor };
@@ -0,0 +1,32 @@
1
+ import { c as WebFontProcessor } from './shared/preset-web-fonts.DSrOMtoz.js';
2
+ import '@unocss/core';
3
+
4
+ interface LocalFontProcessorOptions {
5
+ /**
6
+ * Current working directory
7
+ *
8
+ * @default process.cwd()
9
+ */
10
+ cwd?: string;
11
+ /**
12
+ * Directory to cache the fonts
13
+ *
14
+ * @default 'node_modules/.cache/unocss/fonts'
15
+ */
16
+ cacheDir?: string;
17
+ /**
18
+ * Directory to save the fonts assets
19
+ *
20
+ * @default 'public/assets/fonts'
21
+ */
22
+ fontAssetsDir?: string;
23
+ /**
24
+ * Base URL to serve the fonts from the client
25
+ *
26
+ * @default '/assets/fonts'
27
+ */
28
+ fontServeBaseUrl?: string;
29
+ }
30
+ declare function createLocalFontProcessor(options?: LocalFontProcessorOptions): WebFontProcessor;
31
+
32
+ export { type LocalFontProcessorOptions, createLocalFontProcessor };
package/dist/local.mjs ADDED
@@ -0,0 +1,83 @@
1
+ import { createHash } from 'node:crypto';
2
+ import fs from 'node:fs';
3
+ import fsp from 'node:fs/promises';
4
+ import process from 'node:process';
5
+ import { resolve, join } from 'node:path';
6
+ import { Buffer } from 'node:buffer';
7
+ import { fetch } from 'ofetch';
8
+
9
+ function replaceAsync(string, searchValue, replacer) {
10
+ try {
11
+ if (typeof replacer === "function") {
12
+ const values = [];
13
+ String.prototype.replace.call(string, searchValue, (...args) => {
14
+ values.push(replacer(...args));
15
+ return "";
16
+ });
17
+ return Promise.all(values).then((resolvedValues) => {
18
+ return String.prototype.replace.call(string, searchValue, () => {
19
+ return resolvedValues.shift() || "";
20
+ });
21
+ });
22
+ } else {
23
+ return Promise.resolve(
24
+ String.prototype.replace.call(string, searchValue, replacer)
25
+ );
26
+ }
27
+ } catch (error) {
28
+ return Promise.reject(error);
29
+ }
30
+ }
31
+
32
+ const fontUrlRegex = /[-\w@:%+.~#?&/=]+\.(?:woff2?|eot|ttf|otf|svg)/gi;
33
+ function createLocalFontProcessor(options) {
34
+ const cwd = options?.cwd || process.cwd();
35
+ const cacheDir = resolve(cwd, options?.cacheDir || "node_modules/.cache/unocss/fonts");
36
+ const fontAssetsDir = resolve(cwd, options?.fontAssetsDir || "public/assets/fonts");
37
+ const fontServeBaseUrl = options?.fontServeBaseUrl || "/assets/fonts";
38
+ async function _downloadFont(url, assetPath) {
39
+ const response = await fetch(url).then((r) => r.arrayBuffer());
40
+ await fsp.mkdir(fontAssetsDir, { recursive: true });
41
+ await fsp.writeFile(assetPath, Buffer.from(response));
42
+ }
43
+ const cache = /* @__PURE__ */ new Map();
44
+ function downloadFont(url, assetPath) {
45
+ if (!cache.has(url))
46
+ cache.set(url, _downloadFont(url, assetPath));
47
+ return cache.get(url);
48
+ }
49
+ return {
50
+ async getCSS(fonts, providers, getCSSDefault) {
51
+ const hash = getHash(JSON.stringify(fonts));
52
+ const cachePath = join(cacheDir, `${hash}.css`);
53
+ if (fs.existsSync(cachePath)) {
54
+ return fsp.readFile(cachePath, "utf-8");
55
+ }
56
+ const css = await getCSSDefault(fonts, providers);
57
+ await fsp.mkdir(cacheDir, { recursive: true });
58
+ await fsp.writeFile(cachePath, css, "utf-8");
59
+ return css;
60
+ },
61
+ async transformCSS(css) {
62
+ return await replaceAsync(css, fontUrlRegex, async (url) => {
63
+ const hash = getHash(url);
64
+ const ext = url.split(".").pop();
65
+ let name = "";
66
+ const match1 = url.match(/\/s\/([^/]+)\//);
67
+ if (match1)
68
+ name = match1[1].replace(/\W/g, " ").trim().replace(/\s+/, "-").toLowerCase();
69
+ const filename = `${[name, hash].filter(Boolean).join("-")}.${ext}`;
70
+ const assetPath = join(fontAssetsDir, filename);
71
+ if (!fs.existsSync(assetPath)) {
72
+ await downloadFont(url, assetPath);
73
+ }
74
+ return `${fontServeBaseUrl}/${filename}`;
75
+ });
76
+ }
77
+ };
78
+ }
79
+ function getHash(input, length = 8) {
80
+ return createHash("sha256").update(input).digest("hex").slice(0, length);
81
+ }
82
+
83
+ export { createLocalFontProcessor };
@@ -0,0 +1,83 @@
1
+ import { Awaitable, Arrayable } from '@unocss/core';
2
+
3
+ type WebFontsProviders = 'google' | 'bunny' | 'fontshare' | 'none' | Provider;
4
+ interface WebFontMeta {
5
+ name: string;
6
+ weights?: (string | number)[];
7
+ italic?: boolean;
8
+ /**
9
+ * Override the provider
10
+ * @default <matches root config>
11
+ */
12
+ provider?: WebFontsProviders;
13
+ }
14
+ interface WebFontProcessor {
15
+ getCSS?: (fonts: ResolvedWebFontMeta[], providers: Provider[], getCSSDefault: (fonts: ResolvedWebFontMeta[], providers: Provider[]) => Awaitable<string>) => Awaitable<string | undefined>;
16
+ transformCSS?: (css: string) => Promise<string | undefined>;
17
+ }
18
+ interface ResolvedWebFontMeta extends Omit<WebFontMeta, 'provider'> {
19
+ provider: Provider;
20
+ }
21
+ interface WebFontsOptions {
22
+ /**
23
+ * Provider service of the web fonts
24
+ * @default 'google'
25
+ */
26
+ provider?: WebFontsProviders;
27
+ /**
28
+ * The fonts
29
+ */
30
+ fonts?: Record<string, WebFontMeta | string | (WebFontMeta | string)[]>;
31
+ /**
32
+ * Extend fonts to the theme object
33
+ * @default true
34
+ */
35
+ extendTheme?: boolean;
36
+ /**
37
+ * Key for the theme object
38
+ *
39
+ * @default 'fontFamily'
40
+ */
41
+ themeKey?: string;
42
+ /**
43
+ * Inline CSS @import()
44
+ *
45
+ * @default true
46
+ */
47
+ inlineImports?: boolean;
48
+ /**
49
+ * Custom fetch function
50
+ *
51
+ * @default undefined
52
+ */
53
+ customFetch?: (url: string) => Promise<any>;
54
+ /**
55
+ * Custom processor for the font CSS
56
+ */
57
+ processors?: Arrayable<WebFontProcessor>;
58
+ /**
59
+ * Timeouts for fetching web fonts
60
+ */
61
+ timeouts?: false | {
62
+ /**
63
+ * Timeout for printing warning message
64
+ *
65
+ * @default 500
66
+ */
67
+ warning?: number;
68
+ /**
69
+ * Timeout for failing the fetch
70
+ *
71
+ * @default 2000
72
+ */
73
+ failure?: number;
74
+ };
75
+ }
76
+ interface Provider {
77
+ name: WebFontsProviders;
78
+ getPreflight?: (fonts: WebFontMeta[]) => string;
79
+ getImportUrl?: (fonts: WebFontMeta[]) => string | undefined;
80
+ getFontName?: (font: WebFontMeta) => string;
81
+ }
82
+
83
+ export type { Provider as P, ResolvedWebFontMeta as R, WebFontMeta as W, WebFontsProviders as a, WebFontsOptions as b, WebFontProcessor as c };
@@ -0,0 +1,83 @@
1
+ import { Awaitable, Arrayable } from '@unocss/core';
2
+
3
+ type WebFontsProviders = 'google' | 'bunny' | 'fontshare' | 'none' | Provider;
4
+ interface WebFontMeta {
5
+ name: string;
6
+ weights?: (string | number)[];
7
+ italic?: boolean;
8
+ /**
9
+ * Override the provider
10
+ * @default <matches root config>
11
+ */
12
+ provider?: WebFontsProviders;
13
+ }
14
+ interface WebFontProcessor {
15
+ getCSS?: (fonts: ResolvedWebFontMeta[], providers: Provider[], getCSSDefault: (fonts: ResolvedWebFontMeta[], providers: Provider[]) => Awaitable<string>) => Awaitable<string | undefined>;
16
+ transformCSS?: (css: string) => Promise<string | undefined>;
17
+ }
18
+ interface ResolvedWebFontMeta extends Omit<WebFontMeta, 'provider'> {
19
+ provider: Provider;
20
+ }
21
+ interface WebFontsOptions {
22
+ /**
23
+ * Provider service of the web fonts
24
+ * @default 'google'
25
+ */
26
+ provider?: WebFontsProviders;
27
+ /**
28
+ * The fonts
29
+ */
30
+ fonts?: Record<string, WebFontMeta | string | (WebFontMeta | string)[]>;
31
+ /**
32
+ * Extend fonts to the theme object
33
+ * @default true
34
+ */
35
+ extendTheme?: boolean;
36
+ /**
37
+ * Key for the theme object
38
+ *
39
+ * @default 'fontFamily'
40
+ */
41
+ themeKey?: string;
42
+ /**
43
+ * Inline CSS @import()
44
+ *
45
+ * @default true
46
+ */
47
+ inlineImports?: boolean;
48
+ /**
49
+ * Custom fetch function
50
+ *
51
+ * @default undefined
52
+ */
53
+ customFetch?: (url: string) => Promise<any>;
54
+ /**
55
+ * Custom processor for the font CSS
56
+ */
57
+ processors?: Arrayable<WebFontProcessor>;
58
+ /**
59
+ * Timeouts for fetching web fonts
60
+ */
61
+ timeouts?: false | {
62
+ /**
63
+ * Timeout for printing warning message
64
+ *
65
+ * @default 500
66
+ */
67
+ warning?: number;
68
+ /**
69
+ * Timeout for failing the fetch
70
+ *
71
+ * @default 2000
72
+ */
73
+ failure?: number;
74
+ };
75
+ }
76
+ interface Provider {
77
+ name: WebFontsProviders;
78
+ getPreflight?: (fonts: WebFontMeta[]) => string;
79
+ getImportUrl?: (fonts: WebFontMeta[]) => string | undefined;
80
+ getFontName?: (font: WebFontMeta) => string;
81
+ }
82
+
83
+ export type { Provider as P, ResolvedWebFontMeta as R, WebFontMeta as W, WebFontsProviders as a, WebFontsOptions as b, WebFontProcessor as c };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@unocss/preset-web-fonts",
3
3
  "type": "module",
4
- "version": "0.61.2",
4
+ "version": "0.61.4",
5
5
  "description": "Web Fonts support for Uno CSS",
6
6
  "author": "Anthony Fu <anthonyfu117@hotmail.com>",
7
7
  "license": "MIT",
@@ -27,18 +27,30 @@
27
27
  ".": {
28
28
  "types": "./dist/index.d.mts",
29
29
  "default": "./dist/index.mjs"
30
+ },
31
+ "./local": {
32
+ "types": "./dist/local.d.mts",
33
+ "default": "./dist/local.mjs"
30
34
  }
31
35
  },
32
36
  "main": "dist/index.mjs",
33
37
  "module": "dist/index.mjs",
34
38
  "types": "dist/index.d.ts",
39
+ "typesVersions": {
40
+ "*": {
41
+ "*": [
42
+ "./dist/*",
43
+ "./*"
44
+ ]
45
+ }
46
+ },
35
47
  "files": [
36
48
  "*.css",
37
49
  "dist"
38
50
  ],
39
51
  "dependencies": {
40
52
  "ofetch": "^1.3.4",
41
- "@unocss/core": "0.61.2"
53
+ "@unocss/core": "0.61.4"
42
54
  },
43
55
  "scripts": {
44
56
  "build": "unbuild",