@splendidlabz/svelte 4.17.1 → 4.18.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
@@ -39,6 +39,41 @@ In Astro, hydrate interactive components with `client:load`. Props that take a f
39
39
 
40
40
  Actions and utilities have their own entry points: `@splendidlabz/svelte/actions` and `@splendidlabz/svelte/utils`.
41
41
 
42
+ ## Icons
43
+
44
+ `splendidSvelte()` bundles the icons a site uses at build time. `Icon` then draws them in the server's HTML, with no request to Iconify from the browser. You don't install any icon sets.
45
+
46
+ ```js
47
+ // astro.config.js
48
+ import svelte from '@astrojs/svelte'
49
+ import { splendidSvelte } from '@splendidlabz/svelte/astro'
50
+ import { defineConfig } from 'astro/config'
51
+
52
+ export default defineConfig({
53
+ integrations: [svelte(), splendidSvelte()],
54
+ })
55
+ ```
56
+
57
+ The integration scans `src/` for icon names like `tabler:home`, fetches those icons from Iconify's API, and saves them in `src/icons.json`.
58
+
59
+ - `src/icons.json` appears the first time you run `astro dev` or `astro build`. Commit it. Builds then read from it and make no request.
60
+ - `astro dev` adds a new icon to the file as soon as you save the file that uses it. A build fetches any icon the file lacks.
61
+ - The default icons of Splendid's own components, like Accordion's `tabler:chevron-right`, are saved too.
62
+ - A name Iconify doesn't have is saved as `null`, so it isn't requested again.
63
+ - Icons whose names are built at runtime, like `` `simple-icons:${platform}` ``, are saved as they show up on a page in `astro dev`. The first time, they load from Iconify. They're listed under `captured` in `src/icons.json`.
64
+ - An icon leaves the file once your code no longer names it, except a `captured` icon, which stays until you delete it from the file.
65
+ - Because dev saves runtime icons, you rarely need `icons.names`. Use it for a runtime icon you want bundled before it shows up in dev:
66
+
67
+ ```js
68
+ splendidSvelte({ icons: { names: ['simple-icons:github'] } })
69
+ ```
70
+
71
+ - When Iconify can't be reached, the build still runs. It logs a warning, and the icons it couldn't fetch load in the browser.
72
+ - An icon that isn't bundled renders empty, then fills in at mount from Iconify's cache or its API.
73
+ - `icons: false` turns bundling off and writes no file.
74
+
75
+ Every island that renders an `Icon` loads the whole bundle, from one chunk the islands share. 84 icons come to about 35 kB raw, 10 kB gzipped.
76
+
42
77
  ## Docs
43
78
 
44
79
  https://splendidlabz.com/docs/svelte
