@hamur/icon 0.0.0-stage → 0.0.1

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 (88) hide show
  1. package/LICENSE +22 -0
  2. package/README.md +14 -2
  3. package/dist/chunks/bun-react-fhd05zxm.js +206 -0
  4. package/dist/chunks/bun-react-nygte91t.js +305 -0
  5. package/dist/src/adapters/angular.js +104 -0
  6. package/dist/src/adapters/html.js +47 -0
  7. package/dist/src/adapters/preact.js +56 -0
  8. package/dist/src/adapters/react.js +66 -0
  9. package/dist/src/adapters/solid.js +97 -0
  10. package/dist/src/adapters/svelte.js +6 -0
  11. package/dist/src/adapters/vue.js +63 -0
  12. package/dist/src/index.js +897 -0
  13. package/dist/src/testing.js +46 -0
  14. package/dist/types/src/adapters/angular-icon.d.ts +29 -0
  15. package/dist/types/src/adapters/angular.d.ts +2 -0
  16. package/dist/types/src/adapters/html.d.ts +8 -0
  17. package/dist/types/src/adapters/preact.d.ts +6 -0
  18. package/dist/types/src/adapters/react.d.ts +6 -0
  19. package/dist/types/src/adapters/solid-icon.d.ts +6 -0
  20. package/dist/types/src/adapters/solid.d.ts +4 -0
  21. package/dist/types/src/adapters/svelte.d.ts +2 -0
  22. package/dist/types/src/adapters/vue.d.ts +41 -0
  23. package/dist/types/src/build/client.d.ts +21 -0
  24. package/dist/types/src/build/collections.d.ts +13 -0
  25. package/dist/types/src/build/css.d.ts +10 -0
  26. package/dist/types/src/build/custom.d.ts +10 -0
  27. package/dist/types/src/build/endpoint.d.ts +4 -0
  28. package/dist/types/src/build/runtime.d.ts +3 -0
  29. package/dist/types/src/build/scan.d.ts +37 -0
  30. package/dist/types/src/clean.d.ts +3 -0
  31. package/dist/types/src/index.d.ts +8 -0
  32. package/dist/types/src/kit.d.ts +10 -0
  33. package/dist/types/src/locate.d.ts +4 -0
  34. package/dist/types/src/module.d.ts +3 -0
  35. package/dist/types/src/name.d.ts +13 -0
  36. package/dist/types/src/options.d.ts +46 -0
  37. package/dist/types/src/render.d.ts +68 -0
  38. package/dist/types/src/runtime/bundle.d.ts +2 -0
  39. package/dist/types/src/runtime/classes.d.ts +3 -0
  40. package/dist/types/src/runtime/icons.d.ts +27 -0
  41. package/dist/types/src/runtime/index.d.ts +2 -0
  42. package/dist/types/src/runtime/remote.d.ts +22 -0
  43. package/dist/types/src/runtime/server.d.ts +3 -0
  44. package/dist/types/src/server/door.d.ts +1 -0
  45. package/dist/types/src/server/endpoint.d.ts +28 -0
  46. package/dist/types/src/server/handler.d.ts +1 -0
  47. package/dist/types/src/testing.d.ts +2 -0
  48. package/dist/types/src/types.d.ts +102 -0
  49. package/package.json +114 -4
  50. package/src/adapters/Icon.svelte +60 -0
  51. package/src/adapters/angular-icon.ts +112 -0
  52. package/src/adapters/angular.ts +2 -0
  53. package/src/adapters/html.ts +44 -0
  54. package/src/adapters/preact.ts +63 -0
  55. package/src/adapters/react.ts +80 -0
  56. package/src/adapters/solid-icon.ts +99 -0
  57. package/src/adapters/solid.ts +8 -0
  58. package/src/adapters/svelte.ts +2 -0
  59. package/src/adapters/test/IconPage.svelte +5 -0
  60. package/src/adapters/test/support.ts +78 -0
  61. package/src/adapters/vue.ts +64 -0
  62. package/src/build/client.ts +113 -0
  63. package/src/build/collections.ts +86 -0
  64. package/src/build/css.ts +67 -0
  65. package/src/build/custom.ts +120 -0
  66. package/src/build/endpoint.ts +16 -0
  67. package/src/build/runtime.ts +24 -0
  68. package/src/build/scan.ts +148 -0
  69. package/src/clean.ts +66 -0
  70. package/src/env.d.ts +22 -0
  71. package/src/index.ts +10 -0
  72. package/src/kit.ts +29 -0
  73. package/src/locate.ts +20 -0
  74. package/src/module.ts +35 -0
  75. package/src/name.ts +38 -0
  76. package/src/options.ts +275 -0
  77. package/src/render.ts +247 -0
  78. package/src/runtime/bundle.ts +26 -0
  79. package/src/runtime/classes.ts +5 -0
  80. package/src/runtime/icons.ts +146 -0
  81. package/src/runtime/index.ts +17 -0
  82. package/src/runtime/remote.ts +147 -0
  83. package/src/runtime/server.ts +7 -0
  84. package/src/server/door.ts +1 -0
  85. package/src/server/endpoint.ts +251 -0
  86. package/src/server/handler.ts +30 -0
  87. package/src/testing.ts +23 -0
  88. package/src/types.ts +97 -0
