@driftime/sanity-plugin-icon 0.4.3 → 0.5.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.
Files changed (37) hide show
  1. package/README.md +2 -0
  2. package/dist/{adapters-Bx_MyEX_.js → adapters-Dw6yeA3A.js} +2 -3
  3. package/dist/{adapters-Bx_MyEX_.js.map → adapters-Dw6yeA3A.js.map} +1 -1
  4. package/dist/index.js +3 -4
  5. package/dist/index.js.map +1 -1
  6. package/dist/loader-2g6inuO6.js +96 -0
  7. package/dist/loader-2g6inuO6.js.map +1 -0
  8. package/dist/next-loader.d.ts.map +1 -1
  9. package/dist/next-loader.js +3 -72
  10. package/dist/next-loader.js.map +1 -1
  11. package/dist/next.d.ts +3 -2
  12. package/dist/next.d.ts.map +1 -1
  13. package/dist/next.js +9 -8
  14. package/dist/next.js.map +1 -1
  15. package/dist/{nodes-DAzj56Xn.js → nodes-Bn7fLVZO.js} +47 -3
  16. package/dist/nodes-Bn7fLVZO.js.map +1 -0
  17. package/dist/read-worker.js +2 -2
  18. package/dist/render.js +2 -3
  19. package/dist/render.js.map +1 -1
  20. package/dist/{sets-B2lHNI7c.js → sets-B5arQvrZ.js} +58 -6
  21. package/dist/sets-B5arQvrZ.js.map +1 -0
  22. package/dist/{sets-BFcRq7dc.js → sets-DH5UbUV_.js} +13 -4
  23. package/dist/sets-DH5UbUV_.js.map +1 -0
  24. package/dist/{types-v7Qz7ogk.js → types-CmTEhJK6.js} +3 -5
  25. package/dist/{types-v7Qz7ogk.js.map → types-CmTEhJK6.js.map} +1 -1
  26. package/dist/vite.js +2 -3
  27. package/dist/vite.js.map +1 -1
  28. package/package.json +1 -1
  29. package/dist/nodes-DAzj56Xn.js.map +0 -1
  30. package/dist/registry-B0Dxiwhh.js +0 -68
  31. package/dist/registry-B0Dxiwhh.js.map +0 -1
  32. package/dist/registry-BEEpqK3z.js +0 -13
  33. package/dist/registry-BEEpqK3z.js.map +0 -1
  34. package/dist/sets-B2lHNI7c.js.map +0 -1
  35. package/dist/sets-BFcRq7dc.js.map +0 -1
  36. package/dist/utils-COPacfAq.js +0 -48
  37. package/dist/utils-COPacfAq.js.map +0 -1
@@ -1,76 +1,7 @@
1
1
  import { t as logger } from "./defaults-BEzCWZtH.js";