@@ -0,0 +1,342 @@
1
+ /**
2
+ * @file Bundles the Iconify icons a site names.
3
+ */
4
+
5
+ import { existsSync, readdirSync, readFileSync } from 'node:fs'
6
+ import { readFile, writeFile } from 'node:fs/promises'
7
+ import { createRequire } from 'node:module'
8
+ import { dirname, join, sep } from 'node:path'
9
+ import { getIconData } from '@iconify/utils/lib/icon-set/get-icon'
10
+ import { defaultIconDimensions } from '@iconify/utils/lib/icon/defaults'
11
+ import zlFetch from 'zl-fetch'
12
+
13
+ /**
14
+ * @import { AstroIntegrationLogger } from 'astro'
15
+ * @import { IconifyJSON } from '@iconify/types'
16
+ * @import { Plugin } from './unbarrel.js'
17
+ */
18
+
19
+ /**
20
+ * bundleIcons
21
+ * Serves the icons a site uses as `@splendidlabz/svelte/bundled-icons`.
22
+ *
23
+ * @typedef {{ body: string, width: number, height: number }} BundledIcon
24
+ * @typedef {Record<string, BundledIcon | null>} CachedIcons Null when Iconify has no such icon.
25
+ * @typedef {{ captured: string[], icons: CachedIcons }} IconCache `captured` lists names Icon loaded at runtime in dev.
26
+ *
27
+ * @param {object} opts
28
+ * @param {string} opts.root The site's root folder.
29
+ * @param {string} opts.srcDir Folder scanned for icon names.
30
+ * @param {string[]} [opts.names] Names the source doesn't spell out.
31
+ * @param {Pick<AstroIntegrationLogger, 'warn'>} opts.logger
32
+ * @returns {Plugin}
33
+ */
34
+ export function bundleIcons(opts) {
35
+ const { root, srcDir, names = [], logger } = opts
36
+ const id = '@splendidlabz/svelte/bundled-icons'
37
+ const resolvedId = '\0splendid:bundled-icons'
38
+ const cacheFile = join(srcDir, 'icons.json')
39
+ const prefixes = getSetPrefixes()
40
+ const namesByFile = scanFolder({ folder: srcDir, prefixes })
41
+ const componentNames = getComponentNames({ root, prefixes })
42
+ const capturedNames = new Set()
43
+ /** @type {Promise<IconCache> | undefined} */
44
+ let cacheUpdate
45
+
46
+ // Leaves out the cache, whose keys would count as used names
47
+ namesByFile.delete(cacheFile)
48
+
49
+ return {
50
+ name: 'splendid:bundle-icons',
51
+ // Runs ahead of Vite's resolver, which would find the empty file
52
+ enforce: 'pre',
53
+ // Keeps the bundle out of dev prebundles, so the browser gets the server's icons
54
+ config() {
55
+ return { optimizeDeps: { exclude: [id] } }
56
+ },
57
+ resolveId(source) {
58
+ if (source === id) return resolvedId
59
+ },
60
+ async load(source) {
61
+ if (source !== resolvedId) return
62
+
63
+ // Serves the cached icons, leaving out names Iconify doesn't have
64
+ const cache = await getCache()
65
+ const icons = Object.fromEntries(
66
+ Object.entries(cache.icons).filter(([, icon]) => icon),
67
+ )
68
+ return `export const bundledIcons = ${JSON.stringify(icons)}`
69
+ },
70
+ configureServer(server) {
71
+ // Fills the cache as dev starts, before a page asks for it
72
+ getCache()
73
+
74
+ server.watcher.on('all', async (event, file) => {
75
+ // Skips the cache, files outside srcDir and files that can't name an icon
76
+ if (file === cacheFile) return
77
+ if (!file.startsWith(join(srcDir, sep)) || !isSourceFile(file)) return
78
+
79
+ // Rescans the file that changed
80
+ const previous = namesByFile.get(file) ?? []
81
+ if (event === 'unlink') namesByFile.delete(file)
82
+ if (event === 'add' || event === 'change') {
83
+ const code = readFileSync(file, 'utf8')
84
+ namesByFile.set(file, getIconNames({ code, prefixes }))
85
+ }
86
+
87
+ const current = namesByFile.get(file) ?? []
88
+ if (current.join() === previous.join()) return
89
+
90
+ // Fetches new names into the cache, after any update in flight
91
+ cacheUpdate = getCache().then(updateCache)
92
+ await cacheUpdate
93
+
94
+ // Rebuilds the bundle and reloads the page
95
+ for (const environment of Object.values(server.environments)) {
96
+ const module = environment.moduleGraph.getModuleById(resolvedId)
97
+ if (module) environment.moduleGraph.invalidateModule(module)
98
+ }
99
+ server.ws.send({ type: 'full-reload' })
100
+ })
101
+
102
+ // Caches an icon Icon loaded at runtime, for the next page load
103
+ server.ws.on('splendid:icon', async ({ name }) => {
104
+ const isIconName = getIconNames({ code: name, prefixes })[0] === name
105
+ if (!isIconName || capturedNames.has(name)) return
106
+ if (getScannedNames().has(name)) return
107
+
108
+ capturedNames.add(name)
109
+ cacheUpdate = getCache().then(updateCache)
110
+ await cacheUpdate
111
+
112
+ // Rebuilds the bundle on the next request
113
+ for (const environment of Object.values(server.environments)) {
114
+ const module = environment.moduleGraph.getModuleById(resolvedId)
115
+ if (module) environment.moduleGraph.invalidateModule(module)
116
+ }
117
+ })
118
+ },
119
+ }
120
+
121
+ /**
122
+ * getCache
123
+ * Returns the cache, updating it on the first call.
124
+ *
125
+ * @returns {Promise<IconCache>}
126
+ */
127
+ function getCache() {
128
+ if (!cacheUpdate) cacheUpdate = updateCache()
129
+ return cacheUpdate
130
+ }
131
+
132
+ /**
133
+ * getScannedNames
134
+ * Lists the names the source, `names` and Splendid's components use.
135
+ *
136
+ * @returns {Set<string>}
137
+ */
138
+ function getScannedNames() {
139
+ return new Set([
140
+ ...names,
141
+ ...[...namesByFile.values()].flat(),
142
+ ...componentNames,
143
+ ])
144
+ }
145
+
146
+ /**
147
+ * updateCache
148
+ * Fetches the used icons the cache lacks, and drops unused ones.
149
+ *
150
+ * @returns {Promise<IconCache>}
151
+ */
152
+ async function updateCache() {
153
+ /** @type {IconCache} */
154
+ const cache = existsSync(cacheFile)
155
+ ? JSON.parse(await readFile(cacheFile, 'utf8'))
156
+ : { captured: [], icons: {} }
157
+
158
+ // Keeps captured names until they're removed from the file by hand
159
+ const captured = [...new Set([...cache.captured, ...capturedNames])].sort()
160
+ const usedNames = new Set([...getScannedNames(), ...captured])
161
+
162
+ // Fetches the missing names, which stay missing when Iconify can't be reached
163
+ const missingNames = [...usedNames].filter(name => !(name in cache.icons))
164
+ const { icons, failedNames } = await fetchIcons(missingNames)
165
+ if (failedNames.length) {
166
+ logger.warn(
167
+ `Couldn't fetch ${failedNames.length} icons from Iconify. They load in the browser instead.`,
168
+ )
169
+ }
170
+
171
+ const unusedNames = Object.keys(cache.icons).filter(
172
+ name => !usedNames.has(name),
173
+ )
174
+ const isUnchanged =
175
+ !Object.keys(icons).length &&
176
+ !unusedNames.length &&
177
+ captured.length === cache.captured.length
178
+ if (isUnchanged) return cache
179
+
180
+ // Writes the used names, sorted so the file diffs cleanly
181
+ const nextCache = {
182
+ captured,
183
+ icons: Object.fromEntries(
184
+ Object.entries({ ...cache.icons, ...icons })
185
+ .filter(([name]) => usedNames.has(name))
186
+ .sort(([a], [b]) => a.localeCompare(b)),
187
+ ),
188
+ }
189
+ await writeFile(cacheFile, `${JSON.stringify(nextCache, null, 2)}\n`)
190
+ return nextCache
191
+ }
192
+ }
193
+
194
+ /**
195
+ * getIconNames
196
+ * Lists the `prefix:name` icons a file's text mentions.
197
+ *
198
+ * @param {object} opts
199
+ * @param {string} opts.code
200
+ * @param {Set<string>} opts.prefixes Iconify set prefixes.
201
+ * @returns {string[]}
202
+ */
203
+ export function getIconNames({ code, prefixes }) {
204
+ const matches = code.matchAll(
205
+ /(?<![\w:-])([a-z0-9]+(?:-[a-z0-9]+)*):[a-z0-9]+(?:-[a-z0-9]+)*(?![\w:-])/g,
206
+ )
207
+ const names = [...matches]
208
+ .filter(([, prefix]) => prefixes.has(prefix))
209
+ .map(([name]) => name)
210
+
211
+ return [...new Set(names)]
212
+ }
213
+
214
+ /**
215
+ * getSetPrefixes
216
+ * Lists the prefix of every Iconify icon set.
217
+ *
218
+ * @returns {Set<string>}
219
+ */
220
+ function getSetPrefixes() {
221
+ const require = createRequire(import.meta.url)
222
+ return new Set(Object.keys(require('@iconify/collections/collections.json')))
223
+ }
224
+
225
+ /**
226
+ * scanFolder
227
+ * Lists the icon names in each source file under a folder.
228
+ *
229
+ * @param {object} opts
230
+ * @param {string} opts.folder
231
+ * @param {Set<string>} opts.prefixes
232
+ * @returns {Map<string, string[]>} File to icon names.
233
+ */
234
+ function scanFolder({ folder, prefixes }) {
235
+ const files = readdirSync(folder, { recursive: true, encoding: 'utf8' })
236
+ .map(file => join(folder, file))
237
+ .filter(isSourceFile)
238
+
239
+ return new Map(
240
+ files.map(file => [
241
+ file,
242
+ getIconNames({ code: readFileSync(file, 'utf8'), prefixes }),
243
+ ]),
244
+ )
245
+ }
246
+
247
+ /**
248
+ * getComponentNames
249
+ * Lists the default icons Splendid's own components use.
250
+ *
251
+ * @param {object} opts
252
+ * @param {string} opts.root The site's root folder.
253
+ * @param {Set<string>} opts.prefixes
254
+ * @returns {string[]}
255
+ */
256
+ function getComponentNames({ root, prefixes }) {
257
+ // Finds the components folder of the package the site installed
258
+ const require = createRequire(join(root, 'package.json'))
259
+ const bundledIconsFile = require.resolve('@splendidlabz/svelte/bundled-icons')
260
+ const folder = join(dirname(bundledIconsFile), '..')
261
+
262
+ return [...scanFolder({ folder, prefixes })]
263
+ .filter(([file]) => !/\.(spec|test)\.js$|[\\/]fixtures[\\/]/.test(file))
264
+ .flatMap(([, names]) => names)
265
+ }
266
+
267
+ /**
268
+ * isSourceFile
269
+ * Tells whether a file is text that can name an icon.
270
+ *
271
+ * @param {string} file
272
+ * @returns {boolean}
273
+ */
274
+ function isSourceFile(file) {
275
+ return /\.(astro|svelte|[cm]?[jt]sx?|mdx?|json|ya?ml|html)$/.test(file)
276
+ }
277
+
278
+ /**
279
+ * fetchIcons
280
+ * Fetches icons from Iconify's API, one request per set.
281
+ *
282
+ * @param {string[]} names
283
+ * @returns {Promise<{ icons: CachedIcons, failedNames: string[] }>}
284
+ */
285
+ async function fetchIcons(names) {
286
+ const namesByPrefix = Map.groupBy(names, name => name.split(':')[0])
287
+ const responses = await Promise.all(
288
+ [...namesByPrefix].map(async ([prefix, prefixNames]) => ({
289
+ prefix,
290
+ prefixNames,
291
+ iconSet: await fetchIconSet({ prefix, names: prefixNames }),
292
+ })),
293
+ )
294
+
295
+ /** @type {CachedIcons} */
296
+ const icons = {}
297
+ const failedNames = []
298
+
299
+ for (const { prefix, prefixNames, iconSet } of responses) {
300
+ if (!iconSet) {
301
+ failedNames.push(...prefixNames)
302
+ continue
303
+ }
304
+
305
+ // Records a name the set doesn't have as null, so it isn't asked for again
306
+ for (const name of prefixNames) {
307
+ const icon = getIconData(iconSet, name.slice(prefix.length + 1))
308
+ icons[name] = icon && {
309
+ body: icon.body,
310
+ width: icon.width ?? defaultIconDimensions.width,
311
+ height: icon.height ?? defaultIconDimensions.height,
312
+ }
313
+ }
314
+ }
315
+
316
+ return { icons, failedNames }
317
+ }
318
+
319
+ /**
320
+ * fetchIconSet
321
+ * Fetches some icons of one set from Iconify's API.
322
+ *
323
+ * @param {object} opts
324
+ * @param {string} opts.prefix
325
+ * @param {string[]} opts.names Full `prefix:name` names.
326
+ * @returns {Promise<IconifyJSON | null>} Null when the request fails.
327
+ */
328
+ async function fetchIconSet({ prefix, names }) {
329
+ const icons = names.map(name => name.slice(prefix.length + 1)).join(',')
330
+
331
+ try {
332
+ const response = await zlFetch(
333
+ `https://api.iconify.design/${prefix}.json`,
334
+ {
335
+ query: { icons },
336
+ },
337
+ )
338
+ return /** @type {{ body: IconifyJSON }} */ (response).body
339
+ } catch {
340
+ return null
341
+ }
342
+ }
package/astro/index.js ADDED
@@ -0,0 +1,44 @@
1
+ /**
2
+ * @file Astro integration for Splendid Svelte.
3
+ */
4
+
5
+ import { fileURLToPath } from 'node:url'
6
+ import { bundleIcons } from './bundle-icons.js'
7
+ import { unbarrel } from './unbarrel.js'
8
+
9
+ /**
10
+ * @import { AstroIntegration } from 'astro'
11
+ */
12
+
13
+ /**
14
+ * splendidSvelte
15
+ * Loads each component from its own file, and bundles the site's icons.
16
+ *
17
+ * @param {object} [opts]
18
+ * @param {false | { names?: string[] }} [opts.icons] Extra names, or false.
19
+ * @returns {AstroIntegration}
20
+ */
21
+ export function splendidSvelte({ icons = {} } = {}) {
22
+ return {
23
+ name: '@splendidlabz/svelte',
24
+ hooks: {
25
+ 'astro:config:setup': ({ config, updateConfig, logger }) => {
26
+ const root = fileURLToPath(config.root)
27
+ const plugins = [unbarrel({ root, pkg: '@splendidlabz/svelte' })]
28
+
29
+ if (icons) {
30
+ plugins.push(
31
+ bundleIcons({
32
+ root,
33
+ srcDir: fileURLToPath(config.srcDir),
34
+ names: icons.names,
35
+ logger,
36
+ }),
37
+ )
38
+ }
39
+
40
+ updateConfig({ vite: { plugins } })
41
+ },
42
+ },
43
+ }
44
+ }
@@ -0,0 +1,238 @@
1
+ /**
2
+ * @file Points barrel imports at each component's own file.
3
+ *
4
+ * Astro makes an island's import specifier its hydration entry. `import { Select } from '@splendidlabz/svelte'` makes the whole barrel the entry, so every island downloads every component. Rewriting the import to the component's own file before Astro compiles it gives each island only what it uses.
5
+ *
6
+ * The rewrite runs in `load`, since Astro compiles `.astro` in a `pre` transform ordered ahead of any integration's plugin.
7
+ */
8
+
9
+ import { existsSync, readFileSync, realpathSync, statSync } from 'node:fs'
10
+ import { dirname, join, resolve } from 'node:path'
11
+
12
+ /**
13
+ * @import { ViteUserConfig } from 'astro'
14
+ */
15
+
16
+ /**
17
+ * unbarrel
18
+ * Rewrites a package's barrel imports in `.astro` and `.mdx` files.
19
+ *
20
+ * @typedef {NonNullable<ViteUserConfig['plugins']>[number]} Plugin Vite resolves only inside astro's own node_modules.
21
+ *
22
+ * @param {object} opts
23
+ * @param {string} opts.root The site's root folder.
24
+ * @param {string} opts.pkg Package whose barrel is rewritten.
25
+ * @returns {Plugin}
26
+ */
27
+ export function unbarrel({ root, pkg }) {
28
+ const barrel = findBarrel({ root, pkg })
29
+
30
+ // A site that doesn't install the package has nothing to rewrite
31
+ if (!barrel) return { name: 'splendid:unbarrel' }
32
+
33
+ const components = getBarrelComponents(barrel)
34
+
35
+ return {
36
+ name: 'splendid:unbarrel',
37
+ enforce: 'pre',
38
+ load(id) {
39
+ if (!/\.(astro|mdx)$/.test(id)) return
40
+
41
+ const code = readFileSync(id, 'utf8')
42
+ if (!code.includes(pkg)) return
43
+
44
+ const rewritten = id.endsWith('.mdx')
45
+ ? rewriteMdx({ code, pkg, components })
46
+ : rewriteAstro({ code, pkg, components })
47
+
48
+ if (rewritten !== code) return rewritten
49
+ },
50
+ }
51
+ }
52
+
53
+ /**
54
+ * rewriteAstro
55
+ * Rewrites barrel imports in an `.astro` file's frontmatter.
56
+ *
57
+ * The template is left alone, so a code sample showing the import stays as written.
58
+ *
59
+ * @param {object} opts
60
+ * @param {string} opts.code
61
+ * @param {string} opts.pkg
62
+ * @param {Record<string, string>} opts.components Export name to component file.
63
+ * @returns {string}
64
+ */
65
+ export function rewriteAstro({ code, pkg, components }) {
66
+ const frontmatter = code.match(/^(\s*---\r?\n)([\s\S]*?)(\r?\n---)/)
67
+ if (!frontmatter) return code
68
+
69
+ const [whole, open, body, close] = frontmatter
70
+ const rewritten = rewriteImports({ code: body, pkg, components })
71
+
72
+ return open + rewritten + close + code.slice(whole.length)
73
+ }
74
+
75
+ /**
76
+ * rewriteMdx
77
+ * Rewrites barrel imports in an `.mdx` file, outside code fences.
78
+ *
79
+ * @param {object} opts
80
+ * @param {string} opts.code
81
+ * @param {string} opts.pkg
82
+ * @param {Record<string, string>} opts.components Export name to component file.
83
+ * @returns {string}
84
+ */
85
+ export function rewriteMdx({ code, pkg, components }) {
86
+ // Splits on fences; odd indexes are the fences themselves
87
+ const parts = code.split(/(^(`{3,}|~{3,})[^\n]*\n[\s\S]*?^\2[ \t]*$)/m)
88
+
89
+ return parts
90
+ .map((part, index) => {
91
+ // The split's inner group repeats each fence's marker, which carries no text
92
+ if (index % 3 === 2) return ''
93
+ if (index % 3 === 1) return part
94
+ return rewriteImports({ code: part, pkg, components })
95
+ })
96
+ .join('')
97
+ }
98
+
99
+ /**
100
+ * rewriteImports
101
+ * Turns each named barrel import into default imports of component files.
102
+ *
103
+ * Names that aren't components stay on a barrel import. The line count is kept, so errors still point at the right line.
104
+ *
105
+ * @param {object} opts
106
+ * @param {string} opts.code
107
+ * @param {string} opts.pkg
108
+ * @param {Record<string, string>} opts.components Export name to component file.
109
+ * @returns {string}
110
+ */
111
+ function rewriteImports({ code, pkg, components }) {
112
+ const escaped = pkg.replace(/[.*+?^${}()|[\]\\/]/g, '\\$&')
113
+ const statement = new RegExp(
114
+ `^import\\s*\\{([^}]*)\\}\\s*from\\s*(['"])${escaped}\\2;?`,
115
+ 'gm',
116
+ )
117
+
118
+ return code.replace(statement, (whole, list) => {
119
+ const specifiers = list
120
+ .split(',')
121
+ .map(specifier => specifier.trim())
122
+ .filter(Boolean)
123
+ .map(specifier => {
124
+ const [imported, local = imported] = specifier.split(/\s+as\s+/)
125
+ return { imported, local, specifier }
126
+ })
127
+
128
+ const direct = specifiers
129
+ .filter(({ imported }) => components[imported])
130
+ .map(
131
+ ({ imported, local }) =>
132
+ `import ${local} from ${JSON.stringify(components[imported])};`,
133
+ )
134
+
135
+ const kept = specifiers
136
+ .filter(({ imported }) => !components[imported])
137
+ .map(({ specifier }) => specifier)
138
+
139
+ if (kept.length) direct.push(`import { ${kept.join(', ')} } from '${pkg}';`)
140
+
141
+ const newlines = '\n'.repeat(whole.split('\n').length - 1)
142
+ return direct.join(' ') + newlines
143
+ })
144
+ }
145
+
146
+ /**
147
+ * findBarrel
148
+ * Finds the file a package's `svelte` export condition points at.
149
+ *
150
+ * @param {object} opts
151
+ * @param {string} opts.root
152
+ * @param {string} opts.pkg
153
+ * @returns {string | null} Null when the package isn't installed.
154
+ */
155
+ function findBarrel({ root, pkg }) {
156
+ let dir = root
157
+
158
+ // Walks up, the way Node looks for node_modules
159
+ while (!existsSync(join(dir, 'node_modules', pkg))) {
160
+ if (dir === dirname(dir)) return null
161
+ dir = dirname(dir)
162
+ }
163
+
164
+ const pkgDir = realpathSync(join(dir, 'node_modules', pkg))
165
+ const { exports } = JSON.parse(
166
+ readFileSync(join(pkgDir, 'package.json'), 'utf8'),
167
+ )
168
+
169
+ return join(pkgDir, exports['.'].svelte)
170
+ }
171
+
172
+ /**
173
+ * getBarrelComponents
174
+ * Maps each `.svelte` component a barrel exports to its file.
175
+ *
176
+ * Follows `export *` into nested barrels. Reads the four forms the Splendid barrels use: `export *`, `export { default as X } from`, and `import X from` paired with `export { X }`.
177
+ *
178
+ * @param {string} file A barrel file, or a folder holding `index.js`.
179
+ * @returns {Record<string, string>} Export name to absolute file.
180
+ */
181
+ export function getBarrelComponents(file) {
182
+ const barrel = toModuleFile(file)
183
+ const dir = dirname(barrel)
184
+ const code = readFileSync(barrel, 'utf8')
185
+
186
+ /** @type {Record<string, string>} */
187
+ const components = {}
188
+
189
+ for (const [, from] of code.matchAll(
190
+ /^export\s*\*\s*from\s*['"](.+?)['"]/gm,
191
+ )) {
192
+ Object.assign(components, getBarrelComponents(resolve(dir, from)))
193
+ }
194
+
195
+ for (const [, list, from] of code.matchAll(
196
+ /^export\s*\{([^}]*)\}\s*from\s*['"](.+?)['"]/gm,
197
+ )) {
198
+ for (const specifier of list.split(',')) {
199
+ const [imported, local] = specifier.trim().split(/\s+as\s+/)
200
+ if (imported === 'default' && from.endsWith('.svelte')) {
201
+ components[local] = resolve(dir, from)
202
+ }
203
+ }
204
+ }
205
+
206
+ // Default imports of components, exported by name further down
207
+ /** @type {Record<string, string>} */
208
+ const imported = {}
209
+ for (const [, name, from] of code.matchAll(
210
+ /^import\s+(\w+)\s+from\s*['"](.+?\.svelte)['"]/gm,
211
+ )) {
212
+ imported[name] = resolve(dir, from)
213
+ }
214
+
215
+ for (const [, list] of code.matchAll(/^export\s*\{([^}]*)\}\s*;?\s*$/gm)) {
216
+ for (const specifier of list.split(',')) {
217
+ const [name, exported = name] = specifier.trim().split(/\s+as\s+/)
218
+ if (imported[name]) components[exported] = imported[name]
219
+ }
220
+ }
221
+
222
+ return components
223
+ }
224
+
225
+ /**
226
+ * toModuleFile
227
+ * Resolves a barrel path the way a bundler reads `./Folder` or `./file`.
228
+ *
229
+ * @param {string} file
230
+ * @returns {string}
231
+ */
232
+ function toModuleFile(file) {
233
+ if (existsSync(file) && statSync(file).isDirectory()) {
234
+ return join(file, 'index.js')
235
+ }
236
+ if (!existsSync(file)) return `${file}.js`
237
+ return file
238
+ }
@@ -1,5 +1,6 @@
1
1
  <script>
2
2
  import { getIcon, loadIcon } from '@iconify/svelte'
3
+ import { bundledIcons } from '@splendidlabz/svelte/bundled-icons'
3
4
  import { toStyleString } from '@splendidlabz/utils'
4
5
  import { onMount } from 'svelte'
5
6
 
@@ -9,7 +10,8 @@
9
10
  if (typeof style === 'object') style = toStyleString(style)
10
11
  if (!icon) throw new Error('icon property is required')
11
12
 
12
- let iconData
13
+ // Draws a bundled icon on the first render, on the server and in the browser
14
+ let iconData = bundledIcons[icon]
13
15
  let innerHTML
14
16
  const attributes = {
15
17
  class: `${icon.split(':')[1]}`,
@@ -21,12 +23,16 @@
21
23
  ...$$restProps,
22
24
  }
23
25
 
24
- // If there is an icon set, we use Iconify.
25
- // This stores the icon in localStorage after loading it for the first time. Subsequent loads will use the localStorage cached version.
26
+ // Fills any other icon after hydration, from the cache or from Iconify
27
+ onMount(async _ => {
28
+ if (iconData) return
26
29
 
27
- // Reads the cache after hydration so the first render matches the server
28
- // If icon is not in cache, loads the icon from Iconify
29
- onMount(async _ => (iconData = getIcon(icon) || (await loadIcon(icon))))
30
+ // Asks the dev server to cache the icon for the next page load
31
+ // @ts-expect-error: Vite's client types aren't loaded in this package
32
+ if (import.meta.hot) import.meta.hot.send('splendid:icon', { name: icon })
33
+
34
+ iconData = getIcon(icon) || (await loadIcon(icon))
35
+ })
30
36
 
31
37
  $: if (iconData) {
32
38
  attributes.viewBox = `0 0 ${iconData.width} ${iconData.height}`
@@ -0,0 +1,10 @@
1
+ /**
2
+ * @file Bundled icons, empty without `splendidSvelte()`.
3
+ */
4
+
5
+ /**
6
+ * @import { BundledIcon } from '../../astro/bundle-icons.js'
7
+ */
8
+
9
+ /** @type {Record<string, BundledIcon>} */
10
+ export const bundledIcons = {}
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@splendidlabz/svelte",
3
3
  "type": "module",
4
- "version": "4.17.1",
4
+ "version": "4.18.0",
5
5
  "license": "Elastic-2.0",
6
6
  "sideEffects": false,
7
7
  "homepage": "https://splendidlabz.com/docs/svelte",
@@ -21,20 +21,27 @@
21
21
  "svelte": "./components/index.js"
22
22
  },
23
23
  "./actions": "./actions/index.js",
24
- "./utils": "./utils/index.js"
24
+ "./astro": "./astro/index.js",
25
+ "./utils": "./utils/index.js",
26
+ "./bundled-icons": "./components/Icon/bundled-icons.js"
25
27
  },
26
28
  "files": [
27
29
  "actions",
30
+ "astro",
28
31
  "components",
29
32
  "utils",
30
33
  "!**/*.spec.js",
31
34
  "!**/*.test.js",
35
+ "!astro/fixtures",
32
36
  "!components/DisclosureOld"
33
37
  ],
34
38
  "dependencies": {
35
39
  "@floating-ui/dom": "^1.7.6",
40
+ "@iconify/collections": "^1.0.766",
36
41
  "@iconify/svelte": "^5.2.1",
37
- "@splendidlabz/utils": "*"
42
+ "@iconify/utils": "^3.1.7",
43
+ "@splendidlabz/utils": "*",
44
+ "zl-fetch": "^6.3.1"
38
45
  },
39
46
  "devDependencies": {
40
47
  "@splendidlabz/eslint-config": "3.0.0",
@@ -42,6 +49,7 @@
42
49
  "happy-dom": "^20.9.0",
43
50
  "svelte": "^5.57.1",
44
51
  "svelte-check": "^4.4.6",
52
+ "vite": "^8.3.8",
45
53
  "vitest": "^4.1.4"
46
54
  }
47
55
  }