@@ -0,0 +1,148 @@
1
+ import { readdirSync, readFileSync, type Dirent } from "node:fs"
2
+ import { join, relative, sep } from "node:path"
3
+ import { normalizeName } from "../name.ts"
4
+
5
+ /** The files the scan reads, the ones that hold string literals of the app. */
6
+ export const SCAN_EXTENSIONS = /\.(?:[cm]?[jt]sx?|vue|svelte|css|html|mdx?)$/
7
+ const DECLARATIONS = /\.d\.[cm]?ts$/
8
+ const LITERAL = /"([^"\\\n]*)"|'([^'\\\n]*)'|`([^`\\$]*)`/g
9
+
10
+ export interface ScanRoot {
11
+ /** The app's or a layer's directory; `include` and `exclude` are globs from here. */
12
+ rootDir: string
13
+ /** The folders below it to read. */
14
+ dirs: string[]
15
+ /** Folders inside `dirs` that are not read. */
16
+ skip: string[]
17
+ }
18
+
19
+ export interface ScanRules {
20
+ include: string[]
21
+ exclude: string[]
22
+ }
23
+
24
+ export interface ScanSource {
25
+ file: string
26
+ /** From the app's `rootDir`. */
27
+ relative: string
28
+ }
29
+
30
+ const MARKUP_SEPARATORS = /[\s"'<>=]+/
31
+
32
+ function* literalTokens(text: string, separator: RegExp = /\s+/): Generator<string> {
33
+ for (const match of text.matchAll(LITERAL)) {
34
+ for (const token of (match[1] ?? match[2] ?? match[3] ?? "").split(separator)) if (token !== "") yield token
35
+ }
36
+ }
37
+
38
+ /** The icon names (`prefix:name`) that are string literals of `text` with a known prefix, in the order found. */
39
+ export function scanText(text: string, prefixes: readonly string[], selectorPrefix: string): string[] {
40
+ const found = new Set<string>()
41
+ for (const token of literalTokens(text)) {
42
+ const name = normalizeName(token, prefixes, selectorPrefix)
43
+ if (name && prefixes.includes(name.prefix)) found.add(`${name.prefix}:${name.name}`)
44
+ }
45
+ return [...found]
46
+ }
47
+
48
+ /** An icon class of the app: the class as written (`i-mdi-home`, `i-mdi:home`) and the icon it names (`mdi:home`). */
49
+ export interface IconClass {
50
+ class: string
51
+ name: string
52
+ }
53
+
54
+ /** The class tokens of the literals of `text` and, in a stylesheet, the `.i-…` selectors (`\:` for the colon), that name an icon of a known prefix. */
55
+ export function scanClassText(
56
+ text: string,
57
+ prefixes: readonly string[],
58
+ selectorPrefix: string,
59
+ stylesheet = false,
60
+ ): IconClass[] {
61
+ const found = new Map<string, IconClass>()
62
+ const add = (token: string): void => {
63
+ if (selectorPrefix === "" || !token.startsWith(selectorPrefix) || found.has(token)) return
64
+ const name = normalizeName(token, prefixes, selectorPrefix)
65
+ if (name && prefixes.includes(name.prefix)) found.set(token, { class: token, name: `${name.prefix}:${name.name}` })
66
+ }
67
+ if (stylesheet) {
68
+ const escaped = selectorPrefix.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")
69
+ for (const match of text.matchAll(new RegExp(`\\.(${escaped}[a-z0-9_-]+(?:\\\\:[a-z0-9_-]+)?)`, "gi")))
70
+ add(match[1]!.replace("\\", ""))
71
+ } else for (const token of literalTokens(text, MARKUP_SEPARATORS)) add(token)
72
+ return [...found.values()]
73
+ }
74
+
75
+ function walk(dir: string, skip: ReadonlySet<string>, out: string[]): void {
76
+ let entries: Dirent[]
77
+ try {
78
+ entries = readdirSync(dir, { withFileTypes: true })
79
+ } catch {
80
+ return
81
+ }
82
+ for (const entry of entries) {
83
+ const path = join(dir, entry.name)
84
+ if (entry.name.startsWith(".") || entry.name === "node_modules" || skip.has(path)) continue
85
+ if (entry.isDirectory()) walk(path, skip, out)
86
+ else if (SCAN_EXTENSIONS.test(entry.name) && !DECLARATIONS.test(entry.name)) out.push(path)
87
+ }
88
+ }
89
+
90
+ /** The files below the `dirs` of each root, each once, narrowed by `include` and `exclude`. */
91
+ export function findSources(roots: ScanRoot[], appRoot: string, rules: ScanRules): ScanSource[] {
92
+ const include = rules.include.map((pattern) => new Bun.Glob(pattern))
93
+ const exclude = rules.exclude.map((pattern) => new Bun.Glob(pattern))
94
+ const seen = new Set<string>()
95
+ const out: ScanSource[] = []
96
+ for (const root of roots) {
97
+ const files: string[] = []
98
+ for (const dir of root.dirs) walk(dir, new Set(root.skip), files)
99
+ for (const file of files) {
100
+ if (seen.has(file)) continue
101
+ const own = relative(root.rootDir, file).split(sep).join("/")
102
+ if ((include.length > 0 && !include.some((glob) => glob.match(own))) || exclude.some((glob) => glob.match(own)))
103
+ continue
104
+ seen.add(file)
105
+ out.push({ file, relative: relative(appRoot, file).split(sep).join("/") })
106
+ }
107
+ }
108
+ return out
109
+ }
110
+
111
+ /** Each icon name the sources write, with the first file that does. */
112
+ export function scanSources(
113
+ sources: ScanSource[],
114
+ prefixes: readonly string[],
115
+ selectorPrefix: string,
116
+ ): Map<string, string> {
117
+ const found = new Map<string, string>()
118
+ for (const source of sources) {
119
+ let text: string
120
+ try {
121
+ text = readFileSync(source.file, "utf8")
122
+ } catch {
123
+ continue
124
+ }
125
+ for (const name of scanText(text, prefixes, selectorPrefix)) if (!found.has(name)) found.set(name, source.relative)
126
+ }
127
+ return found
128
+ }
129
+
130
+ /** Each icon class the sources write, with the icon it names and the first file that writes it. */
131
+ export function scanClassSources(
132
+ sources: ScanSource[],
133
+ prefixes: readonly string[],
134
+ selectorPrefix: string,
135
+ ): Map<string, { name: string; file: string }> {
136
+ const found = new Map<string, { name: string; file: string }>()
137
+ for (const source of sources) {
138
+ let text: string
139
+ try {
140
+ text = readFileSync(source.file, "utf8")
141
+ } catch {
142
+ continue
143
+ }
144
+ for (const entry of scanClassText(text, prefixes, selectorPrefix, source.file.endsWith(".css")))
145
+ if (!found.has(entry.class)) found.set(entry.class, { name: entry.name, file: source.relative })
146
+ }
147
+ return found
148
+ }
package/src/clean.ts ADDED
@@ -0,0 +1,66 @@
1
+ import { NAME_PATTERN } from "./name.ts"
2
+ import type { IconifyJSON } from "./types.ts"
3
+
4
+ const MAX_BODY_LENGTH = 64 * 1024
5
+ const isObject = (value: unknown): value is Record<string, unknown> =>
6
+ typeof value === "object" && value !== null && !Array.isArray(value)
7
+ const ICON_NUMBERS = ["width", "height", "left", "top", "rotate"] as const
8
+
9
+ const finite = (value: unknown): value is number => typeof value === "number" && Number.isFinite(value)
10
+
11
+ /** Copies the known keys of an icon or alias; undefined when one is of the wrong type. */
12
+ function cleanEntry(value: unknown, alias: boolean): Record<string, unknown> | undefined {
13
+ if (!isObject(value)) return undefined
14
+ const out: Record<string, unknown> = {}
15
+ if (alias) {
16
+ if (typeof value.parent !== "string") return undefined
17
+ out.parent = value.parent
18
+ } else {
19
+ if (typeof value.body !== "string" || value.body.length > MAX_BODY_LENGTH) return undefined
20
+ out.body = value.body
21
+ }
22
+ for (const key of ICON_NUMBERS) {
23
+ if (value[key] === undefined) continue
24
+ if (!finite(value[key])) return undefined
25
+ out[key] = value[key]
26
+ }
27
+ for (const key of ["hFlip", "vFlip"]) {
28
+ if (value[key] === undefined) continue
29
+ if (typeof value[key] !== "boolean") return undefined
30
+ out[key] = value[key]
31
+ }
32
+ return out
33
+ }
34
+
35
+ /** The upstream answer reduced to what `resolveIcon` reads: known keys, right types, aliases with a known parent. */
36
+ export function cleanCollection(prefix: string, body: Record<string, unknown>): IconifyJSON {
37
+ const clean: Record<string, unknown> = { prefix, icons: {} }
38
+ for (const key of ["width", "height", "left", "top"]) if (finite(body[key])) clean[key] = body[key]
39
+ const icons = clean.icons as Record<string, unknown>
40
+ for (const [name, value] of Object.entries(body.icons as Record<string, unknown>)) {
41
+ const entry = NAME_PATTERN.test(name) ? cleanEntry(value, false) : undefined
42
+ if (entry) icons[name] = entry
43
+ }
44
+ if (isObject(body.aliases)) {
45
+ const aliases: Record<string, unknown> = {}
46
+ const candidates = Object.entries(body.aliases)
47
+ .filter(([name]) => NAME_PATTERN.test(name))
48
+ .flatMap(([name, value]) => {
49
+ const entry = cleanEntry(value, true)
50
+ return entry ? [[name, entry] as const] : []
51
+ })
52
+ for (let changed = true; changed;) {
53
+ changed = false
54
+ for (const [name, entry] of candidates) {
55
+ if (Object.hasOwn(aliases, name)) continue
56
+ const parent = entry.parent as string
57
+ if (Object.hasOwn(icons, parent) || Object.hasOwn(aliases, parent)) {
58
+ aliases[name] = entry
59
+ changed = true
60
+ }
61
+ }
62
+ }
63
+ clean.aliases = aliases
64
+ }
65
+ return clean as unknown as IconifyJSON
66
+ }
package/src/env.d.ts ADDED
@@ -0,0 +1,22 @@
1
+ interface ImportMeta {
2
+ readonly dev?: boolean
3
+ readonly server?: boolean
4
+ readonly hot?: unknown
5
+ }
6
+
7
+ declare module "#hamur/icon/options" {
8
+ const options: import("./types.ts").IconRuntimeOptions
9
+ export default options
10
+ }
11
+
12
+ declare module "#hamur/icon/endpoint" {
13
+ const endpoint: import("./types.ts").IconEndpointOptions
14
+ export default endpoint
15
+ }
16
+
17
+ declare module "#hamur/icon/client" {
18
+ const client: import("./types.ts").IconPayload
19
+ export default client
20
+ }
21
+
22
+ declare module "#hamur/icon/classes.css" {}
package/src/index.ts ADDED
@@ -0,0 +1,10 @@
1
+ import type { IconOptions } from "./types.ts"
2
+
3
+ export { default } from "./module.ts"
4
+ export type { IconifyIcon, IconifyJSON, IconOptions, IconProps } from "./types.ts"
5
+
6
+ declare module "hamur" {
7
+ interface HamurModuleOptions {
8
+ icon?: IconOptions
9
+ }
10
+ }
package/src/kit.ts ADDED
@@ -0,0 +1,29 @@
1
+ import type { HamurContext } from "hamur/kit"
2
+ import type { IconifyJSON } from "./types.ts"
3
+ import { DiagnosticError } from "hamur/kit"
4
+
5
+ declare module "hamur" {
6
+ interface HamurHooks {
7
+ /** Once in `modules:done`, with every installed collection by prefix; add a collection or replace one by assigning its prefix. */
8
+ "icon:collections": (collections: Record<string, IconifyJSON>) => void | Promise<void>
9
+ }
10
+ }
11
+
12
+ const isObject = (value: unknown): value is Record<string, unknown> =>
13
+ typeof value === "object" && value !== null && !Array.isArray(value)
14
+
15
+ /** The collections after `icon:collections`; a value that is not Iconify JSON fails the build naming its prefix. */
16
+ export async function callCollectionsHook(
17
+ hamur: HamurContext,
18
+ collections: Record<string, IconifyJSON>,
19
+ ): Promise<Record<string, IconifyJSON>> {
20
+ await hamur.hooks.callHook("icon:collections", collections)
21
+ for (const [prefix, collection] of Object.entries(collections)) {
22
+ if (!isObject(collection) || !isObject(collection.icons))
23
+ throw new DiagnosticError(
24
+ "HAMUR_E5902",
25
+ `icon:collections: collections[${JSON.stringify(prefix)}] must be Iconify JSON, { prefix, icons }`,
26
+ )
27
+ }
28
+ return collections
29
+ }
package/src/locate.ts ADDED
@@ -0,0 +1,20 @@
1
+ import { existsSync } from "node:fs"
2
+ import { dirname, join } from "node:path"
3
+
4
+ /** Where a collection's file is looked for, in `node_modules` of each directory. */
5
+ export const collectionCandidates = (prefix: string, full: boolean): string[] => [
6
+ `@iconify-json/${prefix}/icons.json`,
7
+ ...(full ? [`@iconify/json/json/${prefix}.json`] : []),
8
+ ]
9
+
10
+ /** The file of a collection, looked for in `node_modules` from `rootDir` up, so a hoisted workspace install is found. */
11
+ export function locateCollection(rootDir: string, prefix: string, full: boolean): string | undefined {
12
+ const candidates = collectionCandidates(prefix, full)
13
+ for (let dir = rootDir; ; dir = dirname(dir)) {
14
+ for (const candidate of candidates) {
15
+ const file = join(dir, "node_modules", candidate)
16
+ if (existsSync(file)) return file
17
+ }
18
+ if (dirname(dir) === dir) return undefined
19
+ }
20
+ }
package/src/module.ts ADDED
@@ -0,0 +1,35 @@
1
+ import { existsSync } from "node:fs"
2
+ import { defineModule, updateRuntimeConfig } from "hamur/kit"
3
+ import { createWarner, setupClient } from "./build/client.ts"
4
+ import { listedCollections, setupCollections } from "./build/collections.ts"
5
+ import { locateCollection } from "./locate.ts"
6
+ import { setupCss } from "./build/css.ts"
7
+ import { setupEndpoint } from "./build/endpoint.ts"
8
+ import { setupRuntime } from "./build/runtime.ts"
9
+ import { iconDefaults, iconDefaultsUnder, resolveOptions } from "./options.ts"
10
+ import type { IconifyJSON, IconOptions } from "./types.ts"
11
+
12
+ export default defineModule<IconOptions>({
13
+ meta: { name: "icon", configKey: "icon", hooks: ["icon:collections"] },
14
+ setup(input, hamur) {
15
+ const { rootDir, preset } = hamur.options
16
+ const options = resolveOptions(input, {
17
+ rootDir,
18
+ layerRoots: hamur.options.layers.map((layer) => layer.rootDir),
19
+ preset,
20
+ exists: existsSync,
21
+ listed: listedCollections(rootDir),
22
+ locate: (prefix, full) => locateCollection(rootDir, prefix, full),
23
+ })
24
+ const defaults = iconDefaultsUnder(iconDefaults(input), hamur.options.runtimeConfig.public?.icon)
25
+ if (Object.keys(defaults).length) updateRuntimeConfig({ public: { icon: defaults } })
26
+ const prefixes: string[] = []
27
+ const collections: Record<string, IconifyJSON> = {}
28
+ setupCollections(options, hamur, prefixes, collections)
29
+ const warn = createWarner()
30
+ setupClient(options, hamur, collections, warn)
31
+ setupCss(options, hamur, collections, warn)
32
+ setupRuntime(options, prefixes)
33
+ setupEndpoint(options, hamur)
34
+ },
35
+ })
package/src/name.ts ADDED
@@ -0,0 +1,38 @@
1
+ /** A prefix and a name of an icon. */
2
+ export const NAME_PATTERN = /^[a-z0-9]+(-[a-z0-9]+)*$/
3
+
4
+ export interface IconName {
5
+ prefix: string
6
+ name: string
7
+ }
8
+
9
+ function pair(text: string): IconName | undefined {
10
+ const at = text.indexOf(":")
11
+ if (at === -1) return undefined
12
+ const prefix = text.slice(0, at)
13
+ const name = text.slice(at + 1)
14
+ return NAME_PATTERN.test(prefix) && NAME_PATTERN.test(name) ? { prefix, name } : undefined
15
+ }
16
+
17
+ /**
18
+ * `prefix:name`, or the class form `<selectorPrefix>prefix:name` and `<selectorPrefix>prefix-name`; the last is read against
19
+ * the prefixes the build knows, the longest that leaves a name winning. Shared by the server, the browser and the scanner.
20
+ */
21
+ export function normalizeName(input: string, prefixes: readonly string[], selectorPrefix = "i-"): IconName | undefined {
22
+ if (selectorPrefix !== "" && input.startsWith(selectorPrefix)) {
23
+ const rest = input.slice(selectorPrefix.length)
24
+ if (rest.includes(":")) {
25
+ const found = pair(rest)
26
+ if (found) return found
27
+ } else {
28
+ for (const prefix of [...prefixes].sort((a, b) => b.length - a.length)) {
29
+ const name = rest.slice(prefix.length + 1)
30
+ if (rest.startsWith(`${prefix}-`) && NAME_PATTERN.test(name)) return { prefix, name }
31
+ }
32
+ }
33
+ }
34
+ return pair(input)
35
+ }
36
+
37
+ /** The most icons one request may ask for. */
38
+ export const MAX_ICONS = 100
package/src/options.ts ADDED
@@ -0,0 +1,275 @@
1
+ import { isAbsolute, resolve } from "node:path"
2
+ import { NAME_PATTERN } from "./name.ts"
3
+ import type { IconDefaults, IconOptions } from "./types.ts"
4
+ import { DiagnosticError, isEnvRef } from "hamur/kit"
5
+
6
+ const OPTION_KEYS = [
7
+ "provider",
8
+ "iconifyApiEndpoint",
9
+ "fallbackToApi",
10
+ "fetchTimeout",
11
+ "serverBundle",
12
+ "clientBundle",
13
+ "customCollections",
14
+ "cssLayer",
15
+ "cssSelectorPrefix",
16
+ "cssWherePseudo",
17
+ "cssClasses",
18
+ "size",
19
+ "class",
20
+ "mode",
21
+ "aliases",
22
+ ]
23
+ const CLIENT_BUNDLE_KEYS = ["icons", "scan", "sizeLimitKb"]
24
+ const CUSTOM_KEYS = ["prefix", "dir", "recursive"]
25
+ const PROVIDERS = ["server", "iconify", "none"] as const
26
+ const SELECTOR_PREFIX = /^[a-z_][a-z0-9_-]*$/i
27
+ /** Presets that serve files only, with no endpoint to ask. */
28
+ export const FILE_PRESETS = new Set(["static", "cloudflare-static"])
29
+
30
+ export interface ResolvedIconOptions {
31
+ provider: "server" | "iconify" | "none"
32
+ iconifyApiEndpoint: string
33
+ fallbackToApi: boolean
34
+ fetchTimeout: number
35
+ /** The Iconify JSON file of each collection of the icon server bundle, by prefix. */
36
+ installed: Record<string, string>
37
+ clientBundle: { icons: string[]; scan: boolean | { include: string[]; exclude: string[] }; sizeLimitKb: number }
38
+ /** `dir` absolute. */
39
+ customCollections: Array<{ prefix: string; dir: string; recursive: boolean }>
40
+ cssLayer?: string
41
+ cssSelectorPrefix: string
42
+ cssWherePseudo: boolean
43
+ cssClasses: boolean
44
+ }
45
+
46
+ export interface OptionsContext {
47
+ rootDir: string
48
+ /** The roots of the app's layers, in priority order. */
49
+ layerRoots?: string[]
50
+ preset: string
51
+ exists(path: string): boolean
52
+ /** The prefixes of the `@iconify-json/<prefix>` packages the app's `package.json` lists. */
53
+ listed: string[]
54
+ /** The Iconify JSON file of `prefix`: `@iconify-json/<prefix>/icons.json`, or with `full` also `@iconify/json/json/<prefix>.json`. */
55
+ locate(prefix: string, full: boolean): string | undefined
56
+ }
57
+
58
+ const isObject = (value: unknown): value is Record<string, unknown> =>
59
+ typeof value === "object" && value !== null && !Array.isArray(value)
60
+ const isPlainRecord = (value: unknown): value is Record<string, unknown> =>
61
+ isObject(value) && Object.getPrototypeOf(value) === Object.prototype && !isEnvRef(value)
62
+ const shown = (value: unknown): string =>
63
+ typeof value === "function" ? "a function" : (JSON.stringify(value) ?? String(value))
64
+ const isPositiveInteger = (value: unknown): value is number =>
65
+ typeof value === "number" && Number.isInteger(value) && value > 0
66
+
67
+ function fail(message: string): never {
68
+ throw new DiagnosticError("HAMUR_E5901", message)
69
+ }
70
+
71
+ function checkKeys(input: Record<string, unknown>, allowed: string[], at: string): void {
72
+ for (const key of Object.keys(input))
73
+ if (!allowed.includes(key)) fail(`${at}.${key} is not an option; use ${allowed.join(", ")}`)
74
+ }
75
+
76
+ function checkBoolean(value: unknown, at: string): boolean {
77
+ if (typeof value !== "boolean") fail(`${at} must be a boolean (got ${shown(value)})`)
78
+ return value
79
+ }
80
+
81
+ function checkPositive(value: unknown, at: string): number {
82
+ if (!isPositiveInteger(value)) fail(`${at} must be a positive integer (got ${shown(value)})`)
83
+ return value
84
+ }
85
+
86
+ function resolveEndpoint(value: unknown): string {
87
+ let url: URL | undefined
88
+ try {
89
+ url = typeof value === "string" ? new URL(value) : undefined
90
+ } catch {}
91
+ if (!url || (url.protocol !== "http:" && url.protocol !== "https:"))
92
+ fail(`icon.iconifyApiEndpoint must be an http or https URL (got ${shown(value)})`)
93
+ return (value as string).replace(/\/+$/, "")
94
+ }
95
+
96
+ function resolveServerBundle(value: unknown, ctx: OptionsContext): Record<string, string> {
97
+ const installed: Record<string, string> = {}
98
+ if (value === false) return installed
99
+ if (value === "local") {
100
+ for (const prefix of ctx.listed) {
101
+ const file = ctx.locate(prefix, false)
102
+ if (file) installed[prefix] = file
103
+ }
104
+ return installed
105
+ }
106
+ const collections = isObject(value) ? value.collections : undefined
107
+ if (
108
+ !isObject(value) ||
109
+ Object.keys(value).some((key) => key !== "collections") ||
110
+ !Array.isArray(collections) ||
111
+ collections.some((entry) => typeof entry !== "string")
112
+ ) {
113
+ fail(`icon.serverBundle must be "local", false or { collections: string[] } (got ${shown(value)})`)
114
+ }
115
+ for (const [index, prefix] of (collections as string[]).entries()) {
116
+ const file = NAME_PATTERN.test(prefix) ? ctx.locate(prefix, true) : undefined
117
+ if (!file)
118
+ fail(
119
+ `icon.serverBundle.collections[${index}] ${shown(prefix)} is not installed; add @iconify-json/${prefix} to the app's dependencies`,
120
+ )
121
+ installed[prefix] = file
122
+ }
123
+ return installed
124
+ }
125
+
126
+ function resolveClientBundle(value: unknown): ResolvedIconOptions["clientBundle"] {
127
+ const out: ResolvedIconOptions["clientBundle"] = { icons: [], scan: true, sizeLimitKb: 256 }
128
+ if (value === undefined) return out
129
+ if (!isObject(value)) fail(`icon.clientBundle must be an object (got ${shown(value)})`)
130
+ checkKeys(value, CLIENT_BUNDLE_KEYS, "icon.clientBundle")
131
+ if (value.icons !== undefined) {
132
+ if (!Array.isArray(value.icons))
133
+ fail(`icon.clientBundle.icons must be an array of "prefix:name" (got ${shown(value.icons)})`)
134
+ for (const [index, icon] of value.icons.entries()) {
135
+ const [prefix, name, more] = typeof icon === "string" ? icon.split(":") : []
136
+ if (more !== undefined || !NAME_PATTERN.test(prefix ?? "") || !NAME_PATTERN.test(name ?? ""))
137
+ fail(`icon.clientBundle.icons[${index}] ${shown(icon)} must be "prefix:name" (got ${shown(icon)})`)
138
+ }
139
+ out.icons = [...(value.icons as string[])]
140
+ }
141
+ if (value.scan !== undefined) {
142
+ const scan = value.scan
143
+ const list = (entry: unknown) =>
144
+ entry === undefined || (Array.isArray(entry) && entry.every((item) => typeof item === "string"))
145
+ if (typeof scan === "boolean") out.scan = scan
146
+ else if (
147
+ isObject(scan) &&
148
+ Object.keys(scan).every((key) => key === "include" || key === "exclude") &&
149
+ list(scan.include) &&
150
+ list(scan.exclude)
151
+ ) {
152
+ out.scan = {
153
+ include: [...((scan.include as string[] | undefined) ?? [])],
154
+ exclude: [...((scan.exclude as string[] | undefined) ?? [])],
155
+ }
156
+ } else fail(`icon.clientBundle.scan must be a boolean or { include?, exclude? } (got ${shown(scan)})`)
157
+ }
158
+ if (value.sizeLimitKb !== undefined)
159
+ out.sizeLimitKb = checkPositive(value.sizeLimitKb, "icon.clientBundle.sizeLimitKb")
160
+ return out
161
+ }
162
+
163
+ function resolveCustomCollections(
164
+ value: unknown,
165
+ installed: Record<string, string>,
166
+ ctx: OptionsContext,
167
+ ): ResolvedIconOptions["customCollections"] {
168
+ if (value === undefined) return []
169
+ if (!Array.isArray(value))
170
+ fail(`icon.customCollections must be an array of { prefix, dir, recursive? } (got ${shown(value)})`)
171
+ const out: ResolvedIconOptions["customCollections"] = []
172
+ for (const [index, entry] of value.entries()) {
173
+ const at = `icon.customCollections[${index}]`
174
+ if (!isObject(entry)) fail(`${at} must be { prefix, dir, recursive? } (got ${shown(entry)})`)
175
+ checkKeys(entry, CUSTOM_KEYS, at)
176
+ const { prefix, dir } = entry
177
+ if (typeof prefix !== "string" || !NAME_PATTERN.test(prefix))
178
+ fail(`${at}.prefix ${shown(prefix)} must match ${NAME_PATTERN}`)
179
+ if (typeof dir !== "string" || dir === "") fail(`${at}.dir must be a non-empty string (got ${shown(dir)})`)
180
+ const path = isAbsolute(dir)
181
+ ? dir
182
+ : ([ctx.rootDir, ...(ctx.layerRoots ?? [])]
183
+ .map((root) => resolve(root, dir))
184
+ .find((candidate) => ctx.exists(candidate)) ?? resolve(ctx.rootDir, dir))
185
+ if (!ctx.exists(path)) fail(`${at}.dir ${shown(dir)} does not exist`)
186
+ if (Object.hasOwn(installed, prefix)) fail(`${at}.prefix ${shown(prefix)} is already an installed collection`)
187
+ if (out.some((seen) => seen.prefix === prefix)) fail(`${at}.prefix ${shown(prefix)} is used twice`)
188
+ out.push({
189
+ prefix,
190
+ dir: path,
191
+ recursive: entry.recursive === undefined ? false : checkBoolean(entry.recursive, `${at}.recursive`),
192
+ })
193
+ }
194
+ return out
195
+ }
196
+
197
+ /** The keys of `icon` that `Icon` reads at render, checked; only the ones set. */
198
+ export function iconDefaults(input: IconOptions | undefined): IconDefaults {
199
+ const raw: Record<string, unknown> = isObject(input) ? input : {}
200
+ const out: IconDefaults = {}
201
+ if (raw.size !== undefined) {
202
+ if (typeof raw.size !== "string" && !(typeof raw.size === "number" && raw.size > 0))
203
+ fail(`icon.size must be a string or a positive number (got ${shown(raw.size)})`)
204
+ out.size = raw.size
205
+ }
206
+ if (raw.class !== undefined) {
207
+ if (typeof raw.class !== "string") fail(`icon.class must be a string (got ${shown(raw.class)})`)
208
+ out.class = raw.class
209
+ }
210
+ if (raw.mode !== undefined) {
211
+ if (raw.mode !== "svg" && raw.mode !== "css") fail(`icon.mode ${shown(raw.mode)} is not "svg" or "css"`)
212
+ out.mode = raw.mode
213
+ }
214
+ if (raw.aliases !== undefined) {
215
+ const aliases = raw.aliases
216
+ if (!isObject(aliases) || !Object.values(aliases).every((target) => typeof target === "string"))
217
+ fail(`icon.aliases must be an object of strings (got ${shown(aliases)})`)
218
+ out.aliases = { ...(aliases as Record<string, string>) }
219
+ }
220
+ return out
221
+ }
222
+
223
+ /** The part of `defaults` the app's own `runtimeConfig.public.icon` does not set, per key and per alias, so the app wins. */
224
+ export function iconDefaultsUnder(defaults: IconDefaults, app: unknown): IconDefaults {
225
+ const own: Record<string, unknown> = isObject(app) ? app : {}
226
+ const out: Record<string, unknown> = {}
227
+ for (const [key, value] of Object.entries(defaults)) {
228
+ const set = own[key]
229
+ if (key === "aliases" && isPlainRecord(set)) {
230
+ const aliases = Object.fromEntries(
231
+ Object.entries(value as Record<string, string>).filter(([name]) => set[name] === undefined),
232
+ )
233
+ if (Object.keys(aliases).length) out.aliases = aliases
234
+ } else if (set === undefined) out[key] = value
235
+ }
236
+ return out as IconDefaults
237
+ }
238
+
239
+ /** `icon` of `hamur.config.ts` checked and merged over the defaults; every load error names its key. */
240
+ export function resolveOptions(input: IconOptions | undefined, ctx: OptionsContext): ResolvedIconOptions {
241
+ const raw: unknown = input ?? {}
242
+ if (!isObject(raw)) fail(`icon must be an object (got ${shown(raw)})`)
243
+ checkKeys(raw, OPTION_KEYS, "icon")
244
+ let provider: ResolvedIconOptions["provider"] = FILE_PRESETS.has(ctx.preset) ? "none" : "server"
245
+ if (raw.provider !== undefined) {
246
+ if (!PROVIDERS.includes(raw.provider as never))
247
+ fail(`icon.provider ${shown(raw.provider)} is not "server", "iconify" or "none"`)
248
+ provider = raw.provider as ResolvedIconOptions["provider"]
249
+ }
250
+ const installed = resolveServerBundle(raw.serverBundle ?? "local", ctx)
251
+ const out: ResolvedIconOptions = {
252
+ provider,
253
+ iconifyApiEndpoint:
254
+ raw.iconifyApiEndpoint === undefined ? "https://api.iconify.design" : resolveEndpoint(raw.iconifyApiEndpoint),
255
+ fallbackToApi: raw.fallbackToApi === undefined ? false : checkBoolean(raw.fallbackToApi, "icon.fallbackToApi"),
256
+ fetchTimeout: raw.fetchTimeout === undefined ? 1500 : checkPositive(raw.fetchTimeout, "icon.fetchTimeout"),
257
+ installed,
258
+ clientBundle: resolveClientBundle(raw.clientBundle),
259
+ customCollections: resolveCustomCollections(raw.customCollections, installed, ctx),
260
+ cssSelectorPrefix: "i-",
261
+ cssWherePseudo: raw.cssWherePseudo === undefined ? true : checkBoolean(raw.cssWherePseudo, "icon.cssWherePseudo"),
262
+ cssClasses: raw.cssClasses === undefined ? false : checkBoolean(raw.cssClasses, "icon.cssClasses"),
263
+ }
264
+ if (raw.cssSelectorPrefix !== undefined) {
265
+ if (typeof raw.cssSelectorPrefix !== "string" || !SELECTOR_PREFIX.test(raw.cssSelectorPrefix))
266
+ fail(`icon.cssSelectorPrefix ${shown(raw.cssSelectorPrefix)} must match ${SELECTOR_PREFIX}`)
267
+ out.cssSelectorPrefix = raw.cssSelectorPrefix
268
+ }
269
+ if (raw.cssLayer !== undefined) {
270
+ if (typeof raw.cssLayer !== "string" || raw.cssLayer === "")
271
+ fail(`icon.cssLayer must be a non-empty string (got ${shown(raw.cssLayer)})`)
272
+ out.cssLayer = raw.cssLayer
273
+ }
274
+ return out
275
+ }