2
- import { r as isRecord } from "./utils-COPacfAq.js";
3
- import { n as getSetsFolder, t as createRegistryModule } from "./registry-B0Dxiwhh.js";
4
- import { a as writeIconNames, i as loadIconSet, n as detectLibraries, r as listRegistryDependencies, t as describeReport } from "./sets-B2lHNI7c.js";
5
- import { i as listPluginFiles, s as readPluginBuild } from "./adapters-Bx_MyEX_.js";
6
- import path from "node:path";
7
- import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
8
- import { randomUUID } from "node:crypto";
9
- /**
10
- * Converts every installed library, writes each set to a file the bundler can split into its own chunk, and returns
11
- * the registry that replaces the placeholder.
12
- *
13
- * @param resourcePath - Path of the placeholder being replaced.
14
- * @param options - The loader's options.
15
- * @returns The registry's code, and the files and folders it was generated from.
16
- */
17
- async function generateRegistryOnce(resourcePath, options) {
18
- let root = process.cwd(), custom = isRecord(options) && isRecord(options.custom) ? options.custom : {}, folders = Object.fromEntries(Object.entries(custom).flatMap(([name, folder]) => typeof folder == "string" ? [[name, folder]] : [])), cacheDir = path.join(root, "node_modules", ".cache"), setsDir = getSetsFolder(root);
19
- await mkdir(setsDir, { recursive: !0 });
20
- let libraries = await detectLibraries(root, folders), files = /* @__PURE__ */ new Map(), names = /* @__PURE__ */ new Map(), converted = await Promise.all(libraries.flatMap((library) => library.styles.map(async ({ style }) => {
21
- let { adapter } = library, { set, report } = await loadIconSet(library, style, {
22
- root,
23
- cacheDir
24
- }), file = path.join(setsDir, `${adapter.library}-${style}.json`), temporary = `${file}.${randomUUID()}.tmp`;
25
- return await writeFile(temporary, JSON.stringify(set)), await rename(temporary, file), logger.info(describeReport(adapter.label, style, report)), {
26
- library: adapter.library,
27
- style,
28
- set,
29
- file
30
- };
31
- })));
32
- for (let { library, style, set, file } of converted) {
33
- let libraryNames = names.get(library) ?? /* @__PURE__ */ new Set();
34
- for (let icon of set.icons) libraryNames.add(icon.name);
35
- names.set(library, libraryNames), files.set(`${library}/${style}`, file);
36
- }
37
- await writeIconNames(new Map([...names].filter(([, libraryNames]) => libraryNames.size > 0)));
38
- let code = createRegistryModule(libraries, (key) => {
39
- let file = files.get(key) ?? "", relative = path.relative(path.dirname(resourcePath), file).replaceAll("\\", "/");
40
- return relative.startsWith(".") ? relative : `./${relative}`;
41
- }), dependencies = listRegistryDependencies(root, libraries);
42
- return {
43
- code,
44
- files: [...dependencies.files, ...await listPluginFiles()],
45
- folders: dependencies.folders
46
- };
47
- }
48
- /**
49
- * Reads the project's `package.json` as text.
50
- *
51
- * @returns The contents, or an empty string when there's no file.
52
- */
53
- async function readManifest() {
54
- try {
55
- return await readFile(path.join(process.cwd(), "package.json"), "utf8");
56
- } catch {
57
- return "";
58
- }
59
- }
60
- /**
61
- * Generates the registry, running again when the project's `package.json` changes while it runs, so a package
62
- * installed during a run isn't missed.
63
- *
64
- * @param resourcePath - Path of the placeholder being replaced.
65
- * @param options - The loader's options.
66
- * @param attempts - Runs allowed, including this one.
67
- * @returns The registry's code, and the files and folders it was generated from.
68
- * @public
69
- */
70
- async function generateRegistry(resourcePath, options, attempts = 3) {
71
- let before = await readManifest(), result = await generateRegistryOnce(resourcePath, options);
72
- return before === await readManifest() || attempts <= 1 ? result : generateRegistry(resourcePath, options, attempts - 1);
73
- }
2
+ import { l as isRecord } from "./nodes-Bn7fLVZO.js";
3
+ import { s as readPluginBuild } from "./adapters-Dw6yeA3A.js";
4
+ import { t as generateRegistry } from "./loader-2g6inuO6.js";
74
5
  /**
75
6
  * Checks whether an imported module is a fresh copy of this one.
76
7
  *
@@ -1 +1 @@
1
- {"version":3,"file":"next-loader.js","names":["randomUUID","mkdir","readFile","rename","writeFile","path","isRecord","writeIconNames","listPluginFiles","createRegistryModule","getSetsFolder","describeReport","detectLibraries","listRegistryDependencies","loadIconSet","logger","LoaderContext","resourcePath","getOptions","addDependency","file","addContextDependency","folder","generateRegistryOnce","options","root","process","cwd","custom","folders","Object","fromEntries","entries","flatMap","name","cacheDir","join","setsDir","recursive","libraries","files","Map","names","Set","converted","Promise","all","library","styles","map","style","adapter","set","report","temporary","JSON","stringify","info","label","libraryNames","get","icon","icons","add","filter","size","code","key","relative","dirname","replaceAll","startsWith","dependencies","readManifest","generateRegistry","attempts","ReturnType","before","result","after","isRecord","LoaderContext","generateRegistry","readPluginBuild","logger","LoaderModule","isLoaderModule","value","iconSetsLoader","this","fresh","import","meta","url","Error","format","code","files","folders","resourcePath","getOptions","file","addDependency","folder","addContextDependency","\"custom\"","\"generateRegistry\""],"sources":["../src/build/loader.ts","../src/next-loader.ts"],"sourcesContent":["import { randomUUID } from \"node:crypto\";\nimport { mkdir, readFile, rename, writeFile } from \"node:fs/promises\";\nimport path from \"node:path\";\n\nimport { isRecord } from \"@repo/lib/utils\";\n\nimport { writeIconNames } from \"@/build/names\";\nimport { listPluginFiles } from \"@/build/packages\";\nimport { createRegistryModule, getSetsFolder } from \"@/build/registry\";\nimport { describeReport, detectLibraries, listRegistryDependencies, loadIconSet } from \"@/build/sets\";\nimport { logger } from \"@/config/defaults\";\n\n/**\n * The parts of a webpack or Turbopack loader's context the build step uses.\n *\n * @public\n */\nexport interface LoaderContext {\n /** Path of the module being loaded. */\n resourcePath: string;\n /**\n * Reads the loader's options.\n *\n * @returns The options.\n */\n getOptions: () => unknown;\n /**\n * Tells the bundler to run the loader again when a file changes.\n *\n * @param file - The file.\n */\n addDependency?: (file: string) => void;\n /**\n * Tells the bundler to run the loader again when anything in a folder changes.\n *\n * @param folder - The folder.\n */\n addContextDependency?: (folder: string) => void;\n}\n\n/**\n * Converts every installed library, writes each set to a file the bundler can split into its own chunk, and returns\n * the registry that replaces the placeholder.\n *\n * @param resourcePath - Path of the placeholder being replaced.\n * @param options - The loader's options.\n * @returns The registry's code, and the files and folders it was generated from.\n */\nasync function generateRegistryOnce(resourcePath: string, options: unknown) {\n const root = process.cwd();\n const custom = isRecord(options) && isRecord(options[\"custom\"]) ? options[\"custom\"] : {};\n const folders = Object.fromEntries(\n Object.entries(custom).flatMap(([name, folder]) => (typeof folder === \"string\" ? [[name, folder]] : [])),\n );\n\n const cacheDir = path.join(root, \"node_modules\", \".cache\");\n const setsDir = getSetsFolder(root);\n await mkdir(setsDir, { recursive: true });\n\n const libraries = await detectLibraries(root, folders);\n const files = new Map<string, string>();\n const names = new Map<string, Set<string>>();\n\n const converted = await Promise.all(\n libraries.flatMap((library) =>\n library.styles.map(async ({ style }) => {\n const { adapter } = library;\n const { set, report } = await loadIconSet(library, style, { root, cacheDir });\n const file = path.join(setsDir, `${adapter.library}-${style}.json`);\n const temporary = `${file}.${randomUUID()}.tmp`;\n\n // The browser and server builds convert at once, even in one process, so each set is swapped in whole.\n await writeFile(temporary, JSON.stringify(set));\n await rename(temporary, file);\n logger.info(describeReport(adapter.label, style, report));\n\n return { library: adapter.library, style, set, file };\n }),\n ),\n );\n\n for (const { library, style, set, file } of converted) {\n const libraryNames = names.get(library) ?? new Set<string>();\n\n for (const icon of set.icons) libraryNames.add(icon.name);\n names.set(library, libraryNames);\n files.set(`${library}/${style}`, file);\n }\n\n await writeIconNames(new Map([...names].filter(([, libraryNames]) => libraryNames.size > 0)));\n\n const code = createRegistryModule(libraries, (key) => {\n const file = files.get(key) ?? \"\";\n const relative = path.relative(path.dirname(resourcePath), file).replaceAll(\"\\\\\", \"/\");\n\n return relative.startsWith(\".\") ? relative : `./${relative}`;\n });\n\n const dependencies = listRegistryDependencies(root, libraries);\n\n // The plugin's own files are included, so updating it runs the loader again even when `package.json` doesn't change.\n return { code, files: [...dependencies.files, ...(await listPluginFiles())], folders: dependencies.folders };\n}\n\n/**\n * Reads the project's `package.json` as text.\n *\n * @returns The contents, or an empty string when there's no file.\n */\nasync function readManifest() {\n try {\n return await readFile(path.join(process.cwd(), \"package.json\"), \"utf8\");\n } catch {\n return \"\";\n }\n}\n\n/**\n * Generates the registry, running again when the project's `package.json` changes while it runs, so a package\n * installed during a run isn't missed.\n *\n * @param resourcePath - Path of the placeholder being replaced.\n * @param options - The loader's options.\n * @param attempts - Runs allowed, including this one.\n * @returns The registry's code, and the files and folders it was generated from.\n * @public\n */\nexport async function generateRegistry(\n resourcePath: string,\n options: unknown,\n attempts = 3,\n): ReturnType<typeof generateRegistryOnce> {\n const before = await readManifest();\n const result = await generateRegistryOnce(resourcePath, options);\n const after = await readManifest();\n\n return before === after || attempts <= 1 ? result : generateRegistry(resourcePath, options, attempts - 1);\n}\n","import { isRecord } from \"@repo/lib/utils\";\n\nimport type { LoaderContext, generateRegistry } from \"@/build/loader\";\nimport { readPluginBuild } from \"@/build/packages\";\nimport { logger } from \"@/config/defaults\";\n\n/** This module as the loader imports it afresh on every run. */\ninterface LoaderModule {\n /** Generates the registry. */\n generateRegistry: typeof generateRegistry;\n}\n\n/**\n * Checks whether an imported module is a fresh copy of this one.\n *\n * @param value - The imported module.\n * @returns True if the module is this one.\n */\nfunction isLoaderModule(value: unknown): value is LoaderModule {\n return isRecord(value) && typeof value[\"generateRegistry\"] === \"function\";\n}\n\n/**\n * Webpack and Turbopack loader that replaces the placeholder registry with the project's converted icon sets. The\n * bundler keeps this module loaded, so it imports a fresh copy of itself, versioned by the plugin's code, and runs that\n * copy's build step, so updating the plugin takes effect without restarting the bundler.\n *\n * @param this - The loader context.\n * @returns The registry's code.\n * @throws When the plugin's build step can't be loaded.\n * @public\n */\nasync function iconSetsLoader(this: LoaderContext) {\n const fresh: unknown = await import(`${import.meta.url}?version=${await readPluginBuild()}`);\n if (!isLoaderModule(fresh)) throw new Error(logger.format(\"The build step couldn't be loaded.\"));\n\n const { code, files, folders } = await fresh.generateRegistry(this.resourcePath, this.getOptions());\n\n for (const file of files) this.addDependency?.(file);\n for (const folder of folders) this.addContextDependency?.(folder);\n\n return code;\n}\n\nexport default iconSetsLoader;\nexport { generateRegistry } from \"@/build/lo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,eAAeC,OAAuC;CAC7D,OAAOP,SAASO,KAAK,KAAK,OAAOA,MAAMmB,oBAAwB;AACjE;;;;;;;;;;;AAYA,eAAelB,iBAAoC;CACjD,IAAME,QAAiB,MAAM,OAAO,GAAGC,YAAYE,IAAG,WAAY,MAAMV,gBAAgB;CACxF,IAAI,CAACG,eAAeI,KAAK,GAAG,MAAUI,MAAMV,OAAOW,OAAO,oCAAoC,CAAC;CAE/F,IAAM,EAAEC,MAAMC,OAAOC,YAAY,MAAMR,MAAMR,iBAAiB,KAAKiB,cAAc,KAAKC,WAAW,CAAC;CAElG,KAAK,IAAMC,QAAQJ,OAAO,KAAKK,gBAAgBD,IAAI;CACnD,KAAK,IAAME,UAAUL,SAAS,KAAKM,uBAAuBD,MAAM;CAEhE,OAAOP;AACT"}
1
+ {"version":3,"file":"next-loader.js","names":["isRecord","LoaderContext","generateRegistry","readPluginBuild","logger","LoaderModule","isLoaderModule","value","iconSetsLoader","this","fresh","import","meta","url","Error","format","code","files","folders","resourcePath","getOptions","file","addDependency","folder","addContextDependency","\"generateRegistry\""],"sources":["../src/next-loader.ts"],"sourcesContent":["import { isRecord } from \"@repo/lib/utils\";\n\nimport type { LoaderContext, generateRegistry } from \"@/build/loader\";\nimport { readPluginBuild } from \"@/build/packages\";\nimport { logger } from \"@/config/defaults\";\n\n/** This module as the loader imports it afresh on every run. */\ninterface LoaderModule {\n /** Generates the registry. */\n generateRegistry: typeof generateRegistry;\n}\n\n/**\n * Checks whether an imported module is a fresh copy of this one.\n *\n * @param value - The imported module.\n * @returns True if the module is this one.\n */\nfunction isLoaderModule(value: unknown): value is LoaderModule {\n return isRecord(value) && typeof value[\"generateRegistry\"] === \"function\";\n}\n\n/**\n * Webpack and Turbopack loader that replaces the placeholder registry with the project's converted icon sets. The\n * bundler keeps this module loaded, so it imports a fresh copy of itself, versioned by the plugin's code, and runs that\n * copy's build step, so updating the plugin takes effect without restarting the bundler.\n *\n * @param this - The loader context.\n * @returns The registry's code.\n * @throws When the plugin's build step can't be loaded.\n * @public\n */\nasync function iconSetsLoader(this: LoaderContext) {\n const fresh: unknown = await import(`${import.meta.url}?version=${await readPluginBuild()}`);\n if (!isLoaderModule(fresh)) throw new Error(logger.format(\"The build step couldn't be loaded.\"));\n\n const { code, files, folders } = await fresh.generateRegistry(this.resourcePath, this.getOptions());\n\n for (const file of files) this.addDependency?.(file);\n for (const folder of folders) this.addContextDependency?.(folder);\n\n return code;\n}\n\nexport default iconSetsLoader;\nexport { generateRegistry } from \"@/build/loader\";\n"],"mappings":";;;;;;;;;;AAkBA,SAASM,eAAeC,OAAuC;CAC7D,OAAOP,SAASO,KAAK,KAAK,OAAOA,MAAMkB,oBAAwB;AACjE;;;;;;;;;;;AAYA,eAAejB,iBAAoC;CACjD,IAAME,QAAiB,MAAM,OAAO,GAAGC,YAAYE,IAAG,WAAY,MAAMV,gBAAgB;CACxF,IAAI,CAACG,eAAeI,KAAK,GAAG,MAAUI,MAAMV,OAAOW,OAAO,oCAAoC,CAAC;CAE/F,IAAM,EAAEC,MAAMC,OAAOC,YAAY,MAAMR,MAAMR,iBAAiB,KAAKiB,cAAc,KAAKC,WAAW,CAAC;CAElG,KAAK,IAAMC,QAAQJ,OAAO,KAAKK,gBAAgBD,IAAI;CACnD,KAAK,IAAME,UAAUL,SAAS,KAAKM,uBAAuBD,MAAM;CAEhE,OAAOP;AACT"}
package/dist/next.d.ts CHANGED
@@ -35,9 +35,10 @@ type SanityIconWebpackCustomizer = (config: SanityIconWebpackConfig, context: ne
35
35
  * Turbopack and webpack.
36
36
  *
37
37
  * @param options - Options for the build step.
38
- * @returns A function that extends the Next.js configuration.
38
+ * @returns A function that extends the Next.js configuration into an async configuration function, which converts the
39
+ * installed libraries before Next.js starts building.
39
40
  * @public
40
41
  */
41
- export declare function withIcons(options?: SanityIconBuildOptions): <Config extends SanityIconNextConfig>(config: Config) => Config;
42
+ export declare function withIcons(options?: SanityIconBuildOptions): <Config extends SanityIconNextConfig>(config: Config) => (phase: string) => Promise<Config>;
42
43
  export type { SanityIconNextConfig, SanityIconWebpackConfig, SanityIconWebpackCustomizer };
43
44
  //# sourceMappingURL=next.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"next.d.ts","names":["SanityIconBuildOptions","SanityIconWebpackConfig","SanityIconNextConfig","Record","SanityIconWebpackCustomizer","withIcons","Config"],"sources":["../src/build/next.ts"],"mappings":";;;;;;UAoBiBC;;EAEf;IAAW;;;;;;;;UAQIC;;EAEf;IAAc,QAAQC;;;EAEtB,UAAUC;;;;;;;;KASAA,+BAA+B,QAAQH,yBAAyB,mBAAmBA;;;;;;;;;wBAa/EI,UAAU,UAASL,0BAOJ,eAAeE,sBAAoB,QAAUI,WAASA"}
1
+ {"version":3,"file":"next.d.ts","names":["SanityIconBuildOptions","SanityIconWebpackConfig","SanityIconNextConfig","Record","SanityIconWebpackCustomizer","withIcons","Config","Promise"],"sources":["../src/build/next.ts"],"mappings":";;;;;;UAoBiBC;;EAEf;IAAW;;;;;;;;UAQIC;;EAEf;IAAc,QAAQC;;;EAEtB,UAAUC;;;;;;;;KASAA,+BAA+B,QAAQH,yBAAyB,mBAAmBA;;;;;;;;;;wBAc/EI,UAAU,UAASL,0BAKJ,eAAeE,sBAAoB,QAAUI,YAAM,kBAiBnDC,QAAAD"}
package/dist/next.js CHANGED
@@ -1,6 +1,6 @@
1
- import { i as registryModulePath, n as getSetsFolder, r as isRegistryModule } from "./registry-B0Dxiwhh.js";
1
+ import { c as registryModulePath, s as isRegistryModule } from "./sets-B5arQvrZ.js";
2
+ import { n as writeIconSets } from "./loader-2g6inuO6.js";
2
3
  import path from "node:path";
3
- import { mkdirSync } from "node:fs";
4
4
  import { fileURLToPath } from "node:url";
5
5
  /** Path of the loader, published next to this file. */
6
6
  const loaderPath = fileURLToPath(new URL("next-loader.js", import.meta.url));
@@ -9,17 +9,17 @@ const loaderPath = fileURLToPath(new URL("next-loader.js", import.meta.url));
9
9
  * Turbopack and webpack.
10
10
  *
11
11
  * @param options - Options for the build step.
12
- * @returns A function that extends the Next.js configuration.
12
+ * @returns A function that extends the Next.js configuration into an async configuration function, which converts the
13
+ * installed libraries before Next.js starts building.
13
14
  * @public
14
15
  */
15
16
  function withIcons(options = {}) {
16
- let loader = {
17
+ let custom = options.custom ?? {}, loader = {
17
18
  loader: loaderPath,
18
- options: { custom: options.custom ?? {} }
19
+ options: { custom }
19
20
  }, placeholder = path.basename(path.dirname(path.dirname(registryModulePath)));
20
- return mkdirSync(getSetsFolder(process.cwd()), { recursive: !0 }), function extendConfig(config) {
21
- let { turbopack, webpack } = config;
22
- return {
21
+ return function extendConfig(config) {
22
+ let { turbopack, webpack } = config, extendedConfig = {
23
23
  ...config,
24
24
  turbopack: {
25
25
  ...turbopack,
@@ -45,6 +45,7 @@ function withIcons(options = {}) {
45
45
  };
46
46
  }
47
47
  };
48
+ return async (phase) => ((phase === "phase-development-server" || phase === "phase-production-build") && await writeIconSets(process.cwd(), custom), extendedConfig);
48
49
  };
49
50
  }
50
51
  export { withIcons };
package/dist/next.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"next.js","names":["mkdirSync","path","fileURLToPath","getSetsFolder","isRegistryModule","registryModulePath","SanityIconBuildOptions","WebpackRule","test","resource","use","loader","options","custom","Record","SanityIconWebpackConfig","module","rules","SanityIconNextConfig","turbopack","webpack","SanityIconWebpackCustomizer","config","context","loaderPath","URL","import","meta","url","withIcons","placeholder","basename","dirname","process","cwd","recursive","extendConfig","Config","loaders","as","webpackConfig","resolved","rule"],"sources":["../src/build/next.ts"],"sourcesContent":["import { mkdirSync } from \"node:fs\";\nimport path from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\n\nimport { getSetsFolder, isRegistryModule, registryModulePath } from \"@/build/registry\";\nimport type { SanityIconBuildOptions } from \"@/build/vite\";\n\n/** A webpack rule, limited to what the build step adds. */\ninterface WebpackRule {\n /** Matches the placeholder registry. */\n test: (resource: string) => boolean;\n /** The loader that replaces it, with the build step's options. */\n use: { loader: string; options: { custom: Record<string, string> } }[];\n}\n\n/**\n * The parts of a webpack configuration the build step extends.\n *\n * @public\n */\nexport interface SanityIconWebpackConfig {\n /** Module settings, whose rules the build step adds to. */\n module?: { rules?: unknown[] };\n}\n\n/**\n * The parts of a Next.js configuration the build step extends, so the package doesn't depend on Next.js's own types.\n *\n * @public\n */\nexport interface SanityIconNextConfig {\n /** Turbopack settings, whose rules the build step adds to. */\n turbopack?: { rules?: Record<string, unknown> };\n /** Customises webpack, for projects that build with it instead of Turbopack. */\n webpack?: SanityIconWebpackCustomizer | null;\n}\n\n/**\n * Customises webpack, as Next.js's `webpack` option does. The context is typed `never` because the build step only\n * passes Next.js's own context through, so any context type a project's function declares is accepted.\n *\n * @public\n */\nexport type SanityIconWebpackCustomizer = (config: SanityIconWebpackConfig, context: never) => SanityIconWebpackConfig;\n\n/** Path of the loader, published next to this file. */\nconst loaderPath = fileURLToPath(new URL(\"next-loader.js\", import.meta.url));\n\n/**\n * Adds the icon build step to a Next.js configuration, for Studios embedded in a Next.js app. It works with both\n * Turbopack and webpack.\n *\n * @param options - Options for the build step.\n * @returns A function that extends the Next.js configuration.\n * @public\n */\nexport function withIcons(options: SanityIconBuildOptions = {}) {\n const loader = { loader: loaderPath, options: { custom: options.custom ?? {} } };\n const placeholder = path.basename(path.dirname(path.dirname(registryModulePath)));\n\n // Turbopack never finds files in a folder that was missing when the build started, so it's made before then.\n mkdirSync(getSetsFolder(process.cwd()), { recursive: true });\n\n return function extendConfig<Config extends SanityIconNextConfig>(config: Config): Config {\n const { turbopack, webpack } = config;\n\n return {\n ...config,\n turbopack: {\n ...turbopack,\n rules: { ...turbopack?.rules, [`**/${placeholder}/dist/sets.js`]: { loaders: [loader], as: \"*.js\" } },\n },\n webpack(webpackConfig: SanityIconWebpackConfig, context: never) {\n const resolved = webpack?.(webpackConfig, context) ?? webpackConfig;\n const rule: WebpackRule = { test: isRegistryModule, use: [loader] };\n\n return { ...resolved, module: { ...resolved.module, rules: [...(resolved.module?.rules ?? []), rule] } };\n },\n };\n };\n}\n"],"mappings":";;;;;AA8CA,MAAMwB,aAAatB,cAAc,IAAIuB,IAAI,kBAAkBC,YAAYE,GAAG,CAAC;;;;;;;;;AAU3E,SAAgBC,UAAUjB,UAAkC,CAAC,GAAG;CAC9D,IAAMD,SAAS;EAAEA,QAAQa;EAAYZ,SAAS,EAAEC,QAAQD,QAAQC,UAAU,CAAC,EAAE;CAAE,GACzEiB,cAAc7B,KAAK8B,SAAS9B,KAAK+B,QAAQ/B,KAAK+B,QAAQ3B,kBAAkB,CAAC,CAAC;CAKhF,OAFAL,UAAUG,cAAc8B,QAAQC,IAAI,CAAC,GAAG,EAAEC,WAAW,GAAK,CAAC,GAEpD,SAASC,aAAkDd,QAAwB;EACxF,IAAM,EAAEH,WAAWC,YAAYE;EAE/B,OAAO;GACL,GAAGA;GACHH,WAAW;IACT,GAAGA;IACHF,OAAO;KAAE,GAAGE,WAAWF;MAAQ,MAAMa,YAAW,iBAAkB;MAAEQ,SAAS,CAAC3B,MAAM;MAAG4B,IAAI;KAAO;IAAE;GACtG;GACAnB,QAAQoB,eAAwCjB,SAAgB;IAC9D,IAAMkB,WAAWrB,UAAUoB,eAAejB,OAAO,KAAKiB,eAChDE,OAAoB;KAAElC,MAAMJ;KAAkBM,KAAK,CAACC,MAAM;IAAE;IAElE,OAAO;KAAE,GAAG8B;KAAUzB,QAAQ;MAAE,GAAGyB,SAASzB;MAAQC,OAAO,CAAC,GAAIwB,SAASzB,QAAQC,SAAS,CAAA,GAAKyB,IAAI;KAAE;IAAE;GACzG;EACF;CACF;AACF"}
1
+ {"version":3,"file":"next.js","names":["path","fileURLToPath","writeIconSets","isRegistryModule","registryModulePath","SanityIconBuildOptions","WebpackRule","test","resource","use","loader","options","custom","Record","SanityIconWebpackConfig","module","rules","SanityIconNextConfig","turbopack","webpack","SanityIconWebpackCustomizer","config","context","loaderPath","URL","import","meta","url","withIcons","placeholder","basename","dirname","extendConfig","Config","extendedConfig","loaders","as","webpackConfig","resolved","rule","phase","process","cwd"],"sources":["../src/build/next.ts"],"sourcesContent":["import path from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\n\nimport { writeIconSets } from \"@/build/loader\";\nimport { isRegistryModule, registryModulePath } from \"@/build/registry\";\nimport type { SanityIconBuildOptions } from \"@/build/vite\";\n\n/** A webpack rule, limited to what the build step adds. */\ninterface WebpackRule {\n /** Matches the placeholder registry. */\n test: (resource: string) => boolean;\n /** The loader that replaces it, with the build step's options. */\n use: { loader: string; options: { custom: Record<string, string> } }[];\n}\n\n/**\n * The parts of a webpack configuration the build step extends.\n *\n * @public\n */\nexport interface SanityIconWebpackConfig {\n /** Module settings, whose rules the build step adds to. */\n module?: { rules?: unknown[] };\n}\n\n/**\n * The parts of a Next.js configuration the build step extends, so the package doesn't depend on Next.js's own types.\n *\n * @public\n */\nexport interface SanityIconNextConfig {\n /** Turbopack settings, whose rules the build step adds to. */\n turbopack?: { rules?: Record<string, unknown> };\n /** Customises webpack, for projects that build with it instead of Turbopack. */\n webpack?: SanityIconWebpackCustomizer | null;\n}\n\n/**\n * Customises webpack, as Next.js's `webpack` option does. The context is typed `never` because the build step only\n * passes Next.js's own context through, so any context type a project's function declares is accepted.\n *\n * @public\n */\nexport type SanityIconWebpackCustomizer = (config: SanityIconWebpackConfig, context: never) => SanityIconWebpackConfig;\n\n/** Path of the loader, published next to this file. */\nconst loaderPath = fileURLToPath(new URL(\"next-loader.js\", import.meta.url));\n\n/**\n * Adds the icon build step to a Next.js configuration, for Studios embedded in a Next.js app. It works with both\n * Turbopack and webpack.\n *\n * @param options - Options for the build step.\n * @returns A function that extends the Next.js configuration into an async configuration function, which converts the\n * installed libraries before Next.js starts building.\n * @public\n */\nexport function withIcons(options: SanityIconBuildOptions = {}) {\n const custom = options.custom ?? {};\n const loader = { loader: loaderPath, options: { custom } };\n const placeholder = path.basename(path.dirname(path.dirname(registryModulePath)));\n\n return function extendConfig<Config extends SanityIconNextConfig>(config: Config) {\n const { turbopack, webpack } = config;\n const extendedConfig: Config = {\n ...config,\n turbopack: {\n ...turbopack,\n rules: { ...turbopack?.rules, [`**/${placeholder}/dist/sets.js`]: { loaders: [loader], as: \"*.js\" } },\n },\n webpack(webpackConfig: SanityIconWebpackConfig, context: never) {\n const resolved = webpack?.(webpackConfig, context) ?? webpackConfig;\n const rule: WebpackRule = { test: isRegistryModule, use: [loader] };\n\n return { ...resolved, module: { ...resolved.module, rules: [...(resolved.module?.rules ?? []), rule] } };\n },\n };\n\n // Turbopack never finds a file that wasn't there when the build started, even with a cache from an earlier build.\n return async (phase: string) => {\n // `next start` also loads the configuration, where `node_modules` may be read-only and nothing is bundled.\n if (phase === \"phase-development-server\" || phase === \"phase-production-build\") {\n await writeIconSets(process.cwd(), custom);\n }\n\n return extendedConfig;\n };\n };\n}\n"],"mappings":";;;;;AA8CA,MAAMuB,aAAatB,cAAc,IAAIuB,IAAI,kBAAkBC,YAAYE,GAAG,CAAC;;;;;;;;;;AAW3E,SAAgBC,UAAUjB,UAAkC,CAAC,GAAG;CAC9D,IAAMC,SAASD,QAAQC,UAAU,CAAC,GAC5BF,SAAS;EAAEA,QAAQa;EAAYZ,SAAS,EAAEC,OAAO;CAAE,GACnDiB,cAAc7B,KAAK8B,SAAS9B,KAAK+B,QAAQ/B,KAAK+B,QAAQ3B,kBAAkB,CAAC,CAAC;CAEhF,OAAO,SAAS4B,aAAkDX,QAAgB;EAChF,IAAM,EAAEH,WAAWC,YAAYE,QACzBa,iBAAyB;GAC7B,GAAGb;GACHH,WAAW;IACT,GAAGA;IACHF,OAAO;KAAE,GAAGE,WAAWF;MAAQ,MAAMa,YAAW,iBAAkB;MAAEM,SAAS,CAACzB,MAAM;MAAG0B,IAAI;KAAO;IAAE;GACtG;GACAjB,QAAQkB,eAAwCf,SAAgB;IAC9D,IAAMgB,WAAWnB,UAAUkB,eAAef,OAAO,KAAKe,eAChDE,OAAoB;KAAEhC,MAAMJ;KAAkBM,KAAK,CAACC,MAAM;IAAE;IAElE,OAAO;KAAE,GAAG4B;KAAUvB,QAAQ;MAAE,GAAGuB,SAASvB;MAAQC,OAAO,CAAC,GAAIsB,SAASvB,QAAQC,SAAS,CAAA,GAAKuB,IAAI;KAAE;IAAE;GACzG;EACF;EAGA,OAAO,OAAOC,YAERA,UAAU,8BAA8BA,UAAU,6BACpD,MAAMtC,cAAcuC,QAAQC,IAAI,GAAG9B,MAAM,GAGpCsB;CAEX;AACF"}
@@ -1,6 +1,50 @@
1
- import { n as isDefined, r as isRecord } from "./utils-COPacfAq.js";
2
1
  import { stegaClean } from "@sanity/client/stega";
3
2
  /**
3
+ * Checks whether a value is present. `false`, blank strings, and empty plain objects count as absent,
4
+ * as does an array with no present elements.
5
+ *
6
+ * @param value - The value to check.
7
+ * @returns True if the value is present.
8
+ */
9
+ function isDefined(value) {
10
+ if (value == null || value === !1) return !1;
11
+ if (typeof value == "string") return value.trim() !== "";
12
+ if (Array.isArray(value)) return value.some((element) => isDefined(element));
13
+ if (typeof value == "object") {
14
+ let prototype = Reflect.getPrototypeOf(value);
15
+ return prototype !== Object.prototype && prototype !== null || Object.keys(value).length > 0;
16
+ }
17
+ return !0;
18
+ }
19
+ /**
20
+ * Converts a string to another case.
21
+ *
22
+ * @param value - The string to convert.
23
+ * @param format - The case to convert to.
24
+ * @returns The converted string.
25
+ */
26
+ function convertCase(value, format) {
27
+ let words = value.replaceAll(/(?<lower>[a-z0-9])(?<upper>[A-Z])/gu, "$<lower> $<upper>").replaceAll(/[-_\s]+/gu, " ").trim().toLowerCase();
28
+ switch (format) {
29
+ case "kebab": return words.replaceAll(/\s+/gu, "-");
30
+ case "snake": return words.replaceAll(/\s+/gu, "_");
31
+ case "camel": return words.replaceAll(/\s+(?<character>.)/gu, (_match, character) => character.toUpperCase());
32
+ case "pascal": return words.replaceAll(/(?:^|\s+)(?<character>.)/gu, (_match, character) => character.toUpperCase());
33
+ case "title": return words.replaceAll(/\b\w/gu, (character) => character.toUpperCase());
34
+ case "sentence": return words.replaceAll(/^(?<character>.)/gu, (character) => character.toUpperCase());
35
+ default: return value;
36
+ }
37
+ }
38
+ /**
39
+ * Checks whether a value is an object whose keys can be read.
40
+ *
41
+ * @param value - The value to check.
42
+ * @returns True if the value is an object.
43
+ */
44
+ function isRecord(value) {
45
+ return typeof value == "object" && !!value;
46
+ }
47
+ /**
4
48
  * SVG elements a drawing may contain: everything that draws, paints, clips, masks, or filters. Anything that runs
5
49
  * code, embeds other content, links away, loads a file, animates, or styles the page around it is left out.
6
50
  */
@@ -134,6 +178,6 @@ function serializeIconDrawing(drawing) {
134
178
  node: drawing.node
135
179
  });
136
180
  }
137
- export { resolveIconDrawing as a, parseIconRoot as i, iconSvgAttributes as n, serializeIconDrawing as o, parseIconNode as r, findDrawingProblem as t };
181
+ export { resolveIconDrawing as a, isDefined as c, parseIconRoot as i, isRecord as l, iconSvgAttributes as n, serializeIconDrawing as o, parseIconNode as r, convertCase as s, findDrawingProblem as t };
138
182
 
139
- //# sourceMappingURL=nodes-DAzj56Xn.js.map
183
+ //# sourceMappingURL=nodes-Bn7fLVZO.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"nodes-Bn7fLVZO.js","names":["Nullable","T","isDefined","value","undefined","trim","Array","isArray","some","element","prototype","Reflect","getPrototypeOf","Object","keys","length","convertCase","format","words","replaceAll","toLowerCase","_match","character","toUpperCase","isRecord","Record","readPath","path","current","segment","isDefined","isRecord","stegaClean","IconElement","element","attributes","Record","children","IconNode","IconRoot","IconDrawing","root","node","iconElements","ReadonlySet","Set","linkAttributes","urlPattern","iconSvgAttributes","xmlns","width","height","const","isAttributes","value","Object","values","every","attribute","isIconElement","Array","isArray","length","parts","name","child","findAttributeProblem","entries","test","has","startsWith","includes","references","matchAll","outside","some","groups","trim","replace","split","undefined","findNodeProblem","problem","findDrawingProblem","parseIconNode","parseIconRoot","parseJson","JSON","parse","resolveIconDrawing","cleaned","stored","drawing","serializeIconDrawing","stringify","parts","\"reference\"","\"root\"","\"node\""],"sources":["../../@repo/lib/utils.ts","../src/lib/nodes.ts"],"sourcesContent":["/** A value that may be null or undefined. */\ntype Nullable<T> = T | null | undefined;\n\n/**\n * Checks whether a value is present. `false`, blank strings, and empty plain objects count as absent,\n * as does an array with no present elements.\n *\n * @param value - The value to check.\n * @returns True if the value is present.\n */\nexport function isDefined<T>(value: Nullable<T> | false): value is T {\n if (value === undefined || value === null || value === false) return false;\n if (typeof value === \"string\") return value.trim() !== \"\";\n if (Array.isArray(value)) return value.some((element) => isDefined(element));\n\n if (typeof value === \"object\") {\n const prototype = Reflect.getPrototypeOf(value);\n if (prototype !== Object.prototype && prototype !== null) return true;\n\n return Object.keys(value).length > 0;\n }\n\n return true;\n}\n\n/**\n * Converts a string to another case.\n *\n * @param value - The string to convert.\n * @param format - The case to convert to.\n * @returns The converted string.\n */\nexport function convertCase(value: string, format: \"kebab\" | \"snake\" | \"camel\" | \"pascal\" | \"title\" | \"sentence\") {\n const words = value\n .replaceAll(/(?<lower>[a-z0-9])(?<upper>[A-Z])/gu, \"$<lower> $<upper>\")\n .replaceAll(/[-_\\s]+/gu, \" \")\n .trim()\n .toLowerCase();\n\n switch (format) {\n case \"kebab\": {\n return words.replaceAll(/\\s+/gu, \"-\");\n }\n case \"snake\": {\n return words.replaceAll(/\\s+/gu, \"_\");\n }\n case \"camel\": {\n return words.replaceAll(/\\s+(?<character>.)/gu, (_match, character: string) => character.toUpperCase());\n }\n case \"pascal\": {\n return words.replaceAll(/(?:^|\\s+)(?<character>.)/gu, (_match, character: string) => character.toUpperCase());\n }\n case \"title\": {\n return words.replaceAll(/\\b\\w/gu, (character) => character.toUpperCase());\n }\n case \"sentence\": {\n return words.replaceAll(/^(?<character>.)/gu, (character) => character.toUpperCase());\n }\n default: {\n return value;\n }\n }\n}\n\n/**\n * Checks whether a value is an object whose keys can be read.\n *\n * @param value - The value to check.\n * @returns True if the value is an object.\n */\nexport function isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null;\n}\n\n/**\n * Reads a nested value by following a path of keys.\n *\n * @param value - The object to read from.\n * @param path - The keys to follow.\n * @returns The value, or undefined when the path doesn't exist.\n */\nexport function readPath(value: unknown, path: string[]) {\n let current: unknown = value;\n\n for (const segment of path) {\n if (!isRecord(current)) return undefined;\n\n current = current[segment];\n }\n\n return current;\n}\n","import { isDefined, isRecord } from \"@repo/lib/utils\";\nimport { stegaClean } from \"@sanity/client/stega\";\n\n/** One element in a drawing: its name, its attributes, and any children, which may include text. */\nexport type IconElement = [element: string, attributes: Record<string, string>, children?: (IconElement | string)[]];\n\n/** An icon's drawing, stored as a tree of elements rather than a component. */\nexport type IconNode = IconElement[];\n\n/** Attributes for the SVG around a drawing's elements. */\nexport type IconRoot = Record<string, string>;\n\n/** An icon's elements together with the SVG attributes they're drawn inside. */\nexport interface IconDrawing {\n /** Attributes for the SVG around the elements. */\n root: IconRoot;\n /** Elements the icon is drawn from. */\n node: IconNode;\n}\n\n/**\n * SVG elements a drawing may contain: everything that draws, paints, clips, masks, or filters. Anything that runs\n * code, embeds other content, links away, loads a file, animates, or styles the page around it is left out.\n */\nconst iconElements: ReadonlySet<string> = new Set([\n \"circle\",\n \"clipPath\",\n \"defs\",\n \"ellipse\",\n \"feBlend\",\n \"feColorMatrix\",\n \"feComponentTransfer\",\n \"feComposite\",\n \"feConvolveMatrix\",\n \"feDiffuseLighting\",\n \"feDisplacementMap\",\n \"feDistantLight\",\n \"feDropShadow\",\n \"feFlood\",\n \"feFuncA\",\n \"feFuncB\",\n \"feFuncG\",\n \"feFuncR\",\n \"feGaussianBlur\",\n \"feMerge\",\n \"feMergeNode\",\n \"feMorphology\",\n \"feOffset\",\n \"fePointLight\",\n \"feSpecularLighting\",\n \"feSpotLight\",\n \"feTile\",\n \"feTurbulence\",\n \"filter\",\n \"g\",\n \"line\",\n \"linearGradient\",\n \"marker\",\n \"mask\",\n \"path\",\n \"pattern\",\n \"polygon\",\n \"polyline\",\n \"radialGradient\",\n \"rect\",\n \"stop\",\n \"symbol\",\n \"text\",\n \"textPath\",\n \"tspan\",\n \"use\",\n]);\n\n/** Attributes that point at another element by URL, which must point inside the drawing. */\nconst linkAttributes = new Set([\"href\", \"xlinkHref\"]);\n\n/** A reference to another element in an attribute value, such as `url(#fade)`. */\nconst urlPattern = /url\\((?<reference>[^)]*)\\)/gu;\n\n/** Attributes every drawing's SVG carries, whichever library it came from. */\nexport const iconSvgAttributes = { xmlns: \"http://www.w3.org/2000/svg\", width: 24, height: 24 } as const;\n\n/**\n * Checks whether a value is a set of attributes, each with a text value.\n *\n * @param value - The value to check.\n * @returns True if the value is a set of attributes.\n */\nfunction isAttributes(value: unknown): value is Record<string, string> {\n return isRecord(value) && Object.values(value).every((attribute) => typeof attribute === \"string\");\n}\n\n/**\n * Checks whether a value is an element in a drawing, with text attributes and valid children.\n *\n * @param value - The value to check.\n * @returns True if the value is an element.\n */\nfunction isIconElement(value: unknown): value is IconElement {\n if (!Array.isArray(value) || value.length < 2 || value.length > 3) return false;\n\n const parts: unknown[] = value;\n const [name, attributes, children] = parts;\n if (typeof name !== \"string\" || !isAttributes(attributes)) return false;\n\n return (\n !isDefined(children) ||\n (Array.isArray(children) && children.every((child) => typeof child === \"string\" || isIconElement(child)))\n );\n}\n\n/**\n * Finds why an element's attributes can't be drawn safely.\n *\n * @param attributes - The attributes.\n * @returns The problem, or undefined when the attributes are safe.\n */\nfunction findAttributeProblem(attributes: Record<string, string>) {\n for (const [name, value] of Object.entries(attributes)) {\n if (/^on/iu.test(name)) return `has an event handler (\\`${name}\\`)`;\n if (!/^[a-zA-Z][a-zA-Z0-9]*$/u.test(name)) return `has an unknown attribute (\\`${name}\\`)`;\n if (/javascript:/iu.test(value)) return \"runs a script\";\n\n if (linkAttributes.has(name) && !value.startsWith(\"#\")) return \"links outside the icon\";\n\n if (value.includes(\"url(\")) {\n const references = [...value.matchAll(urlPattern)];\n const outside = references.some(\n ({ groups }) => !(groups?.[\"reference\"]?.trim().replace(/^[\"']/u, \"\").startsWith(\"#\") ?? false),\n );\n\n if (outside || value.split(\"url(\").length - 1 !== references.length) {\n return \"refers to something outside the icon\";\n }\n }\n }\n\n return undefined;\n}\n\n/**\n * Finds why part of a drawing can't be drawn safely.\n *\n * @param node - The elements to check.\n * @returns The problem, or undefined when every element is safe.\n */\nfunction findNodeProblem(node: (IconElement | string)[]): string | undefined {\n for (const child of node) {\n if (typeof child === \"string\") continue;\n\n const [name, attributes, children] = child;\n if (!iconElements.has(name)) return `uses the \\`<${name}>\\` element`;\n\n const problem = findAttributeProblem(attributes) ?? (isDefined(children) ? findNodeProblem(children) : undefined);\n if (isDefined(problem)) return problem;\n }\n\n return undefined;\n}\n\n/**\n * Finds why a drawing can't be drawn safely: an element or attribute that could run code, load something, or reach\n * outside the icon. The same check guards the build step's output and every stored value before it's drawn.\n *\n * @param drawing - The drawing to check.\n * @returns The problem, or undefined when the drawing is safe.\n */\nexport function findDrawingProblem({ root, node }: IconDrawing) {\n if (!isDefined(node)) return \"draws nothing\";\n\n return findAttributeProblem(root) ?? findNodeProblem(node);\n}\n\n/**\n * Reads a drawing's elements from an already parsed value, such as a converted set.\n *\n * @param value - The value to read.\n * @returns The elements, or undefined when the value isn't a list of them.\n */\nexport function parseIconNode(value: unknown) {\n return Array.isArray(value) && value.every((element) => isIconElement(element)) ? value : undefined;\n}\n\n/**\n * Reads an SVG root from an already parsed value.\n *\n * @param value - The value to read.\n * @returns The root, or undefined when the value isn't one.\n */\nexport function parseIconRoot(value: unknown) {\n return isAttributes(value) ? value : undefined;\n}\n\n/**\n * Parses stored JSON.\n *\n * @param value - The stored text.\n * @returns The parsed value, or undefined when the text isn't JSON.\n */\nfunction parseJson(value: string): unknown {\n try {\n return JSON.parse(value);\n } catch {\n return undefined;\n }\n}\n\n/**\n * Reads a drawing back from its stored form, removing stega characters first.\n *\n * @param value - The stored drawing.\n * @returns The drawing, or undefined when nothing readable and safe was stored.\n */\nexport function resolveIconDrawing(value: string | undefined): IconDrawing | undefined {\n const cleaned = stegaClean(value);\n if (!isDefined(cleaned)) return undefined;\n\n const stored = parseJson(cleaned);\n if (!isRecord(stored)) return undefined;\n\n const root = parseIconRoot(stored[\"root\"]);\n const node = parseIconNode(stored[\"node\"]);\n if (!isDefined(root) || !isDefined(node)) return undefined;\n\n const drawing = { root, node };\n\n return isDefined(findDrawingProblem(drawing)) ? undefined : drawing;\n}\n\n/**\n * Converts a drawing to its stored form.\n *\n * @param drawing - The drawing.\n * @returns The drawing as a string.\n */\nexport function serializeIconDrawing(drawing: IconDrawing) {\n return JSON.stringify({ root: drawing.root, node: drawing.node });\n}\n"],"mappings":";;;;;;;;AAUA,SAAgBE,UAAaC,OAAwC;CACnE,IAAIA,SAAiC,QAAQA,UAAU,IAAO,OAAO;CACrE,IAAI,OAAOA,SAAU,UAAU,OAAOA,MAAME,KAAK,MAAM;CACvD,IAAIC,MAAMC,QAAQJ,KAAK,GAAG,OAAOA,MAAMK,MAAMC,YAAYP,UAAUO,OAAO,CAAC;CAE3E,IAAI,OAAON,SAAU,UAAU;EAC7B,IAAMO,YAAYC,QAAQC,eAAeT,KAAK;EAG9C,OAFIO,cAAcG,OAAOH,aAAaA,cAAc,QAE7CG,OAAOC,KAAKX,KAAK,CAAC,CAACY,SAAS;CACrC;CAEA,OAAO;AACT;;;;;;;;AASA,SAAgBC,YAAYb,OAAec,QAAuE;CAChH,IAAMC,QAAQf,MACXgB,WAAW,uCAAuC,mBAAmB,CAAC,CACtEA,WAAW,aAAa,GAAG,CAAC,CAC5Bd,KAAK,CAAC,CACNe,YAAY;CAEf,QAAQH,QAAR;EACE,KAAK,SACH,OAAOC,MAAMC,WAAW,SAAS,GAAG;EAEtC,KAAK,SACH,OAAOD,MAAMC,WAAW,SAAS,GAAG;EAEtC,KAAK,SACH,OAAOD,MAAMC,WAAW,yBAAyBE,QAAQC,cAAsBA,UAAUC,YAAY,CAAC;EAExG,KAAK,UACH,OAAOL,MAAMC,WAAW,+BAA+BE,QAAQC,cAAsBA,UAAUC,YAAY,CAAC;EAE9G,KAAK,SAC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AOiC,KAAKC,MAAMlC,KAAK;CACzB,QAAQ;EACN;CACF;AACF;;;;;;;AAQA,SAAgBmC,mBAAmBnC,OAAoD;CACrF,IAAMoC,UAAU1D,WAAWsB,KAAK;CAChC,IAAI,CAACxB,UAAU4D,OAAO,GAAG;CAEzB,IAAMC,SAASL,UAAUI,OAAO;CAChC,IAAI,CAAC3D,SAAS4D,MAAM,GAAG;CAEvB,IAAMlD,OAAO4C,cAAcM,OAAOM,IAAO,GACnCvD,OAAO0C,cAAcO,OAAOO,IAAO;CACzC,IAAI,CAACpE,UAAUW,IAAI,KAAK,CAACX,UAAUY,IAAI,GAAG;CAE1C,IAAMkD,UAAU;EAAEnD;EAAMC;CAAK;CAE7B,OAAOZ,UAAUqD,mBAAmBS,OAAO,CAAC,IAAIZ,KAAAA,IAAYY;AAC9D;;;;;;;AAQA,SAAgBC,qBAAqBD,SAAsB;CACzD,OAAOL,KAAKO,UAAU;EAAErD,MAAMmD,QAAQnD;EAAMC,MAAMkD,QAAQlD;CAAK,CAAC;AAClE"}
@@ -1,5 +1,5 @@
1
- import { n as isDefined, r as isRecord } from "./utils-COPacfAq.js";
2
- import { n as createCustomAdapter, t as iconAdapters } from "./adapters-Bx_MyEX_.js";
1
+ import { c as isDefined, l as isRecord } from "./nodes-Bn7fLVZO.js";
2
+ import { n as createCustomAdapter, t as iconAdapters } from "./adapters-Dw6yeA3A.js";
3
3
  import { parentPort, workerData } from "node:worker_threads";
4
4
  /**
5
5
  * Reads one library style in a worker thread, so every package is imported afresh, and posts the icons back.
package/dist/render.js CHANGED
@@ -1,6 +1,5 @@
1
- import { n as isDefined } from "./utils-COPacfAq.js";
2
- import { a as resolveIconDrawing, o as serializeIconDrawing } from "./nodes-DAzj56Xn.js";
3
- import { o as Drawing, r as requestLibrary, t as iconTypeName } from "./types-v7Qz7ogk.js";
1
+ import { a as resolveIconDrawing, c as isDefined, o as serializeIconDrawing } from "./nodes-Bn7fLVZO.js";
2
+ import { o as Drawing, r as requestLibrary, t as iconTypeName } from "./types-CmTEhJK6.js";
4
3
  import { jsx } from "react/jsx-runtime";
5
4
  /**
6
5
  * Draws a stored icon from the shapes saved with it, without loading an icon library.
@@ -1 +1 @@
1
- {"version":3,"file":"render.js","names":["ComponentProps","Drawing","resolveIconDrawing","SanityIcon","SanityIconProps","Omit","value","Icon","props","node","isDefined","requestLibrary","serializeIconDrawing","iconTypeName","IconLibraryId","SanityIcon","SanityIconName","SanityIconStyle","SanityIconLookup","library","Library","style","name","getIcon","Promise","icons","icon","find","candidate","undefined","_type","node","drawing"],"sources":["../src/components/icon.tsx","../src/lib/lookup.ts"],"sourcesContent":["// Consumers render this in server components, where the compiler's memo cache hook can't run.\n\"use no memo\";\n\nimport type { ComponentProps } from \"react\";\n\nimport { Drawing } from \"@/components/drawing\";\nimport { resolveIconDrawing } from \"@/lib/nodes\";\nimport type { SanityIcon } from \"@/types\";\n\n/**\n * Props for drawing a stored icon: an SVG element's props plus the stored value.\n *\n * @public\n */\nexport type SanityIconProps = Omit<ComponentProps<\"svg\">, \"children\"> & {\n /** Stored icon to draw. */\n value: SanityIcon | undefined;\n};\n\n/**\n * Draws a stored icon from the shapes saved with it, without loading an icon library.\n *\n * @returns The icon, or nothing when the value is missing or unreadable.\n * @public\n */\nexport function Icon({ value, ...props }: SanityIconProps) {\n return <Drawing drawing={resolveIconDrawing(value?.node)} {...props} />;\n}\n","import { isDefined } from \"@repo/lib/utils\";\n\nimport { requestLibrary } from \"@/lib/library\";\nimport { serializeIconDrawing } from \"@/lib/nodes\";\nimport { iconTypeName } from \"@/types\";\nimport type { IconLibraryId, SanityIcon, SanityIconName, SanityIconStyle } from \"@/types\";\n\n/**\n * An icon to look up by name, where the style and name are checked against the library.\n *\n * @public\n */\nexport type SanityIconLookup = {\n [Library in IconLibraryId]: {\n /** Identifier of the icon library, such as `phosphor`. */\n library: Library;\n /** Identifier of the library style, such as `bold`. Defaults to the library's first style. */\n style?: SanityIconStyle<Library>;\n /** Name of the icon in its library. */\n name: SanityIconName<Library>;\n };\n}[IconLibraryId];\n\n/**\n * Looks an icon up by name in an installed library, for an icon the site chooses rather than an author.\n *\n * @param lookup - The library, style, and name of the icon.\n * @returns The icon as the Studio stores it, or undefined when the build step hasn't run or the library, style, or\n * name isn't installed.\n * @public\n */\nexport async function getIcon({ library, style, name }: SanityIconLookup): Promise<SanityIcon | undefined> {\n const { icons } = await requestLibrary(library, style);\n const icon = icons?.find((candidate) => candidate.name === name);\n if (!isDefined(icon)) return undefined;\n\n return {\n _type: iconTypeName,\n library,\n ...(isDefined(style) && { style }),\n name,\n node: serializeIconDrawing(icon.drawing),\n };\n}\n"],"mappings":";;;;;;;;;;AAyBA,SAAgBO,KAAK,EAAED,OAAO,GAAGE,SAA0B;CACzD,OAAO,oBAAC,SAAD;EAAS,SAASN,mBAAmBI,OAAOG,IAAI;EAAG,GAAID;CAAM,CAAA;AACtE;;;;;;;;;ACIA,eAAsBe,QAAQ,EAAEJ,SAASE,OAAOC,QAA2D;CACzG,IAAM,EAAEG,UAAU,MAAMd,eAAeQ,SAASE,KAAK,GAC/CK,OAAOD,OAAOE,MAAMC,cAAcA,UAAUN,SAASA,IAAI;CAC/D,IAAKZ,UAAUgB,IAAI,GAEnB,OAAO;EACLI,OAAOjB;EACPM;EACA,GAAIT,UAAUW,KAAK,KAAK,EAAEA,MAAM;EAChCC;EACAS,MAAMnB,qBAAqBc,KAAKM,OAAO;CACzC;AACF"}
1
+ {"version":3,"file":"render.js","names":["ComponentProps","Drawing","resolveIconDrawing","SanityIcon","SanityIconProps","Omit","value","Icon","props","node","isDefined","requestLibrary","serializeIconDrawing","iconTypeName","IconLibraryId","SanityIcon","SanityIconName","SanityIconStyle","SanityIconLookup","library","Library","style","name","getIcon","Promise","icons","icon","find","candidate","undefined","_type","node","drawing"],"sources":["../src/components/icon.tsx","../src/lib/lookup.ts"],"sourcesContent":["// Consumers render this in server components, where the compiler's memo cache hook can't run.\n\"use no memo\";\n\nimport type { ComponentProps } from \"react\";\n\nimport { Drawing } from \"@/components/drawing\";\nimport { resolveIconDrawing } from \"@/lib/nodes\";\nimport type { SanityIcon } from \"@/types\";\n\n/**\n * Props for drawing a stored icon: an SVG element's props plus the stored value.\n *\n * @public\n */\nexport type SanityIconProps = Omit<ComponentProps<\"svg\">, \"children\"> & {\n /** Stored icon to draw. */\n value: SanityIcon | undefined;\n};\n\n/**\n * Draws a stored icon from the shapes saved with it, without loading an icon library.\n *\n * @returns The icon, or nothing when the value is missing or unreadable.\n * @public\n */\nexport function Icon({ value, ...props }: SanityIconProps) {\n return <Drawing drawing={resolveIconDrawing(value?.node)} {...props} />;\n}\n","import { isDefined } from \"@repo/lib/utils\";\n\nimport { requestLibrary } from \"@/lib/library\";\nimport { serializeIconDrawing } from \"@/lib/nodes\";\nimport { iconTypeName } from \"@/types\";\nimport type { IconLibraryId, SanityIcon, SanityIconName, SanityIconStyle } from \"@/types\";\n\n/**\n * An icon to look up by name, where the style and name are checked against the library.\n *\n * @public\n */\nexport type SanityIconLookup = {\n [Library in IconLibraryId]: {\n /** Identifier of the icon library, such as `phosphor`. */\n library: Library;\n /** Identifier of the library style, such as `bold`. Defaults to the library's first style. */\n style?: SanityIconStyle<Library>;\n /** Name of the icon in its library. */\n name: SanityIconName<Library>;\n };\n}[IconLibraryId];\n\n/**\n * Looks an icon up by name in an installed library, for an icon the site chooses rather than an author.\n *\n * @param lookup - The library, style, and name of the icon.\n * @returns The icon as the Studio stores it, or undefined when the build step hasn't run or the library, style, or\n * name isn't installed.\n * @public\n */\nexport async function getIcon({ library, style, name }: SanityIconLookup): Promise<SanityIcon | undefined> {\n const { icons } = await requestLibrary(library, style);\n const icon = icons?.find((candidate) => candidate.name === name);\n if (!isDefined(icon)) return undefined;\n\n return {\n _type: iconTypeName,\n library,\n ...(isDefined(style) && { style }),\n name,\n node: serializeIconDrawing(icon.drawing),\n };\n}\n"],"mappings":";;;;;;;;;AAyBA,SAAgBO,KAAK,EAAED,OAAO,GAAGE,SAA0B;CACzD,OAAO,oBAAC,SAAD;EAAS,SAASN,mBAAmBI,OAAOG,IAAI;EAAG,GAAID;CAAM,CAAA;AACtE;;;;;;;;;ACIA,eAAsBe,QAAQ,EAAEJ,SAASE,OAAOC,QAA2D;CACzG,IAAM,EAAEG,UAAU,MAAMd,eAAeQ,SAASE,KAAK,GAC/CK,OAAOD,OAAOE,MAAMC,cAAcA,UAAUN,SAASA,IAAI;CAC/D,IAAKZ,UAAUgB,IAAI,GAEnB,OAAO;EACLI,OAAOjB;EACPM;EACA,GAAIT,UAAUW,KAAK,KAAK,EAAEA,MAAM;EAChCC;EACAS,MAAMnB,qBAAqBc,KAAKM,OAAO;CACzC;AACF"}
@@ -1,12 +1,64 @@
1
1
  import { n as pluginName } from "./defaults-BEzCWZtH.js";
2
- import { n as isDefined, r as isRecord } from "./utils-COPacfAq.js";
3
- import { t as parseIconSet } from "./sets-BFcRq7dc.js";
4
- import { i as registryModulePath } from "./registry-B0Dxiwhh.js";
5
- import { a as readDeclaredPackages, c as convertIcon, n as createCustomAdapter, o as readJson, r as findPackage, s as readPluginBuild, t as iconAdapters } from "./adapters-Bx_MyEX_.js";
2
+ import { c as isDefined, l as isRecord } from "./nodes-Bn7fLVZO.js";
3
+ import { n as getIconSetKey, t as parseIconSet } from "./sets-DH5UbUV_.js";
4
+ import { a as readDeclaredPackages, c as convertIcon, n as createCustomAdapter, o as readJson, r as findPackage, s as readPluginBuild, t as iconAdapters } from "./adapters-Dw6yeA3A.js";
6
5
  import path from "node:path";
7
6
  import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
7
+ import { realpathSync } from "node:fs";
8
+ import { fileURLToPath } from "node:url";
8
9
  import { once } from "node:events";
9
10
  import { Worker } from "node:worker_threads";
11
+ /**
12
+ * Resolves symbolic links in a path, so a package linked into `node_modules` matches its real location.
13
+ *
14
+ * @param file - The path.
15
+ * @returns The real path, or the path unchanged when it doesn't exist.
16
+ */
17
+ function resolveRealPath(file) {
18
+ try {
19
+ return realpathSync(file);
20
+ } catch {
21
+ return file;
22
+ }
23
+ }
24
+ /**
25
+ * Path of the placeholder registry module the Studio imports, which the build step replaces. The build step's own
26
+ * code is published next to it, so the path is found from this file's location.
27
+ */
28
+ const registryModulePath = resolveRealPath(fileURLToPath(new URL("sets.js", import.meta.url)));
29
+ /**
30
+ * Checks whether a module the bundler is loading is the placeholder registry.
31
+ *
32
+ * @param id - The module's path, possibly followed by a query.
33
+ * @returns Whether it's the placeholder.
34
+ */
35
+ function isRegistryModule(id) {
36
+ let [file] = id.split("?");
37
+ return isDefined(file) && resolveRealPath(file) === registryModulePath;
38
+ }
39
+ /**
40
+ * Writes the module that replaces the placeholder registry, with a loader for each installed library style, so each
41
+ * set is only downloaded when a picker for it opens.
42
+ *
43
+ * @param libraries - Every library the build step knows.
44
+ * @param importFor - The specifier the bundler imports a set from, given its key.
45
+ * @returns The module's code.
46
+ */
47
+ function createRegistryModule(libraries, importFor) {
48
+ let loaders = libraries.flatMap(({ adapter, styles }) => styles.map(({ style }) => {
49
+ let key = getIconSetKey(adapter.library, style);
50
+ return `${JSON.stringify(key)}: () => import(${JSON.stringify(importFor(key))})`;
51
+ })), info = Object.fromEntries(libraries.map(({ adapter, styles, listed, sitePackage }) => [adapter.library, {
52
+ label: adapter.label,
53
+ packageName: adapter.packageName ?? adapter.packageExample ?? adapter.library,
54
+ ...isDefined(adapter.packagePrefix) && { packagePrefix: adapter.packagePrefix },
55
+ styles: isDefined(styles) ? styles.map(({ style }) => style) : adapter.styles,
56
+ listed,
57
+ installed: isDefined(styles),
58
+ ...isDefined(sitePackage) && { sitePackage }
59
+ }]));
60
+ return [`const sets = {\n ${loaders.join(",\n ")}\n};`, `export const iconRegistry = { ready: true, sets, libraries: ${JSON.stringify(info)} };`].join("\n");
61
+ }
10
62
  /** Types file the plugin reads icon names from, published next to the placeholder registry. */
11
63
  const namesFile = path.join(path.dirname(registryModulePath), "names.d.ts");
12
64
  /**
@@ -254,6 +306,6 @@ function describeReport(label, style, report) {
254
306
  ...more
255
307
  ].join("\n");
256
308
  }
257
- export { writeIconNames as a, loadIconSet as i, detectLibraries as n, listRegistryDependencies as r, describeReport as t };
309
+ export { writeIconNames as a, registryModulePath as c, loadIconSet as i, detectLibraries as n, createRegistryModule as o, listRegistryDependencies as r, isRegistryModule as s, describeReport as t };
258
310
 
259
- //# sourceMappingURL=sets-B2lHNI7c.js.map
311
+ //# sourceMappingURL=sets-B5arQvrZ.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sets-B5arQvrZ.js","names":["realpathSync","fileURLToPath","isDefined","DetectedLibrary","getIconSetKey","IconLibraryInfo","resolveRealPath","file","registryModulePath","URL","import","meta","url","isRegistryModule","id","split","createRegistryModule","libraries","importFor","key","loaders","flatMap","adapter","styles","map","style","library","JSON","stringify","info","Record","Object","fromEntries","listed","sitePackage","label","packageName","packageExample","packagePrefix","installed","join","readFile","rename","writeFile","path","isDefined","registryModulePath","pluginName","namesFile","join","dirname","writeIconNames","names","Map","Set","entries","toSorted","first","second","localeCompare","map","library","icons","union","name","JSON","stringify","content","current","catch","temporary","process","pid","once","mkdir","writeFile","path","Worker","isDefined","isRecord","createCustomAdapter","iconAdapters","IconAdapter","SourceIcon","convertIcon","InstalledPackage","findPackage","readDeclaredPackages","readJson","readPluginBuild","IconSet","IconSetIcon","parseIconSet","IconSetReport","total","skipped","name","reason","duration","DetectedStyle","style","installed","DetectedLibrary","adapter","styles","listed","sitePackage","folder","IconSetContext","root","cacheDir","detectLibraries","custom","Record","Promise","declared","known","all","map","packageName","packagePrefix","packagePattern","names","filter","startsWith","toSorted","found","slice","length","flat","has","undefined","find","test","folders","Object","entries","library","directory","resolve","version","findCommonRoot","icons","NonNullable","counts","Map","count","key","JSON","stringify","set","get","common","values","first","second","isSourceIcon","value","keywords","svg","Array","isArray","every","keyword","readSources","candidate","worker","URL","import","meta","url","workerData","env","process","NODE_ENV","received","sources","source","terminate","convertIconSet","started","performance","now","report","converted","icon","problem","push","iconRoot","Math","round","parseReport","flatMap","entry","loadIconSet","context","cacheable","cacheFile","join","replaceAll","cached","dirname","recursive","listRegistryDependencies","libraries","files","describeReport","label","kept","toLocaleString","timing","summary","shown","hidden","more","\"total\"","\"skipped\"","\"name\"","\"reason\"","\"set\"","\"report\""],"sources":["../src/build/registry.ts","../src/build/names.ts","../src/build/sets.ts"],"sourcesContent":["import { realpathSync } from \"node:fs\";\nimport { fileURLToPath } from \"node:url\";\n\nimport { isDefined } from \"@repo/lib/utils\";\n\nimport type { DetectedLibrary } from \"@/build/sets\";\nimport { getIconSetKey } from \"@/lib/registry\";\nimport type { IconLibraryInfo } from \"@/lib/sets\";\n\n/**\n * Resolves symbolic links in a path, so a package linked into `node_modules` matches its real location.\n *\n * @param file - The path.\n * @returns The real path, or the path unchanged when it doesn't exist.\n */\nfunction resolveRealPath(file: string) {\n try {\n return realpathSync(file);\n } catch {\n return file;\n }\n}\n\n/**\n * Path of the placeholder registry module the Studio imports, which the build step replaces. The build step's own\n * code is published next to it, so the path is found from this file's location.\n */\nexport const registryModulePath = resolveRealPath(fileURLToPath(new URL(\"sets.js\", import.meta.url)));\n\n/**\n * Checks whether a module the bundler is loading is the placeholder registry.\n *\n * @param id - The module's path, possibly followed by a query.\n * @returns Whether it's the placeholder.\n */\nexport function isRegistryModule(id: string) {\n const [file] = id.split(\"?\");\n\n return isDefined(file) && resolveRealPath(file) === registryModulePath;\n}\n\n/**\n * Writes the module that replaces the placeholder registry, with a loader for each installed library style, so each\n * set is only downloaded when a picker for it opens.\n *\n * @param libraries - Every library the build step knows.\n * @param importFor - The specifier the bundler imports a set from, given its key.\n * @returns The module's code.\n */\nexport function createRegistryModule(libraries: DetectedLibrary[], importFor: (key: string) => string) {\n const loaders = libraries.flatMap(({ adapter, styles }) =>\n styles.map(({ style }) => {\n const key = getIconSetKey(adapter.library, style);\n\n return `${JSON.stringify(key)}: () => import(${JSON.stringify(importFor(key))})`;\n }),\n );\n\n const info: Record<string, IconLibraryInfo> = Object.fromEntries(\n libraries.map(({ adapter, styles, listed, sitePackage }) => [\n adapter.library,\n {\n label: adapter.label,\n packageName: adapter.packageName ?? adapter.packageExample ?? adapter.library,\n ...(isDefined(adapter.packagePrefix) && { packagePrefix: adapter.packagePrefix }),\n styles: isDefined(styles) ? styles.map(({ style }) => style) : adapter.styles,\n listed,\n installed: isDefined(styles),\n ...(isDefined(sitePackage) && { sitePackage }),\n },\n ]),\n );\n\n return [\n `const sets = {\\n ${loaders.join(\",\\n \")}\\n};`,\n `export const iconRegistry = { ready: true, sets, libraries: ${JSON.stringify(info)} };`,\n ].join(\"\\n\");\n}\n","import { readFile, rename, writeFile } from \"node:fs/promises\";\nimport path from \"node:path\";\n\nimport { isDefined } from \"@repo/lib/utils\";\n\nimport { registryModulePath } from \"@/build/registry\";\nimport { pluginName } from \"@/config/defaults\";\n\n/** Types file the plugin reads icon names from, published next to the placeholder registry. */\nconst namesFile = path.join(path.dirname(registryModulePath), \"names.d.ts\");\n\n/**\n * Writes the installed icon names into the plugin's own types, so options that list icons are checked against them.\n * The file is replaced rather than edited, because pnpm shares a package's files between projects.\n *\n * @param names - Icon names keyed by library.\n */\nexport async function writeIconNames(names: Map<string, Set<string>>) {\n const entries = [...names]\n .toSorted(([first], [second]) => first.localeCompare(second))\n .map(([library, icons]) => {\n const union = [...icons].toSorted().map((name) => JSON.stringify(name));\n\n return ` ${JSON.stringify(library)}: ${isDefined(union) ? union.join(\" | \") : \"never\"};`;\n });\n\n const content = [\n `// Written by ${pluginName}'s build step from the project's installed icon libraries.`,\n \"export type SanityIconNames = {\",\n ...entries,\n \"};\",\n \"\",\n ].join(\"\\n\");\n\n const current = await readFile(namesFile, \"utf8\").catch(() => \"\");\n if (current === content) return;\n\n const temporary = `${namesFile}.${process.pid}.tmp`;\n await writeFile(temporary, content);\n await rename(temporary, namesFile);\n}\n","import { once } from \"node:events\";\nimport { mkdir, writeFile } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { Worker } from \"node:worker_threads\";\n\nimport { isDefined, isRecord } from \"@repo/lib/utils\";\n\nimport { createCustomAdapter } from \"@/build/adapters/custom\";\nimport { iconAdapters } from \"@/build/adapters/index\";\nimport type { IconAdapter } from \"@/build/adapters/types\";\nimport type { SourceIcon } from \"@/build/convert\";\nimport { convertIcon } from \"@/build/convert\";\nimport type { InstalledPackage } from \"@/build/packages\";\nimport { findPackage, readDeclaredPackages, readJson, readPluginBuild } from \"@/build/packages\";\nimport type { IconSet, IconSetIcon } from \"@/lib/sets\";\nimport { parseIconSet } from \"@/lib/sets\";\n\n/** What happened converting a set, for the build's log. */\nexport interface IconSetReport {\n /** Icons the library ships in the style. */\n total: number;\n /** Icons skipped, with why. */\n skipped: { name: string; reason: string }[];\n /** Time the conversion took, in milliseconds, or 0 when it came from the cache. */\n duration: number;\n}\n\n/** One installed style of a library, and the package it's read from. */\nexport interface DetectedStyle {\n /** Identifier of the style. */\n style: string;\n /** The package the style is read from. */\n installed: InstalledPackage;\n}\n\n/** A library found in the project, and where each of its styles is installed. */\nexport interface DetectedLibrary {\n /** How to read the library. */\n adapter: IconAdapter;\n /** The styles the project has installed, empty when it has none. */\n styles: DetectedStyle[];\n /** Whether the project's `package.json` lists the package the library is read from, installed or not. */\n listed: boolean;\n /**\n * Another package of the library the project lists, such as its React version, or undefined when there's none or the\n * library's own package is listed.\n */\n sitePackage?: string;\n /** Folder of the project's own icons, relative to the project, or undefined for a known library. */\n folder?: string;\n}\n\n/** Where the build step reads libraries from and caches conversions. */\nexport interface IconSetContext {\n /** The project folder. */\n root: string;\n /** Folder for cached conversions, or undefined to convert every time. */\n cacheDir: string | undefined;\n}\n\n/**\n * Finds every library the project can use: known libraries whose package it lists and has installed, and its own icon\n * folders. Only listed packages count, so a package that's only there because another one depends on it is ignored.\n *\n * @param root - The project folder.\n * @param custom - The project's own icon folders, keyed by identifier.\n * @returns Every library the build step knows, with where it's installed.\n */\nexport async function detectLibraries(root: string, custom: Record<string, string> = {}): Promise<DetectedLibrary[]> {\n const declared = await readDeclaredPackages(root);\n\n const known = await Promise.all(\n iconAdapters.map(async (adapter) => {\n const { packageName, packagePrefix, packagePattern } = adapter;\n\n if (isDefined(packagePrefix)) {\n const names = [...declared].filter((name) => name.startsWith(packagePrefix)).toSorted();\n const found = await Promise.all(\n names.map(async (name) => {\n const installed = await findPackage(root, name);\n\n return isDefined(installed) ? [{ style: name.slice(packagePrefix.length), installed }] : [];\n }),\n );\n\n return { adapter, styles: found.flat(), listed: isDefined(names) };\n }\n\n const listed = isDefined(packageName) && declared.has(packageName);\n const installed = listed ? await findPackage(root, packageName) : undefined;\n const styles = isDefined(installed) ? adapter.styles.map((style) => ({ style, installed })) : [];\n const sitePackage =\n listed || !isDefined(packagePattern)\n ? undefined\n : [...declared].toSorted().find((name) => packagePattern.test(name));\n\n return { adapter, styles, listed, ...(isDefined(sitePackage) && { sitePackage }) };\n }),\n );\n\n const folders = Object.entries(custom).map(([library, folder]) => ({\n adapter: createCustomAdapter(library, folder),\n listed: true,\n folder,\n styles: [\n { style: \"default\", installed: { name: library, directory: path.resolve(root, folder), version: \"custom\" } },\n ],\n }));\n\n return [...known, ...folders];\n}\n\n/**\n * Picks the root most icons in a set share, so only the others need their own.\n *\n * @param icons - The converted icons.\n * @returns The most common root.\n */\nfunction findCommonRoot(icons: (IconSetIcon & { root: NonNullable<IconSetIcon[\"root\"]> })[]) {\n const counts = new Map<string, { root: IconSet[\"root\"]; count: number }>();\n\n for (const { root } of icons) {\n const key = JSON.stringify(root);\n counts.set(key, { root, count: (counts.get(key)?.count ?? 0) + 1 });\n }\n\n const [common] = [...counts.values()].toSorted((first, second) => second.count - first.count);\n\n return common?.root ?? {};\n}\n\n/**\n * Checks whether a value is an icon as a worker read it from its library.\n *\n * @param value - The value to check.\n * @returns True if the value is a source icon.\n */\nfunction isSourceIcon(value: unknown): value is SourceIcon {\n if (!isRecord(value)) return false;\n\n const { name, keywords, svg } = value;\n\n return (\n typeof name === \"string\" &&\n Array.isArray(keywords) &&\n keywords.every((keyword) => typeof keyword === \"string\") &&\n typeof svg === \"string\"\n );\n}\n\n/**\n * Reads a library's icons in a fresh worker thread. A long-running bundler keeps every module it has imported, so an\n * icon package updated in place would otherwise be read from the old copy.\n *\n * @param library - The library and where it's installed.\n * @param style - The style to read.\n * @param root - The project folder.\n * @returns The icons as the library ships them.\n */\nasync function readSources(library: DetectedLibrary, style: string, root: string) {\n const { adapter, folder } = library;\n const installed = library.styles.find((candidate) => candidate.style === style)?.installed;\n if (!isDefined(installed)) return [];\n\n const worker = new Worker(new URL(\"read-worker.js\", import.meta.url), {\n workerData: { library: adapter.library, folder, style, root, directory: installed.directory },\n // Libraries' components render with React's production build, which writes the same markup without warnings.\n env: { ...process.env, NODE_ENV: \"production\" },\n });\n\n try {\n const received: unknown[] = await once(worker, \"message\");\n const [sources] = received;\n\n return Array.isArray(sources) ? sources.filter((source) => isSourceIcon(source)) : [];\n } finally {\n void worker.terminate();\n }\n}\n\n/**\n * Converts one style of a library into a set, reporting anything skipped.\n *\n * @param library - The library and where it's installed.\n * @param style - The style to convert.\n * @param root - The project folder.\n * @returns The set and its report.\n */\nasync function convertIconSet(library: DetectedLibrary, style: string, root: string) {\n const { adapter } = library;\n const started = performance.now();\n const sources = await readSources(library, style, root);\n\n const report: IconSetReport = { total: sources.length, skipped: [], duration: 0 };\n const converted: (IconSetIcon & { root: NonNullable<IconSetIcon[\"root\"]> })[] = [];\n\n for (const source of sources) {\n const { icon, problem } = convertIcon(source);\n\n if (isDefined(icon)) converted.push(icon);\n else if (isDefined(problem)) report.skipped.push({ name: source.name, reason: problem });\n }\n\n const common = findCommonRoot(converted);\n const set: IconSet = {\n library: adapter.library,\n style,\n root: common,\n icons: converted.map(({ root: iconRoot, ...icon }) =>\n JSON.stringify(iconRoot) === JSON.stringify(common) ? icon : { ...icon, root: iconRoot },\n ),\n };\n\n report.duration = Math.round(performance.now() - started);\n\n return { set, report };\n}\n\n/**\n * Reads a cached conversion's report.\n *\n * @param value - The cached report.\n * @returns The report, or undefined when the value isn't one.\n */\nfunction parseReport(value: unknown): IconSetReport | undefined {\n if (!isRecord(value) || typeof value[\"total\"] !== \"number\" || !Array.isArray(value[\"skipped\"])) return undefined;\n\n const skipped = value[\"skipped\"].flatMap((entry: unknown) =>\n isRecord(entry) && typeof entry[\"name\"] === \"string\" && typeof entry[\"reason\"] === \"string\"\n ? [{ name: entry[\"name\"], reason: entry[\"reason\"] }]\n : [],\n );\n\n return { total: value[\"total\"], skipped, duration: 0 };\n}\n\n/**\n * Loads a converted set, from the cache when the same package version was converted before.\n *\n * @param library - The library and where it's installed.\n * @param style - The style to load.\n * @param context - The project folder and cache folder.\n * @returns The set and its report.\n */\nexport async function loadIconSet(library: DetectedLibrary, style: string, context: IconSetContext) {\n const { adapter, folder } = library;\n const installed = library.styles.find((candidate) => candidate.style === style)?.installed;\n const cacheable = isDefined(context.cacheDir) && isDefined(installed) && !isDefined(folder);\n const cacheFile =\n cacheable && isDefined(context.cacheDir)\n ? path.join(\n context.cacheDir,\n \"driftime-icon\",\n `${adapter.library}-${style}-${installed.name.replaceAll(/[@/]/gu, \"_\")}-${installed.version}-${await readPluginBuild()}.json`,\n )\n : undefined;\n\n if (isDefined(cacheFile)) {\n const cached = await readJson(cacheFile);\n const set = isRecord(cached) ? parseIconSet(cached[\"set\"]) : undefined;\n const report = isRecord(cached) ? parseReport(cached[\"report\"]) : undefined;\n\n if (isDefined(set) && isDefined(report)) return { set, report };\n }\n\n const { set, report } = await convertIconSet(library, style, context.root);\n\n if (isDefined(cacheFile)) {\n await mkdir(path.dirname(cacheFile), { recursive: true });\n await writeFile(cacheFile, JSON.stringify({ set, report }));\n }\n\n return { set, report };\n}\n\n/**\n * Lists the files the registry is generated from, so the bundler regenerates it when a library is installed, removed,\n * or updated, instead of keeping a cached copy.\n *\n * @param root - The project folder.\n * @param libraries - Every library the build step knows.\n * @returns The files, and the folders of the project's own icons.\n */\nexport function listRegistryDependencies(root: string, libraries: DetectedLibrary[]) {\n const files = [path.join(root, \"package.json\")];\n const folders: string[] = [];\n\n for (const { styles, folder } of libraries) {\n for (const { installed } of styles) {\n if (isDefined(folder)) folders.push(installed.directory);\n else files.push(path.join(installed.directory, \"package.json\"));\n }\n }\n\n return { files, folders };\n}\n\n/**\n * Summarises a set's conversion for the build's log, listing the first few icons it skipped and why.\n *\n * @param label - Readable name of the library.\n * @param style - The style converted.\n * @param report - What happened.\n * @returns The summary, one line per skipped icon after the first.\n */\nexport function describeReport(label: string, style: string, report: IconSetReport) {\n const { total, skipped, duration } = report;\n const kept = total - skipped.length;\n const count = `${kept.toLocaleString(\"en-US\")} ${kept === 1 ? \"icon\" : \"icons\"}`;\n const timing = duration > 0 ? `converted in ${duration.toLocaleString(\"en-US\")} ms` : \"loaded from the cache\";\n const summary = `${label} (\\`${style}\\`): ${count} ${timing}`;\n if (!isDefined(skipped)) return `${summary}.`;\n\n const shown = skipped.slice(0, 5).map(({ name, reason }) => ` \\`${name}\\` ${reason}.`);\n const hidden = skipped.length - shown.length;\n const more = hidden > 0 ? [` …and ${hidden.toLocaleString(\"en-US\")} more.`] : [];\n\n return [`${summary}, ${skipped.length.toLocaleString(\"en-US\")} skipped:`, ...shown, ...more].join(\"\\n\");\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAeA,SAASM,gBAAgBC,MAAc;CACrC,IAAI;EACF,OAAOP,aAAaO,IAAI;CAC1B,QAAQ;EACN,OAAOA;CACT;AACF;;;;;AAMA,MAAaC,qBAAqBF,gBAAgBL,cAAc,IAAIQ,IAAI,WAAWC,YAAYE,GAAG,CAAC,CAAC;;;;;;;AAQpG,SAAgBC,iBAAiBC,IAAY;CAC3C,IAAM,CAACP,QAAQO,GAAGC,MAAM,GAAG;CAE3B,OAAOb,UAAUK,IAAI,KAAKD,gBAAgBC,IAAI,MAAMC;AACtD;;;;;;;;;AAUA,SAAgBQ,qBAAqBC,WAA8BC,WAAoC;CACrG,IAAME,UAAUH,UAAUI,SAAS,EAAEC,SAASC,aAC5CA,OAAOC,KAAK,EAAEC,YAAY;EACxB,IAA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G,aAAaqF,QAC/ByB,OAAOlH,QAAQC,QAAQiC,QAGvBmF,UAAU,GAAGJ,MAAK,MAAO3G,MAAK,OAAQ8C,GAF3B8D,KAAKC,eAAe,OAAO,EAAC,GAAID,SAAS,IAAI,SAAS,UAEtB,GADlC9G,WAAW,IAAI,gBAAgBA,SAAS+G,eAAe,OAAO,EAAC,OAAQ;CAEtF,IAAI,CAACnI,UAAUiB,OAAO,GAAG,OAAO,GAAGoH,QAAO;CAE1C,IAAMC,QAAQrH,QAAQgC,MAAM,GAAG,CAAC,CAAC,CAACT,KAAK,EAAEtB,MAAMC,aAAa,OAAOD,KAAI,KAAMC,OAAM,EAAG,GAChFoH,SAAStH,QAAQiC,SAASoF,MAAMpF,QAChCsF,OAAOD,SAAS,IAAI,CAAC,UAAUA,OAAOJ,eAAe,OAAO,EAAC,OAAQ,IAAI,CAAA;CAE/E,OAAO;EAAC,GAAGE,QAAO,IAAKpH,QAAQiC,OAAOiF,eAAe,OAAO,EAAC;EAAa,GAAGG;EAAO,GAAGE;CAAI,CAAC,CAAChB,KAAK,IAAI;AACxG"}
@@ -1,5 +1,14 @@
1
- import { n as isDefined, r as isRecord } from "./utils-COPacfAq.js";
2
- import { i as parseIconRoot, r as parseIconNode } from "./nodes-DAzj56Xn.js";
1
+ import { c as isDefined, i as parseIconRoot, l as isRecord, r as parseIconNode } from "./nodes-Bn7fLVZO.js";
2
+ /**
3
+ * Builds the key a set is registered under.
4
+ *
5
+ * @param library - Identifier of the library.
6
+ * @param style - Identifier of the style.
7
+ * @returns The key.
8
+ */
9
+ function getIconSetKey(library, style) {
10
+ return `${library}/${style}`;
11
+ }
3
12
  /**
4
13
  * Reads one icon of a converted set, skipping it when its data isn't usable.
5
14
  *
@@ -35,6 +44,6 @@ function parseIconSet(value) {
35
44
  })
36
45
  };
37
46
  }
38
- export { parseIconSet as t };
47
+ export { getIconSetKey as n, parseIconSet as t };
39
48
 
40
- //# sourceMappingURL=sets-BFcRq7dc.js.map
49
+ //# sourceMappingURL=sets-DH5UbUV_.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sets-DH5UbUV_.js","names":["IconLibraryInfo","IconSetLoader","Promise","default","IconRegistry","ready","sets","Record","libraries","getIconSetKey","library","style","isDefined","isRecord","IconNode","IconRoot","parseIconNode","parseIconRoot","IconSetIcon","name","keywords","node","root","IconSet","library","style","icons","IconLibraryInfo","label","packageName","packagePrefix","styles","listed","installed","sitePackage","parseIconSetIcon","value","undefined","parsedNode","parsedRoot","Array","isArray","filter","keyword","parseIconSet","flatMap","icon","parsed"],"sources":["../src/lib/registry.ts","../src/lib/sets.ts"],"sourcesContent":["import type { IconLibraryInfo } from \"@/lib/sets\";\n\n/**\n * Loads one converted set, as a module whose default export is the set.\n *\n * @public\n */\nexport type IconSetLoader = () => Promise<{ default: unknown }>;\n\n/**\n * What the build step generates: a loader for every converted set, and every library it knows.\n *\n * @public\n */\nexport interface IconRegistry {\n /** Whether the build step generated the registry, rather than the placeholder being used. */\n ready: boolean;\n /** Loaders keyed by library and style, such as `phosphor/bold`. */\n sets: Record<string, IconSetLoader>;\n /** Libraries the build step knows, keyed by identifier. */\n libraries: Record<string, IconLibraryInfo>;\n}\n\n/**\n * Builds the key a set is registered under.\n *\n * @param library - Identifier of the library.\n * @param style - Identifier of the style.\n * @returns The key.\n */\nexport function getIconSetKey(library: string, style: string) {\n return `${library}/${style}`;\n}\n","import { isDefined, isRecord } from \"@repo/lib/utils\";\n\nimport type { IconNode, IconRoot } from \"@/lib/nodes\";\nimport { parseIconNode, parseIconRoot } from \"@/lib/nodes\";\n\n/** One icon in a converted set. */\nexport interface IconSetIcon {\n /** Name of the icon in its library. */\n name: string;\n /** Words describing the icon, from its library. */\n keywords: string[];\n /** Shapes the icon is drawn from. */\n node: IconNode;\n /** Root for this icon, or undefined when it uses the set's. */\n root?: IconRoot;\n}\n\n/** Icons of one library style, converted by the build step into the stored drawing format. */\nexport interface IconSet {\n /** Identifier of the library, such as `lucide`. */\n library: string;\n /** Identifier of the style, such as `bold`. */\n style: string;\n /** Root most icons in the set share. */\n root: IconRoot;\n /** Every icon in the set. */\n icons: IconSetIcon[];\n}\n\n/**\n * A library the build step knows how to convert, and whether the project has it installed.\n *\n * @public\n */\nexport interface IconLibraryInfo {\n /** Readable name of the library. */\n label: string;\n /** Package the library is read from, or an example of one for a family of packages. */\n packageName: string;\n /** Shared start of the package names of a family of packages, one per style, or undefined for a single package. */\n packagePrefix?: string;\n /** Styles the library offers, the first being the default. */\n styles: string[];\n /** Whether the project's `package.json` lists the package, installed or not. */\n listed: boolean;\n /** Whether the project has the package installed. */\n installed: boolean;\n /** Another package of the library the project lists, such as its React version, or undefined when there's none. */\n sitePackage?: string;\n}\n\n/**\n * Reads one icon of a converted set, skipping it when its data isn't usable.\n *\n * @param value - The value to read.\n * @returns The icon, or undefined when the value isn't one.\n */\nfunction parseIconSetIcon(value: unknown): IconSetIcon | undefined {\n if (!isRecord(value)) return undefined;\n\n const { name, keywords, node, root } = value;\n const parsedNode = parseIconNode(node);\n const parsedRoot = isDefined(root) ? parseIconRoot(root) : undefined;\n\n if (typeof name !== \"string\" || !Array.isArray(keywords) || !isDefined(parsedNode)) return undefined;\n if (isDefined(root) && !isDefined(parsedRoot)) return undefined;\n\n return {\n name,\n keywords: keywords.filter((keyword: unknown) => typeof keyword === \"string\"),\n node: parsedNode,\n ...(isDefined(parsedRoot) && { root: parsedRoot }),\n };\n}\n\n/**\n * Reads a converted set, keeping only the icons whose data is usable.\n *\n * @param value - The value to read.\n * @returns The set, or undefined when the value isn't one.\n */\nexport function parseIconSet(value: unknown): IconSet | undefined {\n if (!isRecord(value)) return undefined;\n\n const { library, style, root, icons } = value;\n const parsedRoot = parseIconRoot(root);\n\n if (typeof library !== \"string\" || typeof style !== \"string\" || !isDefined(parsedRoot) || !Array.isArray(icons)) {\n return undefined;\n }\n\n return {\n library,\n style,\n root: parsedRoot,\n icons: icons.flatMap((icon: unknown) => {\n const parsed = parseIconSetIcon(icon);\n\n return isDefined(parsed) ? [parsed] : [];\n }),\n };\n}\n"],"mappings":";;;;;;;;AA8BA,SAAgBS,cAAcC,SAAiBC,OAAe;CAC5D,OAAO,GAAGD,QAAO,GAAIC;AACvB;;;;;;;ACyBA,SAASwB,iBAAiBC,OAAyC;CACjE,IAAI,CAACvB,SAASuB,KAAK,GAAG;CAEtB,IAAM,EAAEjB,MAAMC,UAAUC,MAAMC,SAASc,OACjCE,aAAatB,cAAcK,IAAI,GAC/BkB,aAAa3B,UAAUU,IAAI,IAAIL,cAAcK,IAAI,IAAIe,KAAAA;CAE3D,IAAI,OAAOlB,QAAS,YAAaqB,MAAMC,QAAQrB,QAAQ,KAAMR,UAAU0B,UAAU,MAC7E1B,WAAUU,IAAI,KAAMV,UAAU2B,UAAU,IAE5C,OAAO;EACLpB;EACAC,UAAUA,SAASsB,QAAQC,YAAqB,OAAOA,WAAY,QAAQ;EAC3EtB,MAAMiB;EACN,GAAI1B,UAAU2B,UAAU,KAAK,EAAEjB,MAAMiB,WAAW;CAClD;AACF;;;;;;;AAQA,SAAgBK,aAAaR,OAAqC;CAChE,IAAI,CAACvB,SAASuB,KAAK,GAAG;CAEtB,IAAM,EAAEZ,SAASC,OAAOH,MAAMI,UAAUU,OAClCG,aAAatB,cAAcK,IAAI;CAErC,IAAI,OAAOE,WAAY,YAAY,OAAOC,SAAU,YAAab,UAAU2B,UAAU,KAAMC,MAAMC,QAAQf,KAAK,GAI9G,OAAO;EACLF;EACAC;EACAH,MAAMiB;EACNb,OAAOA,MAAMmB,SAASC,SAAkB;GACtC,IAAMC,SAASZ,iBAAiBW,IAAI;GAEpC,OAAOlC,UAAUmC,MAAM,IAAI,CAACA,MAAM,IAAI,CAAA;EACxC,CAAC;CACH;AACF"}
@@ -1,7 +1,5 @@
1
- import { n as isDefined, t as convertCase } from "./utils-COPacfAq.js";
2
- import { n as iconSvgAttributes } from "./nodes-DAzj56Xn.js";
3
- import { t as getIconSetKey } from "./registry-BEEpqK3z.js";
4
- import { t as parseIconSet } from "./sets-BFcRq7dc.js";
1
+ import { c as isDefined, n as iconSvgAttributes, s as convertCase } from "./nodes-Bn7fLVZO.js";
2
+ import { n as getIconSetKey, t as parseIconSet } from "./sets-DH5UbUV_.js";
5
3
  import { createElement } from "react";
6
4
  import { jsx } from "react/jsx-runtime";
7
5
  import { iconRegistry } from "@driftime/sanity-plugin-icon/sets";
@@ -188,4 +186,4 @@ async function requestLibrary(library, style) {
188
186
  const iconTypeName = "icon";
189
187
  export { splitMatches as a, selectIcons as i, normalizeTerms as n, Drawing as o, requestLibrary as r, iconTypeName as t };
190
188
 
191
- //# sourceMappingURL=types-v7Qz7ogk.js.map
189
+ //# sourceMappingURL=types-CmTEhJK6.js.map