@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,251 @@
1
+ import { cleanCollection } from "../clean.ts"
2
+ import { MAX_ICONS, NAME_PATTERN } from "../name.ts"
3
+ import { resolveIcon, type IconData } from "../render.ts"
4
+ import type { IconifyIcon, IconifyJSON } from "../types.ts"
5
+
6
+ export { MAX_ICONS }
7
+
8
+ const PATH_MARK = "/_hamur/icons/"
9
+ const FILE = /^([a-z0-9]+(?:-[a-z0-9]+)*)\.json$/
10
+ const HEADERS = { "content-type": "application/json", "x-content-type-options": "nosniff" }
11
+
12
+ export interface IconEndpointFallback {
13
+ iconifyApiEndpoint: string
14
+ fetchTimeout: number
15
+ fetch?: typeof fetch
16
+ warn?: (message: string) => void
17
+ /** Icons kept from upstream answers, hits and misses; default 1000. */
18
+ cacheSize?: number
19
+ /** Milliseconds an upstream answer is kept; default one hour. */
20
+ cacheTtl?: number
21
+ /** Outgoing requests at once; above it the bundle's icons are answered alone. Default 4. */
22
+ maxConcurrent?: number
23
+ now?: () => number
24
+ }
25
+
26
+ export interface IconEndpointEnvironment {
27
+ /** `hamur dev` answers `cache-control: no-cache`. */
28
+ dev: boolean
29
+ collection(prefix: string): IconifyJSON | undefined
30
+ /** Set when `icon.fallbackToApi` is on. */
31
+ fallback?: IconEndpointFallback
32
+ }
33
+
34
+ const shown = (text: string): string => (text.length > 64 ? `${text.slice(0, 64)}…` : text)
35
+ const isObject = (value: unknown): value is Record<string, unknown> =>
36
+ typeof value === "object" && value !== null && !Array.isArray(value)
37
+
38
+ function fail(status: number, error: string): Response {
39
+ return new Response(JSON.stringify({ error }), { status, headers: HEADERS })
40
+ }
41
+
42
+ const iconOf = (data: IconData): IconifyIcon => ({
43
+ body: data.body,
44
+ width: data.width,
45
+ height: data.height,
46
+ ...(data.left ? { left: data.left } : {}),
47
+ ...(data.top ? { top: data.top } : {}),
48
+ })
49
+
50
+ async function etag(text: string): Promise<string> {
51
+ const digest = new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(text)))
52
+ return `"${Array.from(digest.subarray(0, 8), (byte) => byte.toString(16).padStart(2, "0")).join("")}"`
53
+ }
54
+
55
+ class TimedOut extends Error {}
56
+
57
+ const MAX_UPSTREAM_BYTES = 1024 * 1024
58
+ async function readLimited(response: Response, signal: AbortSignal): Promise<string | undefined> {
59
+ const length = Number(response.headers.get("content-length"))
60
+ if (Number.isFinite(length) && length > MAX_UPSTREAM_BYTES) return undefined
61
+ if (!response.body) return undefined
62
+ const reader = response.body.getReader()
63
+ signal.addEventListener("abort", () => void reader.cancel().catch(() => {}), { once: true })
64
+ const chunks: Uint8Array[] = []
65
+ let total = 0
66
+ for (;;) {
67
+ const { done, value } = await reader.read()
68
+ if (done) break
69
+ total += value.byteLength
70
+ if (total > MAX_UPSTREAM_BYTES) {
71
+ await reader.cancel().catch(() => {})
72
+ return undefined
73
+ }
74
+ chunks.push(value)
75
+ }
76
+ const bytes = new Uint8Array(total)
77
+ let at = 0
78
+ for (const chunk of chunks) {
79
+ bytes.set(chunk, at)
80
+ at += chunk.length
81
+ }
82
+ return new TextDecoder().decode(bytes)
83
+ }
84
+
85
+ /** `undefined` is a failed ask: an error status, a body that is not JSON of the right size and type, or a network error. */
86
+ async function askApi(
87
+ fallback: IconEndpointFallback,
88
+ prefix: string,
89
+ names: string[],
90
+ ): Promise<IconifyJSON | undefined> {
91
+ const url = new URL(`${fallback.iconifyApiEndpoint.replace(/\/+$/, "")}/${prefix}.json`)
92
+ url.searchParams.set("icons", names.join(","))
93
+ const controller = new AbortController()
94
+ let timer: ReturnType<typeof setTimeout> | undefined
95
+ const timeout = new Promise<never>((_, reject) => {
96
+ timer = setTimeout(() => {
97
+ controller.abort()
98
+ reject(new TimedOut())
99
+ }, fallback.fetchTimeout)
100
+ })
101
+ const ask = async (): Promise<IconifyJSON | undefined> => {
102
+ const response = await (fallback.fetch ?? fetch)(url, {
103
+ signal: controller.signal,
104
+ headers: { accept: "application/json" },
105
+ })
106
+ if (!response.ok || !/\bjson\b/i.test(response.headers.get("content-type") ?? "")) return undefined
107
+ const text = await readLimited(response, controller.signal)
108
+ if (text === undefined) return undefined
109
+ const body: unknown = JSON.parse(text)
110
+ return isObject(body) && isObject(body.icons) ? cleanCollection(prefix, body) : undefined
111
+ }
112
+ try {
113
+ return await Promise.race([ask(), timeout])
114
+ } catch (error) {
115
+ if (error instanceof TimedOut) throw error
116
+ fallback.warn?.(
117
+ `[icon] the Iconify API did not answer for ${prefix}: ${error instanceof Error ? error.message : String(error)}`,
118
+ )
119
+ return undefined
120
+ } finally {
121
+ clearTimeout(timer)
122
+ }
123
+ }
124
+
125
+ type Upstream = { icons: Record<string, IconifyIcon | null> } | undefined
126
+
127
+ /**
128
+ * `GET /_hamur/icons/<prefix>.json?icons=a,b` in the Iconify API's shape. The prefix and every name are checked against
129
+ * `NAME_PATTERN` before they are looked up or put in an outgoing URL; the endpoint reads no file the request names.
130
+ */
131
+ export function createIconEndpoint(env: IconEndpointEnvironment): (request: Request) => Promise<Response> {
132
+ const fallback = env.fallback
133
+ const now = fallback?.now ?? Date.now
134
+ const known = new Map<string, { icon: IconifyIcon | null; at: number }>()
135
+ const inflight = new Map<string, Promise<Upstream>>()
136
+ let active = 0
137
+
138
+ const remember = (key: string, icon: IconifyIcon | null) => {
139
+ known.delete(key)
140
+ known.set(key, { icon, at: now() })
141
+ while (known.size > (fallback?.cacheSize ?? 1000)) known.delete(known.keys().next().value!)
142
+ }
143
+
144
+ /** Icons of `names` from the cache and the Iconify API; `undefined` is a failed ask (nothing is kept). */
145
+ async function upstream(prefix: string, names: string[]): Promise<Upstream> {
146
+ const icons: Record<string, IconifyIcon | null> = {}
147
+ const unknown: string[] = []
148
+ for (const name of names) {
149
+ const entry = known.get(`${prefix}:${name}`)
150
+ if (entry && now() - entry.at < (fallback!.cacheTtl ?? 3_600_000)) icons[name] = entry.icon
151
+ else unknown.push(name)
152
+ }
153
+ if (unknown.length === 0) return { icons }
154
+ const key = `${prefix}?${[...unknown].sort().join(",")}`
155
+ let pending = inflight.get(key)
156
+ if (!pending) {
157
+ if (active >= (fallback!.maxConcurrent ?? 4)) return undefined
158
+ active++
159
+ pending = askApi(fallback!, prefix, unknown)
160
+ .then((remote): Upstream => {
161
+ if (!remote) return undefined
162
+ const fresh: Record<string, IconifyIcon | null> = {}
163
+ for (const name of unknown) {
164
+ const data = resolveIcon(remote, name)
165
+ fresh[name] = data ? iconOf(data) : null
166
+ remember(`${prefix}:${name}`, fresh[name])
167
+ }
168
+ return { icons: fresh }
169
+ })
170
+ .finally(() => {
171
+ active--
172
+ inflight.delete(key)
173
+ })
174
+ inflight.set(key, pending)
175
+ }
176
+ const fresh = await pending
177
+ return fresh && { icons: { ...icons, ...fresh.icons } }
178
+ }
179
+
180
+ return async (request) => {
181
+ if (request.method !== "GET" && request.method !== "HEAD")
182
+ return new Response(JSON.stringify({ error: "method not allowed" }), {
183
+ status: 405,
184
+ headers: { ...HEADERS, allow: "GET, HEAD" },
185
+ })
186
+ const url = new URL(request.url)
187
+ const at = url.pathname.indexOf(PATH_MARK)
188
+ const file = at === -1 ? "" : url.pathname.slice(at + PATH_MARK.length)
189
+ const prefix = FILE.exec(file)?.[1]
190
+ if (!prefix) return fail(404, `collection ${shown(file.replace(/\.json$/, ""))} not found`)
191
+
192
+ const raw = url.searchParams.get("icons")
193
+ if (!raw) return fail(400, "icons query is required")
194
+ const listed = raw.split(",")
195
+ if (listed.length > MAX_ICONS) return fail(400, `icons lists ${listed.length} names; at most ${MAX_ICONS}`)
196
+ for (const name of listed)
197
+ if (!NAME_PATTERN.test(name))
198
+ return fail(400, `icon name ${JSON.stringify(shown(name))} must match ${NAME_PATTERN}`)
199
+ const asked = [...new Set(listed)]
200
+
201
+ const collection = env.collection(prefix)
202
+ const found: Record<string, IconifyIcon> = {}
203
+ let missing: string[] = []
204
+ for (const name of asked) {
205
+ const data = collection && resolveIcon(collection, name)
206
+ if (data) found[name] = iconOf(data)
207
+ else missing.push(name)
208
+ }
209
+
210
+ let answered = true
211
+ let remote: Upstream
212
+ if (missing.length > 0 && fallback) {
213
+ try {
214
+ remote = await upstream(prefix, missing)
215
+ } catch (error) {
216
+ if (error instanceof TimedOut) return fail(504, `iconify api timed out after ${fallback.fetchTimeout} ms`)
217
+ throw error
218
+ }
219
+ answered = remote !== undefined
220
+ if (remote) {
221
+ const stillMissing: string[] = []
222
+ for (const name of missing) {
223
+ const icon = remote.icons[name]
224
+ if (icon) found[name] = icon
225
+ else stillMissing.push(name)
226
+ }
227
+ missing = stillMissing
228
+ }
229
+ }
230
+
231
+ if (Object.keys(found).length === 0) {
232
+ if (!collection && !remote) return fail(404, `collection ${prefix} not found`)
233
+ return fail(
234
+ 404,
235
+ missing.length === 1
236
+ ? `icon ${prefix}:${missing[0]} not found`
237
+ : `icons ${missing.map((name) => `${prefix}:${name}`).join(", ")} not found`,
238
+ )
239
+ }
240
+
241
+ const text = JSON.stringify({ prefix, icons: found, ...(missing.length > 0 ? { not_found: missing } : {}) })
242
+ const tag = await etag(text)
243
+ const headers = {
244
+ ...HEADERS,
245
+ "cache-control": !answered ? "no-store" : env.dev ? "no-cache" : "public, max-age=604800",
246
+ etag: tag,
247
+ }
248
+ if (request.headers.get("if-none-match") === tag) return new Response(null, { status: 304, headers })
249
+ return new Response(request.method === "HEAD" ? null : text, { status: 200, headers })
250
+ }
251
+ }
@@ -0,0 +1,30 @@
1
+ /// <reference path="../env.d.ts" />
2
+ import endpoint from "#hamur/icon/endpoint"
3
+ import { defineHandler, useLogger } from "hamur/server"
4
+ import { loadServerCollections } from "../runtime/bundle.ts"
5
+ import { getServerCollection } from "../runtime/icons.ts"
6
+ import { createIconEndpoint } from "./endpoint.ts"
7
+
8
+ const answer = createIconEndpoint({
9
+ dev: endpoint.dev,
10
+ collection: getServerCollection,
11
+ ...(endpoint.fallbackToApi
12
+ ? {
13
+ fallback: {
14
+ iconifyApiEndpoint: endpoint.iconifyApiEndpoint,
15
+ fetchTimeout: endpoint.fetchTimeout,
16
+ warn: (message: string) => useLogger().warn(message),
17
+ },
18
+ }
19
+ : {}),
20
+ })
21
+
22
+ export const iconEndpoint = defineHandler({
23
+ route: "/_hamur/icons/**:path",
24
+ method: "*",
25
+ raw: true,
26
+ async handler(_, { event }) {
27
+ await loadServerCollections()
28
+ return answer(event.request)
29
+ },
30
+ })
package/src/testing.ts ADDED
@@ -0,0 +1,23 @@
1
+ import { readFileSync } from "node:fs"
2
+ import { collectionCandidates, locateCollection } from "./locate.ts"
3
+ import { NAME_PATTERN } from "./name.ts"
4
+ import { addServerCollection } from "./runtime/icons.ts"
5
+ import type { IconifyJSON } from "./types.ts"
6
+
7
+ /** Reads the installed collections into the registry a server render reads, as the server plugin does at start. */
8
+ export function loadIconCollections(prefixes: string[]): void {
9
+ const rootDir = process.cwd()
10
+ for (const prefix of prefixes) {
11
+ if (!NAME_PATTERN.test(prefix)) throw new Error(`loadIconCollections: "${prefix}" is not a collection prefix`)
12
+ const file = locateCollection(rootDir, prefix, true)
13
+ if (!file) {
14
+ const looked = collectionCandidates(prefix, true)
15
+ .map((candidate) => `node_modules/${candidate}`)
16
+ .join(" or ")
17
+ throw new Error(
18
+ `loadIconCollections: collection "${prefix}" is not installed; looked for ${looked} from ${rootDir} up. Add @iconify-json/${prefix} to the app's devDependencies`,
19
+ )
20
+ }
21
+ addServerCollection(prefix, JSON.parse(readFileSync(file, "utf8")) as IconifyJSON)
22
+ }
23
+ }
package/src/types.ts ADDED
@@ -0,0 +1,97 @@
1
+ /** One icon of the Iconify JSON format; `width` and `height` default to the collection's, then 16. */
2
+ export interface IconifyIcon {
3
+ body: string
4
+ width?: number
5
+ height?: number
6
+ left?: number
7
+ top?: number
8
+ /** Quarter turns clockwise. */
9
+ rotate?: number
10
+ hFlip?: boolean
11
+ vFlip?: boolean
12
+ hidden?: boolean
13
+ }
14
+
15
+ /** An alias: another icon of the collection by name, with its own size or transformation over the parent's. */
16
+ export interface IconifyAlias extends Omit<Partial<IconifyIcon>, "body"> {
17
+ parent: string
18
+ }
19
+
20
+ /** The Iconify JSON format of `@iconify-json/<prefix>/icons.json`, read with no Iconify package. */
21
+ export interface IconifyJSON {
22
+ prefix: string
23
+ icons: Record<string, IconifyIcon>
24
+ aliases?: Record<string, IconifyAlias>
25
+ width?: number
26
+ height?: number
27
+ left?: number
28
+ top?: number
29
+ not_found?: string[]
30
+ }
31
+
32
+ export type IconMode = "svg" | "css"
33
+
34
+ export type IconCustomize = (content: string, name: string, prefix: string) => string
35
+
36
+ /** The props every adapter's `Icon` takes; every other attribute goes on the `<svg>` or the `<span>`. */
37
+ export interface IconProps {
38
+ /** `"mdi:home"`, `"i-mdi-home"` or `"i-mdi:home"`. */
39
+ name: string
40
+ /** Default `"1em"`; a number is CSS pixels. */
41
+ size?: string | number
42
+ /** Default `"svg"`. */
43
+ mode?: IconMode
44
+ /** The icon's accessible name; without it the icon is decorative. */
45
+ title?: string
46
+ /** Receives the icon's body and returns the one drawn. */
47
+ customize?: IconCustomize
48
+ }
49
+
50
+ /** The keys of `icon` that `Icon` reads at render, sent as `runtimeConfig.public.icon`. */
51
+ export interface IconDefaults {
52
+ size?: string | number
53
+ class?: string
54
+ mode?: IconMode
55
+ aliases?: Record<string, string>
56
+ }
57
+
58
+ /** `icon` in `hamur.config.ts`. */
59
+ export interface IconOptions extends IconDefaults {
60
+ provider?: "server" | "iconify" | "none"
61
+ iconifyApiEndpoint?: string
62
+ fallbackToApi?: boolean
63
+ fetchTimeout?: number
64
+ serverBundle?: "local" | false | { collections: string[] }
65
+ clientBundle?: { icons?: string[]; scan?: boolean | { include?: string[]; exclude?: string[] }; sizeLimitKb?: number }
66
+ customCollections?: Array<{ prefix: string; dir: string; recursive?: boolean }>
67
+ cssLayer?: string
68
+ cssSelectorPrefix?: string
69
+ cssWherePseudo?: boolean
70
+ cssClasses?: boolean
71
+ }
72
+
73
+ /** `#hamur/icon/options`: what the render reads. */
74
+ export interface IconRuntimeOptions {
75
+ /** Every prefix the build knows, longest first, so the `i-` form finds the longest that leaves a name. */
76
+ prefixes: string[]
77
+ /** The prefixes of the icon server bundle, each `<prefix>.json` of `useStorage("assets:icons")`. */
78
+ serverBundle: string[]
79
+ /** Where the browser asks for an icon the payload and the client bundle lack. */
80
+ provider: "server" | "iconify" | "none"
81
+ iconifyApiEndpoint: string
82
+ fetchTimeout: number
83
+ cssLayer?: string
84
+ cssSelectorPrefix: string
85
+ cssWherePseudo: boolean
86
+ }
87
+
88
+ /** `app.modulePayload.icon`, the icons a server render used, by prefix, in the Iconify JSON shape. */
89
+ export type IconPayload = Record<string, { icons: Record<string, IconifyIcon> }>
90
+
91
+ /** `#hamur/icon/endpoint`: what the endpoint reads. */
92
+ export interface IconEndpointOptions {
93
+ dev: boolean
94
+ fallbackToApi: boolean
95
+ iconifyApiEndpoint: string
96
+ fetchTimeout: number
97
+ }