iconplease 0.2.0 → 0.3.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 +64 -11
- package/bin/iconplease.mjs +187 -0
- package/dist/config.d.ts +2 -0
- package/dist/config.js +5 -0
- package/dist/iconplease.min.js +1 -1
- package/dist/index.d.ts +2 -2
- package/dist/index.js +1 -1
- package/dist/react.js +2 -2
- package/dist/store.d.ts +1 -0
- package/dist/store.js +128 -19
- package/dist/types.d.ts +20 -0
- package/package.json +6 -2
package/README.md
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
# iconplease
|
|
2
2
|
|
|
3
|
-
Icons you can draw yourself.
|
|
4
|
-
browser, and new icons show up without updating this package.
|
|
3
|
+
Icons you can draw yourself. Each page loads only the icons it shows from the iconplease CDN, keeps
|
|
4
|
+
them in the browser, and new icons show up without updating this package.
|
|
5
5
|
|
|
6
6
|
## React
|
|
7
7
|
|
|
8
8
|
```bash
|
|
9
|
-
npm i iconplease
|
|
9
|
+
npm i iconplease@0.3.0
|
|
10
10
|
```
|
|
11
11
|
|
|
12
12
|
```tsx
|
|
@@ -35,15 +35,16 @@ never throws.
|
|
|
35
35
|
## Plain HTML
|
|
36
36
|
|
|
37
37
|
```html
|
|
38
|
-
<script src="https://cdn.jsdelivr.net/npm/iconplease@0.
|
|
39
|
-
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/iconplease@0.
|
|
38
|
+
<script src="https://cdn.jsdelivr.net/npm/iconplease@0.3.0/dist/iconplease.min.js" defer></script>
|
|
39
|
+
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/iconplease@0.3.0/dist/styles.css">
|
|
40
40
|
|
|
41
41
|
<i data-icon="heart"></i>
|
|
42
42
|
<i data-icon="rocket" data-size="32" data-color="#e11d48" data-stroke="1.5" data-motion="pop"></i>
|
|
43
43
|
<i data-icon="bell" data-label="Notifications"></i>
|
|
44
44
|
```
|
|
45
45
|
|
|
46
|
-
Elements added later are picked up automatically. `<i class="ip ip-heart">` works too.
|
|
46
|
+
Elements added later are picked up automatically. `<i class="ip ip-heart">` works too. A `class` on the
|
|
47
|
+
`<i>` stays on the `<i>`; style that element. An unknown name leaves the `<i>` empty and logs one warning.
|
|
47
48
|
|
|
48
49
|
## Functions
|
|
49
50
|
|
|
@@ -57,17 +58,69 @@ const names = iconNames();
|
|
|
57
58
|
|
|
58
59
|
## Your own set
|
|
59
60
|
|
|
60
|
-
Create a
|
|
61
|
+
Create a set in your iconplease account, publish it, and pick one of three ways to use it. Sites only
|
|
62
|
+
ever see the version you published, never work in progress.
|
|
63
|
+
|
|
64
|
+
### Build time (recommended for public sites)
|
|
65
|
+
|
|
66
|
+
No key on the page and no network for your icons. With React, server rendering outputs the real icon
|
|
67
|
+
(call `init({ set })` on the server as well).
|
|
68
|
+
|
|
69
|
+
```sh
|
|
70
|
+
ICONPLEASE_SECRET_KEY=ip_sk_… npx iconplease pull
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
This writes `src/iconplease.generated.ts`: your published set, plus the public icons your code uses
|
|
74
|
+
(`icon="…"` and `data-icon="…"` literals), plus an `IconName` type listing every name in it. `pull` warns
|
|
75
|
+
about names it cannot find; type your own props or constants as `IconName` and a typo fails to compile.
|
|
76
|
+
Commit it, and run `npx iconplease pull --check` in CI to catch a stale file. The secret key is only
|
|
77
|
+
read from the environment and never written to the file.
|
|
61
78
|
|
|
62
79
|
```ts
|
|
63
80
|
import { init } from "iconplease";
|
|
81
|
+
import set from "./iconplease.generated";
|
|
82
|
+
init({ set });
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
Names not in the file (built dynamically at runtime) still load from the public CDN.
|
|
86
|
+
|
|
87
|
+
### Live, with a publishable key
|
|
88
|
+
|
|
89
|
+
```ts
|
|
64
90
|
init({ apiKey: "ip_pk_…" });
|
|
65
91
|
```
|
|
66
92
|
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
93
|
+
Your set's version of an icon wins over the public one. The set loads in one request, is cached in the
|
|
94
|
+
browser and re-checked at most once an hour. Limit the key to your own sites when you create it; any
|
|
95
|
+
other site gets a console warning and the public icons. Publishable keys are visible in your page by
|
|
96
|
+
design.
|
|
97
|
+
|
|
98
|
+
Combine both with `init({ set, apiKey })`: bundled icons render immediately, and are replaced only
|
|
99
|
+
when a newer version has been published.
|
|
100
|
+
|
|
101
|
+
### Signed-in apps, with short-lived tokens
|
|
102
|
+
|
|
103
|
+
Keep a secret key on your server and hand the page a token that lasts 10 minutes:
|
|
104
|
+
|
|
105
|
+
```ts
|
|
106
|
+
// your server, behind your own sign-in
|
|
107
|
+
const res = await fetch("https://api.iconplease.com/sdk/token", {
|
|
108
|
+
method: "POST",
|
|
109
|
+
headers: { Authorization: `Bearer ${process.env.ICONPLEASE_SECRET_KEY}` },
|
|
110
|
+
});
|
|
111
|
+
return res.json(); // { token, expiresAt }
|
|
112
|
+
|
|
113
|
+
// your page
|
|
114
|
+
init({ token: () => fetch("/api/iconplease-token").then((r) => r.json()) });
|
|
115
|
+
```
|
|
116
|
+
|
|
117
|
+
The snippet above is your `/api/iconplease-token` route. Your function may return the token text or
|
|
118
|
+
`{ token, expiresAt }`. The package calls it when it needs to load the set and its last token is within a
|
|
119
|
+
minute of expiring, and once more if a token is refused. In token mode the set is kept in memory only, never
|
|
120
|
+
in `localStorage`. This protects pages behind your sign-in only; on a
|
|
121
|
+
public page, use build time instead.
|
|
122
|
+
|
|
123
|
+
**Never put a secret key (`ip_sk_…`) in front-end code.** `init` refuses one.
|
|
71
124
|
|
|
72
125
|
## How loading works
|
|
73
126
|
|
|
@@ -0,0 +1,187 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { existsSync, readFileSync, readdirSync, statSync, writeFileSync, mkdirSync } from "node:fs";
|
|
3
|
+
import { dirname, extname, join, relative, resolve } from "node:path";
|
|
4
|
+
|
|
5
|
+
const HELP = `iconplease pull — write your published set into your project
|
|
6
|
+
|
|
7
|
+
Usage
|
|
8
|
+
npx iconplease pull [options]
|
|
9
|
+
|
|
10
|
+
Reads ICONPLEASE_SECRET_KEY (a secret key, ip_sk_…) from the environment.
|
|
11
|
+
|
|
12
|
+
Options
|
|
13
|
+
--out <file> generated file (default src/iconplease.generated.ts; .js writes plain JavaScript)
|
|
14
|
+
--src <dir> folder scanned for public icon names (default src)
|
|
15
|
+
--check do not write; exit 1 if the file is missing or out of date (for CI)
|
|
16
|
+
--api <url> API address (default https://api.iconplease.com)
|
|
17
|
+
--cdn <url> CDN address (default https://cdn.iconplease.com)
|
|
18
|
+
-h, --help show this help
|
|
19
|
+
|
|
20
|
+
Then, in your app:
|
|
21
|
+
import { init } from "iconplease";
|
|
22
|
+
import set from "./iconplease.generated";
|
|
23
|
+
init({ set });
|
|
24
|
+
`;
|
|
25
|
+
|
|
26
|
+
const plural = (count, word) => `${count} ${word}${count === 1 ? "" : "s"}`;
|
|
27
|
+
const NAME = /^[a-z0-9](?:[a-z0-9-]{0,62}[a-z0-9])?$/;
|
|
28
|
+
const USAGE = /\b(?:data-icon|icon)\s*=\s*\{?\s*["'`]([a-z0-9](?:[a-z0-9-]{0,62}[a-z0-9])?)["'`]/g;
|
|
29
|
+
const SCANNED = new Set([".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs", ".vue", ".svelte", ".astro", ".html", ".mdx", ".md"]);
|
|
30
|
+
const SKIPPED = new Set(["node_modules", "dist", "build", ".git", ".next", ".svelte-kit", ".astro", "coverage", "out"]);
|
|
31
|
+
const SECRET = /ip_sk_[A-Za-z0-9]{32}/;
|
|
32
|
+
|
|
33
|
+
const fail = (message) => {
|
|
34
|
+
console.error(`iconplease: ${message}`);
|
|
35
|
+
process.exit(1);
|
|
36
|
+
};
|
|
37
|
+
|
|
38
|
+
const parseArgs = (argv) => {
|
|
39
|
+
const [command, ...rest] = argv;
|
|
40
|
+
const options = { out: "src/iconplease.generated.ts", src: "src", api: "https://api.iconplease.com", cdn: "https://cdn.iconplease.com", check: false };
|
|
41
|
+
if (!command || command === "-h" || command === "--help" || command === "help") return { help: true };
|
|
42
|
+
if (command !== "pull") fail(`unknown command "${command}". Run npx iconplease --help.`);
|
|
43
|
+
for (let index = 0; index < rest.length; index++) {
|
|
44
|
+
const flag = rest[index];
|
|
45
|
+
if (flag === "-h" || flag === "--help") return { help: true };
|
|
46
|
+
if (flag === "--check") options.check = true;
|
|
47
|
+
else if (["--out", "--src", "--api", "--cdn"].includes(flag)) {
|
|
48
|
+
const value = rest[++index];
|
|
49
|
+
if (!value) fail(`${flag} needs a value.`);
|
|
50
|
+
options[flag.slice(2)] = value;
|
|
51
|
+
} else fail(`unknown option "${flag}". Run npx iconplease --help.`);
|
|
52
|
+
}
|
|
53
|
+
return options;
|
|
54
|
+
};
|
|
55
|
+
|
|
56
|
+
const walk = (dir, outFile, found) => {
|
|
57
|
+
if (!existsSync(dir)) return;
|
|
58
|
+
for (const entry of readdirSync(dir)) {
|
|
59
|
+
if (SKIPPED.has(entry)) continue;
|
|
60
|
+
const path = join(dir, entry);
|
|
61
|
+
const info = statSync(path);
|
|
62
|
+
if (info.isDirectory()) walk(path, outFile, found);
|
|
63
|
+
else if (SCANNED.has(extname(entry)) && resolve(path) !== outFile && info.size < 2_000_000) {
|
|
64
|
+
for (const match of readFileSync(path, "utf8").matchAll(USAGE)) found.add(match[1]);
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
};
|
|
68
|
+
|
|
69
|
+
const getJSON = async (url, init) => {
|
|
70
|
+
let response;
|
|
71
|
+
try {
|
|
72
|
+
response = await fetch(url, init);
|
|
73
|
+
} catch (error) {
|
|
74
|
+
fail(`could not reach ${new URL(url).origin} (${error.message}).`);
|
|
75
|
+
}
|
|
76
|
+
const body = await response.json().catch(() => ({}));
|
|
77
|
+
return { status: response.status, ok: response.ok, body };
|
|
78
|
+
};
|
|
79
|
+
|
|
80
|
+
const fetchSet = async (api, key) => {
|
|
81
|
+
const { status, ok, body } = await getJSON(`${api.replace(/\/+$/, "")}/sdk/set`, { headers: { Authorization: `Bearer ${key}` } });
|
|
82
|
+
if (status === 401) fail(`ICONPLEASE_SECRET_KEY was refused: ${body.error ?? "not valid"}`);
|
|
83
|
+
if (!ok) fail(`could not read your set (${status}): ${body.error ?? "unknown error"}`);
|
|
84
|
+
return body;
|
|
85
|
+
};
|
|
86
|
+
|
|
87
|
+
const fetchPublic = async (cdn, names) => {
|
|
88
|
+
if (!names.length) return { icons: {}, missing: [] };
|
|
89
|
+
const base = cdn.replace(/\/+$/, "");
|
|
90
|
+
const pointer = await getJSON(`${base}/catalogue/latest.json`);
|
|
91
|
+
if (!pointer.ok || !/^catalogue\/index-[a-z0-9]+\.json$/.test(String(pointer.body.index ?? "").replace(/^\/+/, ""))) {
|
|
92
|
+
fail("could not read the public catalogue.");
|
|
93
|
+
}
|
|
94
|
+
const index = await getJSON(`${base}/${String(pointer.body.index).replace(/^\/+/, "")}`);
|
|
95
|
+
if (!index.ok || typeof index.body !== "object") fail("could not read the public catalogue index.");
|
|
96
|
+
const versions = index.body.icons ?? index.body;
|
|
97
|
+
const icons = {};
|
|
98
|
+
const missing = [];
|
|
99
|
+
for (const name of names) {
|
|
100
|
+
const version = versions[name];
|
|
101
|
+
if (!Number.isInteger(version) || version < 1) {
|
|
102
|
+
missing.push(name);
|
|
103
|
+
continue;
|
|
104
|
+
}
|
|
105
|
+
let response;
|
|
106
|
+
try {
|
|
107
|
+
response = await fetch(`${base}/v${version}/${name}.svg`);
|
|
108
|
+
} catch (error) {
|
|
109
|
+
fail(`could not download the public icon "${name}" (${error.message}).`);
|
|
110
|
+
}
|
|
111
|
+
if (!response.ok) fail(`could not download the public icon "${name}" (${response.status}).`);
|
|
112
|
+
icons[name] = { version, svg: (await response.text()).trim(), source: "public" };
|
|
113
|
+
}
|
|
114
|
+
return { icons, missing };
|
|
115
|
+
};
|
|
116
|
+
|
|
117
|
+
const render = (outFile, payload, names) => {
|
|
118
|
+
const typed = /\.(ts|tsx|mts|cts)$/.test(outFile);
|
|
119
|
+
const json = JSON.stringify(payload, null, 2);
|
|
120
|
+
const summary = `${plural(Object.values(payload.icons).filter((icon) => icon.source === "set").length, "set icon")}, ${plural(Object.values(payload.icons).filter((icon) => icon.source === "public").length, "public icon")}`;
|
|
121
|
+
const lines = [
|
|
122
|
+
"// Generated by `npx iconplease pull`. Do not edit; run it again to update.",
|
|
123
|
+
`// ${payload.workspace ? `Set: ${payload.workspace.name}` : "No set"} · published version ${payload.version ?? "none"} · ${summary}.`,
|
|
124
|
+
];
|
|
125
|
+
if (typed) {
|
|
126
|
+
lines.push('import type { BundledSet } from "iconplease";', "", `export const set: BundledSet = ${json};`, "");
|
|
127
|
+
lines.push(`export type IconName = ${names.length ? names.map((name) => JSON.stringify(name)).join(" | ") : "never"};`, "");
|
|
128
|
+
} else {
|
|
129
|
+
lines.push("", `export const set = ${json};`, "");
|
|
130
|
+
}
|
|
131
|
+
lines.push("export default set;", "");
|
|
132
|
+
return lines.join("\n");
|
|
133
|
+
};
|
|
134
|
+
|
|
135
|
+
const main = async () => {
|
|
136
|
+
const options = parseArgs(process.argv.slice(2));
|
|
137
|
+
if (options.help) {
|
|
138
|
+
console.log(HELP);
|
|
139
|
+
return;
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
const key = (process.env.ICONPLEASE_SECRET_KEY ?? "").trim();
|
|
143
|
+
if (!key) fail("set ICONPLEASE_SECRET_KEY to a secret key (ip_sk_…) from your set's API keys tab.");
|
|
144
|
+
if (key.startsWith("ip_pk_")) fail("ICONPLEASE_SECRET_KEY holds a publishable key. pull needs a secret key (ip_sk_…).");
|
|
145
|
+
if (!SECRET.test(key)) fail("ICONPLEASE_SECRET_KEY does not look like a secret key (ip_sk_ followed by 32 characters).");
|
|
146
|
+
|
|
147
|
+
const outFile = resolve(options.out);
|
|
148
|
+
const remote = await fetchSet(options.api, key);
|
|
149
|
+
const setIcons = {};
|
|
150
|
+
for (const [name, entry] of Object.entries(remote.icons ?? {})) {
|
|
151
|
+
if (NAME.test(name) && typeof entry?.svg === "string") setIcons[name] = { version: Number(entry.version) || 1, svg: entry.svg, source: "set" };
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
const used = new Set();
|
|
155
|
+
walk(resolve(options.src), outFile, used);
|
|
156
|
+
const wanted = [...used].filter((name) => !setIcons[name]).sort();
|
|
157
|
+
const { icons: publicIcons, missing } = await fetchPublic(options.cdn, wanted);
|
|
158
|
+
|
|
159
|
+
const all = { ...publicIcons, ...setIcons };
|
|
160
|
+
const names = Object.keys(all).sort();
|
|
161
|
+
const payload = {
|
|
162
|
+
format: 1,
|
|
163
|
+
version: typeof remote.version === "number" ? remote.version : null,
|
|
164
|
+
workspace: remote.workspace ? { id: remote.workspace.id, name: remote.workspace.name } : null,
|
|
165
|
+
icons: Object.fromEntries(names.map((name) => [name, all[name]])),
|
|
166
|
+
};
|
|
167
|
+
const output = render(outFile, payload, names);
|
|
168
|
+
|
|
169
|
+
if (output.includes(key) || SECRET.test(output)) fail("refusing to write: the output would contain a secret key.");
|
|
170
|
+
|
|
171
|
+
const where = relative(process.cwd(), outFile) || outFile;
|
|
172
|
+
if (remote.version === null || remote.version === undefined) console.warn("iconplease: this set has not been published yet, so it adds no icons. Publish it in your account.");
|
|
173
|
+
if (missing.length) console.warn(`iconplease: not in your set or the public library: ${missing.join(", ")}. Check the spelling.`);
|
|
174
|
+
|
|
175
|
+
if (options.check) {
|
|
176
|
+
const current = existsSync(outFile) ? readFileSync(outFile, "utf8") : null;
|
|
177
|
+
if (current !== output) fail(`${where} is ${current === null ? "missing" : "out of date"}. Run npx iconplease pull and commit the result.`);
|
|
178
|
+
console.log(`iconplease: ${where} is up to date (${plural(names.length, "icon")}, set version ${payload.version ?? "none"}).`);
|
|
179
|
+
return;
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
mkdirSync(dirname(outFile), { recursive: true });
|
|
183
|
+
writeFileSync(outFile, output);
|
|
184
|
+
console.log(`iconplease: wrote ${where} — ${plural(Object.keys(setIcons).length, "set icon")}, ${plural(Object.keys(publicIcons).length, "public icon")}, set version ${payload.version ?? "none"}.`);
|
|
185
|
+
};
|
|
186
|
+
|
|
187
|
+
main().catch((error) => fail(error instanceof Error ? error.message : String(error)));
|
package/dist/config.d.ts
CHANGED
|
@@ -5,3 +5,5 @@ export declare const cdnBase: () => string;
|
|
|
5
5
|
export declare const revalidateMs: () => number;
|
|
6
6
|
export declare const apiBase: () => string;
|
|
7
7
|
export declare const apiKey: () => string | undefined;
|
|
8
|
+
export declare const tokenSource: () => import("./types.js").TokenSource | undefined;
|
|
9
|
+
export declare const bundledSet: () => import("./types.js").BundledSet | undefined;
|
package/dist/config.js
CHANGED
|
@@ -11,6 +11,9 @@ export const init = (next = {}) => {
|
|
|
11
11
|
if (next.apiKey && !/^ip_pk_[A-Za-z0-9]{32}$/.test(next.apiKey)) {
|
|
12
12
|
console.warn("iconplease: that does not look like a publishable key (ip_pk_ followed by 32 characters). Set icons will not load.");
|
|
13
13
|
}
|
|
14
|
+
if (next.token !== undefined && typeof next.token !== "function") {
|
|
15
|
+
throw new Error("iconplease: token must be a function that asks your server for a fresh token, e.g. () => fetch(\"/api/iconplease-token\").then((r) => r.json()).");
|
|
16
|
+
}
|
|
14
17
|
config = { ...DEFAULTS, ...next };
|
|
15
18
|
return config;
|
|
16
19
|
};
|
|
@@ -19,3 +22,5 @@ export const cdnBase = () => (config.cdnUrl ?? DEFAULTS.cdnUrl).replace(/\/+$/,
|
|
|
19
22
|
export const revalidateMs = () => Math.max(0, config.revalidate ?? DEFAULTS.revalidate) * 1000;
|
|
20
23
|
export const apiBase = () => (config.apiUrl ?? DEFAULTS.apiUrl).replace(/\/+$/, "");
|
|
21
24
|
export const apiKey = () => config.apiKey || undefined;
|
|
25
|
+
export const tokenSource = () => config.token;
|
|
26
|
+
export const bundledSet = () => config.set;
|
package/dist/iconplease.min.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";(()=>{var w={cdnUrl:"https://cdn.iconplease.com",apiUrl:"https://api.iconplease.com",revalidate:3600},g={...w},C=(e={})=>{if(e.apiKey&&e.apiKey.startsWith("ip_sk_"))throw new Error("iconplease: that is a secret key. init() runs in the browser, where the key is readable by anyone \u2014 use the publishable key (ip_pk_\u2026).");return e.apiKey&&!/^ip_pk_[A-Za-z0-9]{32}$/.test(e.apiKey)&&console.warn("iconplease: that does not look like a publishable key (ip_pk_ followed by 32 characters). Set icons will not load."),g={...w,...e},g};var P=()=>{var e;return((e=g.cdnUrl)!=null?e:w.cdnUrl).replace(/\/+$/,"")},j=()=>{var e;return Math.max(0,(e=g.revalidate)!=null?e:w.revalidate)*1e3},X=()=>{var e;return((e=g.apiUrl)!=null?e:w.apiUrl).replace(/\/+$/,"")},x=()=>g.apiKey||void 0;var me=/<\s*(script|foreignObject|iframe|object|embed|style)\b[\s\S]*?(<\s*\/\s*\1\s*>|\/>)/gi,he=/\s+on[a-z]+\s*=\s*("[^"]*"|'[^']*'|[^\s>]+)/gi,ye=/\s+(?:xlink:)?href\s*=\s*("\s*javascript:[^"]*"|'\s*javascript:[^']*')/gi,be=/^[a-z][a-z0-9-]*$/,we=/^[^"<>]*$/,xe=e=>e.replace(me,"").replace(he,"").replace(ye,""),D=e=>{var o;if(!e||typeof e!="object")return;let t=e;if(typeof t.body!="string"||typeof t.viewBox!="string"||!/^[0-9.\s-]+$/.test(t.viewBox))return;let n={};for(let[s,r]of Object.entries((o=t.attrs)!=null?o:{}))be.test(s)&&!s.startsWith("on")&&typeof r=="string"&&we.test(r)&&(n[s]=r);return{viewBox:t.viewBox,attrs:n,body:xe(t.body)}};var te="iconplease:index:v2",ne="iconplease:icons:v2",oe="iconplease:set:v1",ve=1e3,A=/^[a-z0-9](?:[a-z0-9-]{0,62}[a-z0-9])?$/,c={status:"idle",revision:0},O=0,I,Y=!1,Z=!1,M,m=new Map,u=new Map,T,k=0,h=!1,v,_=!1,R=new Map,z=new Set,S=()=>{try{return typeof localStorage=="undefined"?void 0:localStorage}catch{return}},p=(e={})=>{c={...c,...e,revision:c.revision+1};for(let t of z)t()},E=(e,t)=>`${e}@${t}`,se=e=>{if(!e||typeof e!="object")return;let t=e;if(t.format!==2||typeof t.hash!="string"||!t.icons||typeof t.icons!="object")return;let n=Object.entries(t.icons).filter(([o,s])=>A.test(o)&&Number.isInteger(s)&&s>0);return{format:2,hash:t.hash,icons:Object.fromEntries(n)}},L=e=>e.slice(0,14),ke=()=>{var n,o,s;let e=x(),t=e?L(e):void 0;if(t!==T&&(T=t,u.clear(),k=0,h=!1,v=void 0,_=!1,!!t))try{let r=JSON.parse((o=(n=S())==null?void 0:n.getItem(oe))!=null?o:"null");if(!r||r.tag!==t)return;for(let[i,f]of Object.entries((s=r.icons)!=null?s:{})){let a=A.test(i)&&typeof(f==null?void 0:f.svg)=="string"?K(f.svg):void 0;a&&u.set(i,a)}k=typeof r.checkedAt=="number"?r.checkedAt:0,h=!0}catch{return}},y=()=>{var t,n;if(ke(),Y)return;Y=!0;let e=S();if(e){try{let o=JSON.parse((t=e.getItem(te))!=null?t:"null"),s=se(o==null?void 0:o.index);s&&(c={status:"ready",index:s,revision:c.revision},O=typeof(o==null?void 0:o.checkedAt)=="number"?o.checkedAt:0)}catch{return}try{let o=JSON.parse((n=e.getItem(ne))!=null?n:"{}");for(let[s,r]of Object.entries(o)){let i=D(r);i&&m.set(s,i)}}catch{return}}},Q=()=>{var e;try{(e=S())==null||e.setItem(te,JSON.stringify({index:c.index,checkedAt:O}))}catch{return}},re=()=>{M||(M=setTimeout(()=>{var n,o,s;M=void 0;let e=(o=(n=c.index)==null?void 0:n.icons)!=null?o:{},t=[...m.entries()].filter(([r])=>{let i=r.lastIndexOf("@");return e[r.slice(0,i)]===Number(r.slice(i+1))});try{(s=S())==null||s.setItem(ne,JSON.stringify(Object.fromEntries(t.slice(-ve))))}catch{return}},0))},ee=async e=>{let t=await fetch(e);if(!t.ok)throw new Error(`${t.status} for ${e}`);return t.json()},ie=e=>{Z||(Z=!0,console.warn("iconplease: could not reach the icon CDN.",e))},Se=async()=>{var s;let e=P(),t=await ee(`${e}/catalogue/latest.json`);if((t==null?void 0:t.format)!==2||typeof t.hash!="string"||typeof t.index!="string")throw new Error("iconplease: the catalogue pointer is malformed");if(O=Date.now(),((s=c.index)==null?void 0:s.hash)===t.hash){Q();return}let n=t.index.replace(/^\/+/,"");if(!/^catalogue\/index-[a-z0-9]+\.json$/.test(n))throw new Error("iconplease: unexpected index location");let o=se(await ee(`${e}/${n}`));if(!o)throw new Error("iconplease: the icon index is malformed");p({status:"ready",index:o}),Q(),re()},B=(e={})=>{if(y(),c.index&&Date.now()-O<j()&&!e.force)return Promise.resolve();if(I)return I;let n=Se().catch(o=>{c.index||p({status:"error"}),ie(o)}).finally(()=>{I=void 0});return I=n,!c.index&&c.status!=="loading"&&p({status:"loading"}),n},K=e=>{let t=/<svg\b([^>]*)>([\s\S]*)<\/svg>\s*$/.exec(e.trim());if(!t)return;let n={},o="0 0 24 24";for(let[,s,r]of t[1].matchAll(/([a-zA-Z:-]+)="([^"]*)"/g))s==="viewBox"?o=r:["xmlns","width","height","aria-hidden","role","class","style"].includes(s)||(n[s]=r);return D({viewBox:o,attrs:n,body:t[2]})},Ie=(e,t)=>{let n=E(e,t),o=R.get(n);if(o)return o;let s=fetch(`${P()}/v${t}/${e}.svg`).then(async r=>{if(!r.ok)throw new Error(`${r.status} for ${e}`);let i=K(await r.text());if(!i)throw new Error(`iconplease: "${e}" is not a valid SVG`);m.set(n,i),re(),p()}).catch(ie).finally(()=>{R.delete(n)});return R.set(n,s),s},Ee=async e=>{var r,i;let t=await fetch(`${X()}/sdk/set?key=${encodeURIComponent(e)}`),n=await t.json().catch(()=>({}));if(!t.ok)throw new Error(n.error||`HTTP ${t.status}`);let o=new Map,s={};for(let[f,a]of Object.entries((r=n.icons)!=null?r:{})){if(!A.test(f)||typeof(a==null?void 0:a.svg)!="string")continue;let l=K(a.svg);l&&(o.set(f,l),s[f]={version:Number(a.version)||1,svg:a.svg})}if(L(e)===T){u.clear();for(let[f,a]of o)u.set(f,a);k=Date.now(),h=!0;try{(i=S())==null||i.setItem(oe,JSON.stringify({tag:L(e),checkedAt:k,icons:s}))}catch{p();return}p()}},U=(e={})=>{y();let t=x();if(!t||h&&Date.now()-k<j()&&!e.force)return Promise.resolve();if(v)return v;let o=Ee(t).catch(s=>{h=!0,_||(_=!0,console.warn(`iconplease: could not load your icon set \u2014 ${s instanceof Error?s.message:String(s)} Falling back to public icons.`)),p()}).finally(()=>{v=void 0});return v=o,o},F=async e=>{var o,s;if(!A.test(e))return;if(y(),x()){if(u.has(e)){U();return}if(await U(),u.has(e))return}let t=(o=c.index)==null?void 0:o.icons[e];if(t&&m.has(E(e,t))){B();return}await B();let n=(s=c.index)==null?void 0:s.icons[e];n&&!m.has(E(e,n))&&await Ie(e,n)},J=async(e={})=>{let{icons:t=[],force:n=!1}=Array.isArray(e)?{icons:e}:e;await Promise.all([B({force:n}),U({force:n})]),await Promise.all(t.map(F))},ae=e=>(y(),z.add(e),()=>z.delete(e));var $=e=>{var o;y();let t=u.get(e);if(t)return t;let n=(o=c.index)==null?void 0:o.icons[e];return n?m.get(E(e,n)):void 0},ce=e=>(y(),u.has(e)||x()&&!h?!1:c.status==="ready"&&!!c.index&&!(e in c.index.icons));var Ae=/^[#a-zA-Z0-9(),.%\s-]{1,64}$/,Oe=/[<>"&]/g,$e={"<":"<",">":">",'"':""","&":"&"},Ne=e=>e.replace(Oe,t=>$e[t]),de=e=>String(Number(e.toFixed(3))),Ce=(e,t)=>e.replace(/\b(fill|stroke)="currentColor"/g,`$1="${t}"`),Pe=(e,t)=>e.replace(/\bstroke-width="([0-9]*\.?[0-9]+)"/g,(n,o)=>`stroke-width="${de(Number(o)*t)}"`),q=(e,t={})=>{var G;let{size:n=24,color:o,strokeScale:s,motion:r,label:i,className:f}=t,a=o&&Ae.test(o)?o:void 0,l=typeof s=="number"&&Number.isFinite(s)&&s>0&&s!==1?s:void 0,d={...(G=e.attrs)!=null?G:{}};if(a)for(let W of["fill","stroke"])d[W]==="currentColor"&&(d[W]=a);l&&d["stroke-width"]&&(d["stroke-width"]=de(Number(d["stroke-width"])*l));let b=e.body;return a&&(b=Ce(b,a)),l&&(b=Pe(b,l)),d.width=String(n),d.height=String(n),d.viewBox=e.viewBox,r&&r!=="none"&&(d["data-motion"]=r),i?(d.role="img",d["aria-label"]=i):d["aria-hidden"]="true",f&&(d.class=f),{attrs:d,body:b}},H=({attrs:e,body:t})=>`<svg xmlns="http://www.w3.org/2000/svg" ${Object.entries(e).map(([o,s])=>`${o}="${Ne(s)}"`).join(" ")}>${t}</svg>`,fe=(e,t={})=>{let n=typeof e=="string"?$(e):e;return n?H(q(n,t)):void 0};var le="[data-icon], i.ip[class*='ip-']",je=new Set(["none","wiggle","pop","bounce","draw"]),ue=new Set,De=e=>{let t=e.getAttribute("data-icon");if(t)return t;for(let n of Array.from(e.classList))if(n.startsWith("ip-")&&n.length>3)return n.slice(3)},pe=e=>{if(e===null)return;let t=Number(e);return Number.isFinite(t)&&t>0?t:void 0},V=e=>{var f,a,l,d;let t=De(e);if(!t)return;let n=$(t),o=e.getAttribute("data-motion"),s=o&&je.has(o)?o:void 0,r={size:(f=pe(e.getAttribute("data-size")))!=null?f:24,color:(a=e.getAttribute("data-color"))!=null?a:void 0,strokeScale:pe(e.getAttribute("data-stroke")),motion:s,label:(l=e.getAttribute("data-label"))!=null?l:void 0},i=JSON.stringify([t,r,n?"1":"0"]);if(e.getAttribute("data-ip-rendered")!==i){if(!n){ce(t)?ue.has(t)||(ue.add(t),console.warn(`iconplease: no icon named "${t}".`)):F(t);return}e.innerHTML=H(q(n,r)),e.setAttribute("data-ip-rendered",i),e.tagName==="I"&&((d=e.style).display||(d.display="inline-flex"))}},N=(e=document)=>{e instanceof Element&&e.matches(le)&&V(e),e.querySelectorAll(le).forEach(V)},ge=()=>{let e=window.iconpleaseConfig;e&&C(e),ae(()=>N()),N(),J(),new MutationObserver(t=>{for(let n of t)n.type==="attributes"&&n.target instanceof Element&&V(n.target),n.addedNodes.forEach(o=>{o instanceof Element&&N(o)})}).observe(document.documentElement,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["data-icon","data-size","data-color","data-stroke","data-motion","data-label","class"]})};window.iconplease={init:C,load:J,renderSVG:fe,refresh:()=>N()};document.readyState==="loading"?document.addEventListener("DOMContentLoaded",ge,{once:!0}):ge();})();
|
|
1
|
+
"use strict";(()=>{var v={cdnUrl:"https://cdn.iconplease.com",apiUrl:"https://api.iconplease.com",revalidate:3600},l={...v},z=(e={})=>{if(e.apiKey&&e.apiKey.startsWith("ip_sk_"))throw new Error("iconplease: that is a secret key. init() runs in the browser, where the key is readable by anyone \u2014 use the publishable key (ip_pk_\u2026).");if(e.apiKey&&!/^ip_pk_[A-Za-z0-9]{32}$/.test(e.apiKey)&&console.warn("iconplease: that does not look like a publishable key (ip_pk_ followed by 32 characters). Set icons will not load."),e.token!==void 0&&typeof e.token!="function")throw new Error('iconplease: token must be a function that asks your server for a fresh token, e.g. () => fetch("/api/iconplease-token").then((r) => r.json()).');return l={...v,...e},l};var L=()=>{var e;return((e=l.cdnUrl)!=null?e:v.cdnUrl).replace(/\/+$/,"")},K=()=>{var e;return Math.max(0,(e=l.revalidate)!=null?e:v.revalidate)*1e3},U=()=>{var e;return((e=l.apiUrl)!=null?e:v.apiUrl).replace(/\/+$/,"")},F=()=>l.apiKey||void 0,x=()=>l.token,ce=()=>l.set;var Oe=/<\s*(script|foreignObject|iframe|object|embed|style)\b[\s\S]*?(<\s*\/\s*\1\s*>|\/>)/gi,Ne=/\s+on[a-z]+\s*=\s*("[^"]*"|'[^']*'|[^\s>]+)/gi,$e=/\s+(?:xlink:)?href\s*=\s*("\s*javascript:[^"]*"|'\s*javascript:[^']*')/gi,Pe=/^[a-z][a-z0-9-]*$/,De=/^[^"<>]*$/,je=e=>e.replace(Oe,"").replace(Ne,"").replace($e,""),J=e=>{var o;if(!e||typeof e!="object")return;let t=e;if(typeof t.body!="string"||typeof t.viewBox!="string"||!/^[0-9.\s-]+$/.test(t.viewBox))return;let n={};for(let[r,s]of Object.entries((o=t.attrs)!=null?o:{}))Pe.test(r)&&!r.startsWith("on")&&typeof s=="string"&&De.test(s)&&(n[r]=s);return{viewBox:t.viewBox,attrs:n,body:je(t.body)}};var pe="iconplease:index:v2",ge="iconplease:icons:v2",me="iconplease:set:v1",Ce=1e3,O=/^[a-z0-9](?:[a-z0-9-]{0,62}[a-z0-9])?$/,c={status:"idle",revision:0},T=0,P,ae=!1,de=!1,q,y=new Map,h=new Map,H,E=0,b=!1,I,G=!1,V=new Map,w=null,W=0,_e=6e4,A,j=null,Y=new Map,C=new Map,Te=()=>{let e=ce();if(e!==A&&(A=e,Y.clear(),C.clear(),j=null,!(!e||e.format!==1||typeof e.icons!="object"))){j=typeof e.version=="number"?e.version:null;for(let[t,n]of Object.entries(e.icons)){if(!O.test(t)||typeof(n==null?void 0:n.svg)!="string")continue;let o=M(n.svg);o&&(n.source==="public"?C:Y).set(t,o)}}},Me=()=>w!==null&&(j===null||w>j),m=e=>{var t,n;return A?Me()?(t=h.get(e))!=null?t:C.get(e):(n=Y.get(e))!=null?n:C.get(e):h.get(e)};var X=new Set,N=()=>{try{return typeof localStorage=="undefined"?void 0:localStorage}catch{return}},p=(e={})=>{c={...c,...e,revision:c.revision+1};for(let t of X)t()},_=(e,t)=>`${e}@${t}`,ye=e=>{if(!e||typeof e!="object")return;let t=e;if(t.format!==2||typeof t.hash!="string"||!t.icons||typeof t.icons!="object")return;let n=Object.entries(t.icons).filter(([o,r])=>O.test(o)&&Number.isInteger(r)&&r>0);return{format:2,hash:t.hash,icons:Object.fromEntries(n)}},Re=e=>e.slice(0,14),$=()=>{if(x())return"token";let e=F();return e?Re(e):void 0},Be=6e4,ze=9*6e4,D,S,Le=(e=!1)=>{let t=x();return t?!e&&D&&D.expiresAt-Be>Date.now()?Promise.resolve(D.token):S||(S=t().then(n=>{let o=typeof n=="string"?n:n==null?void 0:n.token;if(typeof o!="string"||!o.startsWith("ipt_"))throw new Error("your token function did not return an iconplease token (ipt_\u2026).");let r=typeof n=="string"?void 0:n.expiresAt,s=typeof r=="number"?r:r?Date.parse(r):NaN;return D={token:o,expiresAt:Number.isFinite(s)?s:Date.now()+ze},o}).finally(()=>{S=void 0}),S):Promise.reject(new Error("no token source"))},Ke=()=>{var t,n,o;let e=$();if(e!==H&&(H=e,h.clear(),E=0,b=!1,I=void 0,G=!1,w=null,W=0,!!e))try{if(e==="token")return;let r=JSON.parse((n=(t=N())==null?void 0:t.getItem(me))!=null?n:"null");if(!r||r.tag!==e)return;for(let[s,i]of Object.entries((o=r.icons)!=null?o:{})){let u=O.test(s)&&typeof(i==null?void 0:i.svg)=="string"?M(i.svg):void 0;u&&h.set(s,u)}E=typeof r.checkedAt=="number"?r.checkedAt:0,w=typeof r.version=="number"?r.version:null,b=!0}catch{return}},g=()=>{var t,n;if(Te(),Ke(),ae)return;ae=!0;let e=N();if(e){try{let o=JSON.parse((t=e.getItem(pe))!=null?t:"null"),r=ye(o==null?void 0:o.index);r&&(c={status:"ready",index:r,revision:c.revision},T=typeof(o==null?void 0:o.checkedAt)=="number"?o.checkedAt:0)}catch{return}try{let o=JSON.parse((n=e.getItem(ge))!=null?n:"{}");for(let[r,s]of Object.entries(o)){let i=J(s);i&&y.set(r,i)}}catch{return}}},ue=()=>{var e;try{(e=N())==null||e.setItem(pe,JSON.stringify({index:c.index,checkedAt:T}))}catch{return}},he=()=>{q||(q=setTimeout(()=>{var n,o,r;q=void 0;let e=(o=(n=c.index)==null?void 0:n.icons)!=null?o:{},t=[...y.entries()].filter(([s])=>{let i=s.lastIndexOf("@");return e[s.slice(0,i)]===Number(s.slice(i+1))});try{(r=N())==null||r.setItem(ge,JSON.stringify(Object.fromEntries(t.slice(-Ce))))}catch{return}},0))},fe=async e=>{let t=await fetch(e);if(!t.ok)throw new Error(`${t.status} for ${e}`);return t.json()},be=e=>{de||(de=!0,console.warn("iconplease: could not reach the icon CDN.",e))},Ue=async()=>{var r;let e=L(),t=await fe(`${e}/catalogue/latest.json`);if((t==null?void 0:t.format)!==2||typeof t.hash!="string"||typeof t.index!="string")throw new Error("iconplease: the catalogue pointer is malformed");if(T=Date.now(),((r=c.index)==null?void 0:r.hash)===t.hash){ue();return}let n=t.index.replace(/^\/+/,"");if(!/^catalogue\/index-[a-z0-9]+\.json$/.test(n))throw new Error("iconplease: unexpected index location");let o=ye(await fe(`${e}/${n}`));if(!o)throw new Error("iconplease: the icon index is malformed");p({status:"ready",index:o}),ue(),he()},Z=(e={})=>{if(g(),c.index&&Date.now()-T<K()&&!e.force)return Promise.resolve();if(P)return P;let n=Ue().catch(o=>{c.index||p({status:"error"}),be(o)}).finally(()=>{P=void 0});return P=n,!c.index&&c.status!=="loading"&&p({status:"loading"}),n},M=e=>{let t=/<svg\b([^>]*)>([\s\S]*)<\/svg>\s*$/.exec(e.trim());if(!t)return;let n={},o="0 0 24 24";for(let[,r,s]of t[1].matchAll(/([a-zA-Z:-]+)="([^"]*)"/g))r==="viewBox"?o=s:["xmlns","width","height","aria-hidden","role","class","style"].includes(r)||(n[r]=s);return J({viewBox:o,attrs:n,body:t[2]})},Fe=(e,t)=>{let n=_(e,t),o=V.get(n);if(o)return o;let r=fetch(`${L()}/v${t}/${e}.svg`).then(async s=>{if(!s.ok)throw new Error(`${s.status} for ${e}`);let i=M(await s.text());if(!i)throw new Error(`iconplease: "${e}" is not a valid SVG`);y.set(n,i),he(),p()}).catch(be).finally(()=>{V.delete(n)});return V.set(n,r),r},le=async(e=!1)=>{var n;if(!x()){let o=(n=F())!=null?n:"";return fetch(`${U()}/sdk/set?key=${encodeURIComponent(o)}`)}let t=await Le(e);return fetch(`${U()}/sdk/set`,{headers:{Authorization:`Bearer ${t}`}})},Je=async e=>{var s,i;let t=await le();t.status===401&&x()&&(t=await le(!0));let n=await t.json().catch(()=>({}));if(!t.ok)throw new Error(n.error||`HTTP ${t.status}`);let o=new Map,r={};for(let[u,d]of Object.entries((s=n.icons)!=null?s:{})){if(!O.test(u)||typeof(d==null?void 0:d.svg)!="string")continue;let f=M(d.svg);f&&(o.set(u,f),r[u]={version:Number(d.version)||1,svg:d.svg})}if(e===H){h.clear();for(let[u,d]of o)h.set(u,d);E=Date.now(),b=!0,w=typeof n.version=="number"?n.version:null;try{e!=="token"&&((i=N())==null||i.setItem(me,JSON.stringify({tag:e,checkedAt:E,version:w,icons:r})))}catch{p();return}p()}},Q=(e={})=>{g();let t=$();if(!t||b&&Date.now()-E<K()&&!e.force||!e.force&&Date.now()<W)return Promise.resolve();if(I)return I;let o=Je(t).catch(r=>{b=!0,W=Date.now()+_e,G||(G=!0,console.warn(`iconplease: could not load your icon set \u2014 ${r instanceof Error?r.message:String(r)} Falling back to public icons.`)),p()}).finally(()=>{I=void 0});return I=o,o},ee=async e=>{var o,r;if(!O.test(e))return;if(g(),$()){if(m(e)){Q();return}if(await Q(),m(e))return}else if(m(e))return;let t=(o=c.index)==null?void 0:o.icons[e];if(t&&y.has(_(e,t))){Z();return}await Z();let n=(r=c.index)==null?void 0:r.icons[e];n&&!y.has(_(e,n))&&await Fe(e,n)},te=async(e={})=>{let{icons:t=[],force:n=!1}=Array.isArray(e)?{icons:e}:e;g(),!(A&&!$()&&t.every(r=>m(r)))&&(await Promise.all([A?Promise.resolve():Z({force:n}),Q({force:n})]),await Promise.all(t.map(ee)))},we=e=>(g(),X.add(e),()=>X.delete(e));var R=e=>{var o;g();let t=m(e);if(t)return t;let n=(o=c.index)==null?void 0:o.icons[e];return n?y.get(_(e,n)):void 0},ke=e=>(g(),m(e)||$()&&!b?!1:c.status==="ready"&&!!c.index&&!(e in c.index.icons));var qe=/^[#a-zA-Z0-9(),.%\s-]{1,64}$/,Ve=/[<>"&]/g,He={"<":"<",">":">",'"':""","&":"&"},Ge=e=>e.replace(Ve,t=>He[t]),ve=e=>String(Number(e.toFixed(3))),We=(e,t)=>e.replace(/\b(fill|stroke)="currentColor"/g,`$1="${t}"`),Ye=(e,t)=>e.replace(/\bstroke-width="([0-9]*\.?[0-9]+)"/g,(n,o)=>`stroke-width="${ve(Number(o)*t)}"`),ne=(e,t={})=>{var se;let{size:n=24,color:o,strokeScale:r,motion:s,label:i,className:u}=t,d=o&&qe.test(o)?o:void 0,f=typeof r=="number"&&Number.isFinite(r)&&r>0&&r!==1?r:void 0,a={...(se=e.attrs)!=null?se:{}};if(d)for(let ie of["fill","stroke"])a[ie]==="currentColor"&&(a[ie]=d);f&&a["stroke-width"]&&(a["stroke-width"]=ve(Number(a["stroke-width"])*f));let k=e.body;return d&&(k=We(k,d)),f&&(k=Ye(k,f)),a.width=String(n),a.height=String(n),a.viewBox=e.viewBox,s&&s!=="none"&&(a["data-motion"]=s),i?(a.role="img",a["aria-label"]=i):a["aria-hidden"]="true",u&&(a.class=u),{attrs:a,body:k}},oe=({attrs:e,body:t})=>`<svg xmlns="http://www.w3.org/2000/svg" ${Object.entries(e).map(([o,r])=>`${o}="${Ge(r)}"`).join(" ")}>${t}</svg>`,xe=(e,t={})=>{let n=typeof e=="string"?R(e):e;return n?oe(ne(n,t)):void 0};var Se="[data-icon], i.ip[class*='ip-']",Xe=new Set(["none","wiggle","pop","bounce","draw"]),Ie=new Set,Ze=e=>{let t=e.getAttribute("data-icon");if(t)return t;for(let n of Array.from(e.classList))if(n.startsWith("ip-")&&n.length>3)return n.slice(3)},Ee=e=>{if(e===null)return;let t=Number(e);return Number.isFinite(t)&&t>0?t:void 0},re=e=>{var u,d,f,a;let t=Ze(e);if(!t)return;let n=R(t),o=e.getAttribute("data-motion"),r=o&&Xe.has(o)?o:void 0,s={size:(u=Ee(e.getAttribute("data-size")))!=null?u:24,color:(d=e.getAttribute("data-color"))!=null?d:void 0,strokeScale:Ee(e.getAttribute("data-stroke")),motion:r,label:(f=e.getAttribute("data-label"))!=null?f:void 0},i=JSON.stringify([t,s,n?"1":"0"]);if(e.getAttribute("data-ip-rendered")!==i){if(!n){ke(t)?Ie.has(t)||(Ie.add(t),console.warn(`iconplease: no icon named "${t}".`)):ee(t);return}e.innerHTML=oe(ne(n,s)),e.setAttribute("data-ip-rendered",i),e.tagName==="I"&&((a=e.style).display||(a.display="inline-flex"))}},B=(e=document)=>{e instanceof Element&&e.matches(Se)&&re(e),e.querySelectorAll(Se).forEach(re)},Ae=()=>{let e=window.iconpleaseConfig;e&&z(e),we(()=>B()),B(),te(),new MutationObserver(t=>{for(let n of t)n.type==="attributes"&&n.target instanceof Element&&re(n.target),n.addedNodes.forEach(o=>{o instanceof Element&&B(o)})}).observe(document.documentElement,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["data-icon","data-size","data-color","data-stroke","data-motion","data-label","class"]})};window.iconplease={init:z,load:te,renderSVG:xe,refresh:()=>B()};document.readyState==="loading"?document.addEventListener("DOMContentLoaded",Ae,{once:!0}):Ae();})();
|
package/dist/index.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
export { init, getConfig } from "./config.js";
|
|
2
|
-
export { load, loadSet, requestIcon, subscribe, getIcon, getStatus, iconNames, setIconNames, isUnknown } from "./store.js";
|
|
2
|
+
export { load, loadSet, requestIcon, subscribe, getIcon, getStatus, iconNames, setIconNames, isUnknown, bundledIcon } from "./store.js";
|
|
3
3
|
export { renderSVG, prepare } from "./render.js";
|
|
4
4
|
export type { RenderOptions, Prepared } from "./render.js";
|
|
5
5
|
export type { LoadOptions } from "./store.js";
|
|
6
|
-
export type { Config, IconData, IconIndex, IconMotion, Status } from "./types.js";
|
|
6
|
+
export type { Config, IconData, IconIndex, IconMotion, Status, BundledSet, BundledIcon, TokenSource } from "./types.js";
|
package/dist/index.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
export { init, getConfig } from "./config.js";
|
|
2
|
-
export { load, loadSet, requestIcon, subscribe, getIcon, getStatus, iconNames, setIconNames, isUnknown } from "./store.js";
|
|
2
|
+
export { load, loadSet, requestIcon, subscribe, getIcon, getStatus, iconNames, setIconNames, isUnknown, bundledIcon } from "./store.js";
|
|
3
3
|
export { renderSVG, prepare } from "./render.js";
|
package/dist/react.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { jsx as _jsx } from "react/jsx-runtime";
|
|
2
2
|
import { useEffect, useSyncExternalStore } from "react";
|
|
3
3
|
import { prepare } from "./render.js";
|
|
4
|
-
import { getIcon, getSnapshot, isUnknown, requestIcon, subscribe } from "./store.js";
|
|
4
|
+
import { bundledIcon, getIcon, getSnapshot, isUnknown, requestIcon, subscribe } from "./store.js";
|
|
5
5
|
const serverSnapshot = { status: "idle", revision: 0 };
|
|
6
6
|
const getServerSnapshot = () => serverSnapshot;
|
|
7
7
|
const REACT_NAMES = {
|
|
@@ -23,7 +23,7 @@ export const Iconplease = ({ icon, size = 24, className, label, ...options }) =>
|
|
|
23
23
|
useEffect(() => {
|
|
24
24
|
void requestIcon(icon);
|
|
25
25
|
}, [icon]);
|
|
26
|
-
const data = state === serverSnapshot ?
|
|
26
|
+
const data = state === serverSnapshot ? bundledIcon(icon) : getIcon(icon);
|
|
27
27
|
if (!data) {
|
|
28
28
|
if (state !== serverSnapshot && isUnknown(icon) && !warned.has(icon)) {
|
|
29
29
|
warned.add(icon);
|
package/dist/store.d.ts
CHANGED
package/dist/store.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { apiBase, apiKey, cdnBase, revalidateMs } from "./config.js";
|
|
1
|
+
import { apiBase, apiKey, bundledSet, cdnBase, revalidateMs, tokenSource } from "./config.js";
|
|
2
2
|
import { cleanIcon } from "./sanitize.js";
|
|
3
3
|
const INDEX_KEY = "iconplease:index:v2";
|
|
4
4
|
const ICONS_KEY = "iconplease:icons:v2";
|
|
@@ -19,6 +19,45 @@ let setLoaded = false;
|
|
|
19
19
|
let setInflight;
|
|
20
20
|
let warnedSet = false;
|
|
21
21
|
const iconInflight = new Map();
|
|
22
|
+
let liveVersion = null;
|
|
23
|
+
let setRetryAt = 0;
|
|
24
|
+
const SET_RETRY_MS = 60000;
|
|
25
|
+
let appliedBundle;
|
|
26
|
+
let bundleVersion = null;
|
|
27
|
+
const bundleOwn = new Map();
|
|
28
|
+
const bundlePublic = new Map();
|
|
29
|
+
const syncBundle = () => {
|
|
30
|
+
const bundle = bundledSet();
|
|
31
|
+
if (bundle === appliedBundle)
|
|
32
|
+
return;
|
|
33
|
+
appliedBundle = bundle;
|
|
34
|
+
bundleOwn.clear();
|
|
35
|
+
bundlePublic.clear();
|
|
36
|
+
bundleVersion = null;
|
|
37
|
+
if (!bundle || bundle.format !== 1 || typeof bundle.icons !== "object")
|
|
38
|
+
return;
|
|
39
|
+
bundleVersion = typeof bundle.version === "number" ? bundle.version : null;
|
|
40
|
+
for (const [name, entry] of Object.entries(bundle.icons)) {
|
|
41
|
+
if (!NAME.test(name) || typeof entry?.svg !== "string")
|
|
42
|
+
continue;
|
|
43
|
+
const icon = parseSVG(entry.svg);
|
|
44
|
+
if (!icon)
|
|
45
|
+
continue;
|
|
46
|
+
(entry.source === "public" ? bundlePublic : bundleOwn).set(name, icon);
|
|
47
|
+
}
|
|
48
|
+
};
|
|
49
|
+
const liveWins = () => liveVersion !== null && (bundleVersion === null || liveVersion > bundleVersion);
|
|
50
|
+
const ownIcon = (name) => {
|
|
51
|
+
if (!appliedBundle)
|
|
52
|
+
return setIcons.get(name);
|
|
53
|
+
if (liveWins())
|
|
54
|
+
return setIcons.get(name) ?? bundlePublic.get(name);
|
|
55
|
+
return bundleOwn.get(name) ?? bundlePublic.get(name);
|
|
56
|
+
};
|
|
57
|
+
export const bundledIcon = (name) => {
|
|
58
|
+
syncBundle();
|
|
59
|
+
return bundleOwn.get(name) ?? bundlePublic.get(name);
|
|
60
|
+
};
|
|
22
61
|
const listeners = new Set();
|
|
23
62
|
const storage = () => {
|
|
24
63
|
try {
|
|
@@ -45,9 +84,41 @@ const cleanIndex = (raw) => {
|
|
|
45
84
|
return { format: 2, hash: data.hash, icons: Object.fromEntries(entries) };
|
|
46
85
|
};
|
|
47
86
|
const keyTag = (key) => key.slice(0, 14);
|
|
48
|
-
const
|
|
87
|
+
const sourceTag = () => {
|
|
88
|
+
if (tokenSource())
|
|
89
|
+
return "token";
|
|
49
90
|
const key = apiKey();
|
|
50
|
-
|
|
91
|
+
return key ? keyTag(key) : undefined;
|
|
92
|
+
};
|
|
93
|
+
const TOKEN_MARGIN_MS = 60000;
|
|
94
|
+
const DEFAULT_TOKEN_MS = 9 * 60000;
|
|
95
|
+
let cachedToken;
|
|
96
|
+
let tokenInflight;
|
|
97
|
+
const freshToken = (force = false) => {
|
|
98
|
+
const source = tokenSource();
|
|
99
|
+
if (!source)
|
|
100
|
+
return Promise.reject(new Error("no token source"));
|
|
101
|
+
if (!force && cachedToken && cachedToken.expiresAt - TOKEN_MARGIN_MS > Date.now())
|
|
102
|
+
return Promise.resolve(cachedToken.token);
|
|
103
|
+
if (tokenInflight)
|
|
104
|
+
return tokenInflight;
|
|
105
|
+
tokenInflight = source()
|
|
106
|
+
.then((answer) => {
|
|
107
|
+
const token = typeof answer === "string" ? answer : answer?.token;
|
|
108
|
+
if (typeof token !== "string" || !token.startsWith("ipt_"))
|
|
109
|
+
throw new Error("your token function did not return an iconplease token (ipt_…).");
|
|
110
|
+
const raw = typeof answer === "string" ? undefined : answer.expiresAt;
|
|
111
|
+
const at = typeof raw === "number" ? raw : raw ? Date.parse(raw) : NaN;
|
|
112
|
+
cachedToken = { token, expiresAt: Number.isFinite(at) ? at : Date.now() + DEFAULT_TOKEN_MS };
|
|
113
|
+
return token;
|
|
114
|
+
})
|
|
115
|
+
.finally(() => {
|
|
116
|
+
tokenInflight = undefined;
|
|
117
|
+
});
|
|
118
|
+
return tokenInflight;
|
|
119
|
+
};
|
|
120
|
+
const syncSetKey = () => {
|
|
121
|
+
const tag = sourceTag();
|
|
51
122
|
if (tag === setFor)
|
|
52
123
|
return;
|
|
53
124
|
setFor = tag;
|
|
@@ -56,9 +127,13 @@ const syncSetKey = () => {
|
|
|
56
127
|
setLoaded = false;
|
|
57
128
|
setInflight = undefined;
|
|
58
129
|
warnedSet = false;
|
|
130
|
+
liveVersion = null;
|
|
131
|
+
setRetryAt = 0;
|
|
59
132
|
if (!tag)
|
|
60
133
|
return;
|
|
61
134
|
try {
|
|
135
|
+
if (tag === "token")
|
|
136
|
+
return;
|
|
62
137
|
const cached = JSON.parse(storage()?.getItem(SET_KEY) ?? "null");
|
|
63
138
|
if (!cached || cached.tag !== tag)
|
|
64
139
|
return;
|
|
@@ -68,6 +143,7 @@ const syncSetKey = () => {
|
|
|
68
143
|
setIcons.set(name, icon);
|
|
69
144
|
}
|
|
70
145
|
setCheckedAt = typeof cached.checkedAt === "number" ? cached.checkedAt : 0;
|
|
146
|
+
liveVersion = typeof cached.version === "number" ? cached.version : null;
|
|
71
147
|
setLoaded = true;
|
|
72
148
|
}
|
|
73
149
|
catch {
|
|
@@ -75,6 +151,7 @@ const syncSetKey = () => {
|
|
|
75
151
|
}
|
|
76
152
|
};
|
|
77
153
|
const hydrate = () => {
|
|
154
|
+
syncBundle();
|
|
78
155
|
syncSetKey();
|
|
79
156
|
if (hydrated)
|
|
80
157
|
return;
|
|
@@ -222,8 +299,18 @@ const fetchIcon = (name, version) => {
|
|
|
222
299
|
iconInflight.set(key, request);
|
|
223
300
|
return request;
|
|
224
301
|
};
|
|
225
|
-
const
|
|
226
|
-
|
|
302
|
+
const requestSet = async (force = false) => {
|
|
303
|
+
if (!tokenSource()) {
|
|
304
|
+
const key = apiKey() ?? "";
|
|
305
|
+
return fetch(`${apiBase()}/sdk/set?key=${encodeURIComponent(key)}`);
|
|
306
|
+
}
|
|
307
|
+
const token = await freshToken(force);
|
|
308
|
+
return fetch(`${apiBase()}/sdk/set`, { headers: { Authorization: `Bearer ${token}` } });
|
|
309
|
+
};
|
|
310
|
+
const fetchSet = async (tag) => {
|
|
311
|
+
let response = await requestSet();
|
|
312
|
+
if (response.status === 401 && tokenSource())
|
|
313
|
+
response = await requestSet(true);
|
|
227
314
|
const body = (await response.json().catch(() => ({})));
|
|
228
315
|
if (!response.ok)
|
|
229
316
|
throw new Error(body.error || `HTTP ${response.status}`);
|
|
@@ -238,15 +325,17 @@ const fetchSet = async (key) => {
|
|
|
238
325
|
next.set(name, icon);
|
|
239
326
|
raw[name] = { version: Number(entry.version) || 1, svg: entry.svg };
|
|
240
327
|
}
|
|
241
|
-
if (
|
|
328
|
+
if (tag !== setFor)
|
|
242
329
|
return;
|
|
243
330
|
setIcons.clear();
|
|
244
331
|
for (const [name, icon] of next)
|
|
245
332
|
setIcons.set(name, icon);
|
|
246
333
|
setCheckedAt = Date.now();
|
|
247
334
|
setLoaded = true;
|
|
335
|
+
liveVersion = typeof body.version === "number" ? body.version : null;
|
|
248
336
|
try {
|
|
249
|
-
|
|
337
|
+
if (tag !== "token")
|
|
338
|
+
storage()?.setItem(SET_KEY, JSON.stringify({ tag, checkedAt: setCheckedAt, version: liveVersion, icons: raw }));
|
|
250
339
|
}
|
|
251
340
|
catch {
|
|
252
341
|
notify();
|
|
@@ -256,17 +345,20 @@ const fetchSet = async (key) => {
|
|
|
256
345
|
};
|
|
257
346
|
export const loadSet = (options = {}) => {
|
|
258
347
|
hydrate();
|
|
259
|
-
const
|
|
260
|
-
if (!
|
|
348
|
+
const tag = sourceTag();
|
|
349
|
+
if (!tag)
|
|
261
350
|
return Promise.resolve();
|
|
262
351
|
const fresh = setLoaded && Date.now() - setCheckedAt < revalidateMs();
|
|
263
352
|
if (fresh && !options.force)
|
|
264
353
|
return Promise.resolve();
|
|
354
|
+
if (!options.force && Date.now() < setRetryAt)
|
|
355
|
+
return Promise.resolve();
|
|
265
356
|
if (setInflight)
|
|
266
357
|
return setInflight;
|
|
267
|
-
const pending = fetchSet(
|
|
358
|
+
const pending = fetchSet(tag)
|
|
268
359
|
.catch((error) => {
|
|
269
360
|
setLoaded = true;
|
|
361
|
+
setRetryAt = Date.now() + SET_RETRY_MS;
|
|
270
362
|
if (!warnedSet) {
|
|
271
363
|
warnedSet = true;
|
|
272
364
|
console.warn(`iconplease: could not load your icon set — ${error instanceof Error ? error.message : String(error)} Falling back to public icons.`);
|
|
@@ -283,15 +375,18 @@ export const requestIcon = async (name) => {
|
|
|
283
375
|
if (!NAME.test(name))
|
|
284
376
|
return;
|
|
285
377
|
hydrate();
|
|
286
|
-
if (
|
|
287
|
-
if (
|
|
378
|
+
if (sourceTag()) {
|
|
379
|
+
if (ownIcon(name)) {
|
|
288
380
|
void loadSet();
|
|
289
381
|
return;
|
|
290
382
|
}
|
|
291
383
|
await loadSet();
|
|
292
|
-
if (
|
|
384
|
+
if (ownIcon(name))
|
|
293
385
|
return;
|
|
294
386
|
}
|
|
387
|
+
else if (ownIcon(name)) {
|
|
388
|
+
return;
|
|
389
|
+
}
|
|
295
390
|
const known = state.index?.icons[name];
|
|
296
391
|
if (known && icons.has(keyOf(name, known))) {
|
|
297
392
|
void loadIndex();
|
|
@@ -304,7 +399,11 @@ export const requestIcon = async (name) => {
|
|
|
304
399
|
};
|
|
305
400
|
export const load = async (options = {}) => {
|
|
306
401
|
const { icons: names = [], force = false } = Array.isArray(options) ? { icons: options } : options;
|
|
307
|
-
|
|
402
|
+
hydrate();
|
|
403
|
+
const bundledOnly = appliedBundle && !sourceTag() && names.every((name) => ownIcon(name));
|
|
404
|
+
if (bundledOnly)
|
|
405
|
+
return;
|
|
406
|
+
await Promise.all([appliedBundle ? Promise.resolve() : loadIndex({ force }), loadSet({ force })]);
|
|
308
407
|
await Promise.all(names.map(requestIcon));
|
|
309
408
|
};
|
|
310
409
|
export const subscribe = (listener) => {
|
|
@@ -319,7 +418,7 @@ export const getSnapshot = () => {
|
|
|
319
418
|
export const getStatus = () => getSnapshot().status;
|
|
320
419
|
export const getIcon = (name) => {
|
|
321
420
|
hydrate();
|
|
322
|
-
const own =
|
|
421
|
+
const own = ownIcon(name);
|
|
323
422
|
if (own)
|
|
324
423
|
return own;
|
|
325
424
|
const version = state.index?.icons[name];
|
|
@@ -327,17 +426,19 @@ export const getIcon = (name) => {
|
|
|
327
426
|
};
|
|
328
427
|
export const isUnknown = (name) => {
|
|
329
428
|
hydrate();
|
|
330
|
-
if (
|
|
429
|
+
if (ownIcon(name))
|
|
331
430
|
return false;
|
|
332
|
-
if (
|
|
431
|
+
if (sourceTag() && !setLoaded)
|
|
333
432
|
return false;
|
|
334
433
|
return state.status === "ready" && !!state.index && !(name in state.index.icons);
|
|
335
434
|
};
|
|
336
435
|
export const setIconNames = () => {
|
|
337
436
|
hydrate();
|
|
338
|
-
|
|
437
|
+
if (!appliedBundle)
|
|
438
|
+
return [...setIcons.keys()];
|
|
439
|
+
return liveWins() ? [...setIcons.keys()] : [...bundleOwn.keys()];
|
|
339
440
|
};
|
|
340
|
-
export const iconNames = () => [...new Set([...setIconNames(), ...Object.keys(getSnapshot().index?.icons ?? {})])];
|
|
441
|
+
export const iconNames = () => [...new Set([...setIconNames(), ...bundlePublic.keys(), ...Object.keys(getSnapshot().index?.icons ?? {})])];
|
|
341
442
|
export const resetForTests = () => {
|
|
342
443
|
state = { status: "idle", revision: 0 };
|
|
343
444
|
checkedAt = 0;
|
|
@@ -352,6 +453,14 @@ export const resetForTests = () => {
|
|
|
352
453
|
setLoaded = false;
|
|
353
454
|
setInflight = undefined;
|
|
354
455
|
warnedSet = false;
|
|
456
|
+
cachedToken = undefined;
|
|
457
|
+
tokenInflight = undefined;
|
|
458
|
+
liveVersion = null;
|
|
459
|
+
setRetryAt = 0;
|
|
460
|
+
appliedBundle = undefined;
|
|
461
|
+
bundleVersion = null;
|
|
462
|
+
bundleOwn.clear();
|
|
463
|
+
bundlePublic.clear();
|
|
355
464
|
if (persistTimer)
|
|
356
465
|
clearTimeout(persistTimer);
|
|
357
466
|
persistTimer = undefined;
|
package/dist/types.d.ts
CHANGED
|
@@ -20,5 +20,25 @@ export type Config = {
|
|
|
20
20
|
apiUrl?: string;
|
|
21
21
|
revalidate?: number;
|
|
22
22
|
apiKey?: string;
|
|
23
|
+
token?: TokenSource;
|
|
24
|
+
set?: BundledSet;
|
|
23
25
|
};
|
|
26
|
+
export type BundledIcon = {
|
|
27
|
+
version: number;
|
|
28
|
+
svg: string;
|
|
29
|
+
source: "set" | "public";
|
|
30
|
+
};
|
|
31
|
+
export type BundledSet = {
|
|
32
|
+
format: 1;
|
|
33
|
+
version: number | null;
|
|
34
|
+
workspace?: {
|
|
35
|
+
id: string;
|
|
36
|
+
name: string;
|
|
37
|
+
} | null;
|
|
38
|
+
icons: Record<string, BundledIcon>;
|
|
39
|
+
};
|
|
40
|
+
export type TokenSource = () => Promise<string | {
|
|
41
|
+
token: string;
|
|
42
|
+
expiresAt?: string | number;
|
|
43
|
+
}>;
|
|
24
44
|
export type Status = "idle" | "loading" | "ready" | "error";
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "iconplease",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"description": "Icons you can draw yourself.
|
|
3
|
+
"version": "0.3.0",
|
|
4
|
+
"description": "Icons you can draw yourself. Pages load only the icons they show from the iconplease CDN; private sets via a key, a token or a build-time file.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"icons",
|
|
7
7
|
"icon",
|
|
@@ -34,6 +34,7 @@
|
|
|
34
34
|
},
|
|
35
35
|
"files": [
|
|
36
36
|
"dist",
|
|
37
|
+
"bin",
|
|
37
38
|
"README.md"
|
|
38
39
|
],
|
|
39
40
|
"engines": {
|
|
@@ -61,5 +62,8 @@
|
|
|
61
62
|
"react": "^19.3.0",
|
|
62
63
|
"react-dom": "^19.3.0",
|
|
63
64
|
"typescript": "^5.8.3"
|
|
65
|
+
},
|
|
66
|
+
"bin": {
|
|
67
|
+
"iconplease": "./bin/iconplease.mjs"
|
|
64
68
|
}
|
|
65
69
|
}
|