iconplease 0.1.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 +73 -6
- package/bin/iconplease.mjs +187 -0
- package/dist/config.d.ts +4 -0
- package/dist/config.js +11 -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 +5 -0
- package/dist/store.js +233 -3
- package/dist/types.d.ts +21 -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
|
|
|
@@ -55,6 +56,72 @@ const svg = renderSVG("heart", { size: 32 }); // string, or undefined if unkno
|
|
|
55
56
|
const names = iconNames();
|
|
56
57
|
```
|
|
57
58
|
|
|
59
|
+
## Your own set
|
|
60
|
+
|
|
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.
|
|
78
|
+
|
|
79
|
+
```ts
|
|
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
|
|
90
|
+
init({ apiKey: "ip_pk_…" });
|
|
91
|
+
```
|
|
92
|
+
|
|
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.
|
|
124
|
+
|
|
58
125
|
## How loading works
|
|
59
126
|
|
|
60
127
|
- The SDK downloads a small **index** of icon names (about 1.5 KB for the whole catalogue), then
|
|
@@ -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
|
@@ -3,3 +3,7 @@ export declare const init: (next?: Config) => Config;
|
|
|
3
3
|
export declare const getConfig: () => Config;
|
|
4
4
|
export declare const cdnBase: () => string;
|
|
5
5
|
export declare const revalidateMs: () => number;
|
|
6
|
+
export declare const apiBase: () => string;
|
|
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
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
const DEFAULTS = {
|
|
2
2
|
cdnUrl: "https://cdn.iconplease.com",
|
|
3
|
+
apiUrl: "https://api.iconplease.com",
|
|
3
4
|
revalidate: 3600,
|
|
4
5
|
};
|
|
5
6
|
let config = { ...DEFAULTS };
|
|
@@ -7,9 +8,19 @@ export const init = (next = {}) => {
|
|
|
7
8
|
if (next.apiKey && next.apiKey.startsWith("ip_sk_")) {
|
|
8
9
|
throw new Error("iconplease: that is a secret key. init() runs in the browser, where the key is readable by anyone — use the publishable key (ip_pk_…).");
|
|
9
10
|
}
|
|
11
|
+
if (next.apiKey && !/^ip_pk_[A-Za-z0-9]{32}$/.test(next.apiKey)) {
|
|
12
|
+
console.warn("iconplease: that does not look like a publishable key (ip_pk_ followed by 32 characters). Set icons will not load.");
|
|
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
|
+
}
|
|
10
17
|
config = { ...DEFAULTS, ...next };
|
|
11
18
|
return config;
|
|
12
19
|
};
|
|
13
20
|
export const getConfig = () => config;
|
|
14
21
|
export const cdnBase = () => (config.cdnUrl ?? DEFAULTS.cdnUrl).replace(/\/+$/, "");
|
|
15
22
|
export const revalidateMs = () => Math.max(0, config.revalidate ?? DEFAULTS.revalidate) * 1000;
|
|
23
|
+
export const apiBase = () => (config.apiUrl ?? DEFAULTS.apiUrl).replace(/\/+$/, "");
|
|
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 h={cdnUrl:"https://cdn.iconplease.com",revalidate:3600},m={...h},S=(t={})=>{if(t.apiKey&&t.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 m={...h,...t},m};var k=()=>{var t;return((t=m.cdnUrl)!=null?t:h.cdnUrl).replace(/\/+$/,"")},L=()=>{var t;return Math.max(0,(t=m.revalidate)!=null?t:h.revalidate)*1e3};var ot=/<\s*(script|foreignObject|iframe|object|embed|style)\b[\s\S]*?(<\s*\/\s*\1\s*>|\/>)/gi,rt=/\s+on[a-z]+\s*=\s*("[^"]*"|'[^']*'|[^\s>]+)/gi,st=/\s+(?:xlink:)?href\s*=\s*("\s*javascript:[^"]*"|'\s*javascript:[^']*')/gi,it=/^[a-z][a-z0-9-]*$/,at=/^[^"<>]*$/,ct=t=>t.replace(ot,"").replace(rt,"").replace(st,""),E=t=>{var o;if(!t||typeof t!="object")return;let e=t;if(typeof e.body!="string"||typeof e.viewBox!="string"||!/^[0-9.\s-]+$/.test(e.viewBox))return;let n={};for(let[r,s]of Object.entries((o=e.attrs)!=null?o:{}))it.test(r)&&!r.startsWith("on")&&typeof s=="string"&&at.test(s)&&(n[r]=s);return{viewBox:e.viewBox,attrs:n,body:ct(e.body)}};var J="iconplease:index:v2",q="iconplease:icons:v2",dt=1e3,H=/^[a-z0-9](?:[a-z0-9-]{0,62}[a-z0-9])?$/,i={status:"idle",revision:0},w=0,b,_=!1,B=!1,O,u=new Map,A=new Map,$=new Set,C=()=>{try{return typeof localStorage=="undefined"?void 0:localStorage}catch{return}},y=(t={})=>{i={...i,...t,revision:i.revision+1};for(let e of $)e()},x=(t,e)=>`${t}@${e}`,K=t=>{if(!t||typeof t!="object")return;let e=t;if(e.format!==2||typeof e.hash!="string"||!e.icons||typeof e.icons!="object")return;let n=Object.entries(e.icons).filter(([o,r])=>H.test(o)&&Number.isInteger(r)&&r>0);return{format:2,hash:e.hash,icons:Object.fromEntries(n)}},g=()=>{var e,n;if(_)return;_=!0;let t=C();if(t){try{let o=JSON.parse((e=t.getItem(J))!=null?e:"null"),r=K(o==null?void 0:o.index);r&&(i={status:"ready",index:r,revision:i.revision},w=typeof(o==null?void 0:o.checkedAt)=="number"?o.checkedAt:0)}catch{return}try{let o=JSON.parse((n=t.getItem(q))!=null?n:"{}");for(let[r,s]of Object.entries(o)){let c=E(s);c&&u.set(r,c)}}catch{return}}},F=()=>{var t;try{(t=C())==null||t.setItem(J,JSON.stringify({index:i.index,checkedAt:w}))}catch{return}},V=()=>{O||(O=setTimeout(()=>{var n,o,r;O=void 0;let t=(o=(n=i.index)==null?void 0:n.icons)!=null?o:{},e=[...u.entries()].filter(([s])=>{let c=s.lastIndexOf("@");return t[s.slice(0,c)]===Number(s.slice(c+1))});try{(r=C())==null||r.setItem(q,JSON.stringify(Object.fromEntries(e.slice(-dt))))}catch{return}},0))},U=async t=>{let e=await fetch(t);if(!e.ok)throw new Error(`${e.status} for ${t}`);return e.json()},G=t=>{B||(B=!0,console.warn("iconplease: could not reach the icon CDN.",t))},ft=async()=>{var r;let t=k(),e=await U(`${t}/catalogue/latest.json`);if((e==null?void 0:e.format)!==2||typeof e.hash!="string"||typeof e.index!="string")throw new Error("iconplease: the catalogue pointer is malformed");if(w=Date.now(),((r=i.index)==null?void 0:r.hash)===e.hash){F();return}let n=e.index.replace(/^\/+/,"");if(!/^catalogue\/index-[a-z0-9]+\.json$/.test(n))throw new Error("iconplease: unexpected index location");let o=K(await U(`${t}/${n}`));if(!o)throw new Error("iconplease: the icon index is malformed");y({status:"ready",index:o}),F(),V()},N=(t={})=>{if(g(),i.index&&Date.now()-w<L()&&!t.force)return Promise.resolve();if(b)return b;let n=ft().catch(o=>{i.index||y({status:"error"}),G(o)}).finally(()=>{b=void 0});return b=n,!i.index&&i.status!=="loading"&&y({status:"loading"}),n},ut=t=>{let e=/<svg\b([^>]*)>([\s\S]*)<\/svg>\s*$/.exec(t.trim());if(!e)return;let n={},o="0 0 24 24";for(let[,r,s]of e[1].matchAll(/([a-zA-Z:-]+)="([^"]*)"/g))r==="viewBox"?o=s:["xmlns","width","height","aria-hidden","role","class","style"].includes(r)||(n[r]=s);return E({viewBox:o,attrs:n,body:e[2]})},lt=(t,e)=>{let n=x(t,e),o=A.get(n);if(o)return o;let r=fetch(`${k()}/v${e}/${t}.svg`).then(async s=>{if(!s.ok)throw new Error(`${s.status} for ${t}`);let c=ut(await s.text());if(!c)throw new Error(`iconplease: "${t}" is not a valid SVG`);u.set(n,c),V(),y()}).catch(G).finally(()=>{A.delete(n)});return A.set(n,r),r},j=async t=>{var o,r;if(!H.test(t))return;g();let e=(o=i.index)==null?void 0:o.icons[t];if(e&&u.has(x(t,e))){N();return}await N();let n=(r=i.index)==null?void 0:r.icons[t];n&&!u.has(x(t,n))&&await lt(t,n)},P=async(t={})=>{let{icons:e=[],force:n=!1}=Array.isArray(t)?{icons:t}:t;await N({force:n}),await Promise.all(e.map(j))},W=t=>(g(),$.add(t),()=>$.delete(t));var v=t=>{var n;g();let e=(n=i.index)==null?void 0:n.icons[t];return e?u.get(x(t,e)):void 0},X=t=>(g(),i.status==="ready"&&!!i.index&&!(t in i.index.icons));var pt=/^[#a-zA-Z0-9(),.%\s-]{1,64}$/,gt=/[<>"&]/g,mt={"<":"<",">":">",'"':""","&":"&"},ht=t=>t.replace(gt,e=>mt[e]),Y=t=>String(Number(t.toFixed(3))),bt=(t,e)=>t.replace(/\b(fill|stroke)="currentColor"/g,`$1="${e}"`),yt=(t,e)=>t.replace(/\bstroke-width="([0-9]*\.?[0-9]+)"/g,(n,o)=>`stroke-width="${Y(Number(o)*e)}"`),D=(t,e={})=>{var T;let{size:n=24,color:o,strokeScale:r,motion:s,label:c,className:l}=e,d=o&&pt.test(o)?o:void 0,f=typeof r=="number"&&Number.isFinite(r)&&r>0&&r!==1?r:void 0,a={...(T=t.attrs)!=null?T:{}};if(d)for(let z of["fill","stroke"])a[z]==="currentColor"&&(a[z]=d);f&&a["stroke-width"]&&(a["stroke-width"]=Y(Number(a["stroke-width"])*f));let p=t.body;return d&&(p=bt(p,d)),f&&(p=yt(p,f)),a.width=String(n),a.height=String(n),a.viewBox=t.viewBox,s&&s!=="none"&&(a["data-motion"]=s),c?(a.role="img",a["aria-label"]=c):a["aria-hidden"]="true",l&&(a.class=l),{attrs:a,body:p}},M=({attrs:t,body:e})=>`<svg xmlns="http://www.w3.org/2000/svg" ${Object.entries(t).map(([o,r])=>`${o}="${ht(r)}"`).join(" ")}>${e}</svg>`,Z=(t,e={})=>{let n=typeof t=="string"?v(t):t;return n?M(D(n,e)):void 0};var Q="[data-icon], i.ip[class*='ip-']",xt=new Set(["none","wiggle","pop","bounce","draw"]),tt=new Set,wt=t=>{let e=t.getAttribute("data-icon");if(e)return e;for(let n of Array.from(t.classList))if(n.startsWith("ip-")&&n.length>3)return n.slice(3)},et=t=>{if(t===null)return;let e=Number(t);return Number.isFinite(e)&&e>0?e:void 0},R=t=>{var l,d,f,a;let e=wt(t);if(!e)return;let n=v(e),o=t.getAttribute("data-motion"),r=o&&xt.has(o)?o:void 0,s={size:(l=et(t.getAttribute("data-size")))!=null?l:24,color:(d=t.getAttribute("data-color"))!=null?d:void 0,strokeScale:et(t.getAttribute("data-stroke")),motion:r,label:(f=t.getAttribute("data-label"))!=null?f:void 0},c=JSON.stringify([e,s,n?"1":"0"]);if(t.getAttribute("data-ip-rendered")!==c){if(!n){X(e)?tt.has(e)||(tt.add(e),console.warn(`iconplease: no icon named "${e}".`)):j(e);return}t.innerHTML=M(D(n,s)),t.setAttribute("data-ip-rendered",c),t.tagName==="I"&&((a=t.style).display||(a.display="inline-flex"))}},I=(t=document)=>{t instanceof Element&&t.matches(Q)&&R(t),t.querySelectorAll(Q).forEach(R)},nt=()=>{let t=window.iconpleaseConfig;t&&S(t),W(()=>I()),I(),P(),new MutationObserver(e=>{for(let n of e)n.type==="attributes"&&n.target instanceof Element&&R(n.target),n.addedNodes.forEach(o=>{o instanceof Element&&I(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:S,load:P,renderSVG:Z,refresh:()=>I()};document.readyState==="loading"?document.addEventListener("DOMContentLoaded",nt,{once:!0}):nt();})();
|
|
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, requestIcon, subscribe, getIcon, getStatus, iconNames, 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, requestIcon, subscribe, getIcon, getStatus, iconNames, 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
|
@@ -4,10 +4,14 @@ export type State = {
|
|
|
4
4
|
index?: IconIndex;
|
|
5
5
|
revision: number;
|
|
6
6
|
};
|
|
7
|
+
export declare const bundledIcon: (name: string) => IconData | undefined;
|
|
7
8
|
export declare const loadIndex: (options?: {
|
|
8
9
|
force?: boolean;
|
|
9
10
|
}) => Promise<void>;
|
|
10
11
|
export declare const parseSVG: (text: string) => IconData | undefined;
|
|
12
|
+
export declare const loadSet: (options?: {
|
|
13
|
+
force?: boolean;
|
|
14
|
+
}) => Promise<void>;
|
|
11
15
|
export declare const requestIcon: (name: string) => Promise<void>;
|
|
12
16
|
export type LoadOptions = {
|
|
13
17
|
icons?: string[];
|
|
@@ -19,5 +23,6 @@ export declare const getSnapshot: () => State;
|
|
|
19
23
|
export declare const getStatus: () => Status;
|
|
20
24
|
export declare const getIcon: (name: string) => IconData | undefined;
|
|
21
25
|
export declare const isUnknown: (name: string) => boolean;
|
|
26
|
+
export declare const setIconNames: () => string[];
|
|
22
27
|
export declare const iconNames: () => string[];
|
|
23
28
|
export declare const resetForTests: () => void;
|
package/dist/store.js
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
|
-
import { 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";
|
|
5
|
+
const SET_KEY = "iconplease:set:v1";
|
|
5
6
|
const MAX_CACHED_ICONS = 1000;
|
|
6
7
|
const NAME = /^[a-z0-9](?:[a-z0-9-]{0,62}[a-z0-9])?$/;
|
|
7
8
|
let state = { status: "idle", revision: 0 };
|
|
@@ -11,7 +12,52 @@ let hydrated = false;
|
|
|
11
12
|
let warnedOffline = false;
|
|
12
13
|
let persistTimer;
|
|
13
14
|
const icons = new Map();
|
|
15
|
+
const setIcons = new Map();
|
|
16
|
+
let setFor;
|
|
17
|
+
let setCheckedAt = 0;
|
|
18
|
+
let setLoaded = false;
|
|
19
|
+
let setInflight;
|
|
20
|
+
let warnedSet = false;
|
|
14
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
|
+
};
|
|
15
61
|
const listeners = new Set();
|
|
16
62
|
const storage = () => {
|
|
17
63
|
try {
|
|
@@ -37,7 +83,76 @@ const cleanIndex = (raw) => {
|
|
|
37
83
|
const entries = Object.entries(data.icons).filter(([name, version]) => NAME.test(name) && Number.isInteger(version) && version > 0);
|
|
38
84
|
return { format: 2, hash: data.hash, icons: Object.fromEntries(entries) };
|
|
39
85
|
};
|
|
86
|
+
const keyTag = (key) => key.slice(0, 14);
|
|
87
|
+
const sourceTag = () => {
|
|
88
|
+
if (tokenSource())
|
|
89
|
+
return "token";
|
|
90
|
+
const key = apiKey();
|
|
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();
|
|
122
|
+
if (tag === setFor)
|
|
123
|
+
return;
|
|
124
|
+
setFor = tag;
|
|
125
|
+
setIcons.clear();
|
|
126
|
+
setCheckedAt = 0;
|
|
127
|
+
setLoaded = false;
|
|
128
|
+
setInflight = undefined;
|
|
129
|
+
warnedSet = false;
|
|
130
|
+
liveVersion = null;
|
|
131
|
+
setRetryAt = 0;
|
|
132
|
+
if (!tag)
|
|
133
|
+
return;
|
|
134
|
+
try {
|
|
135
|
+
if (tag === "token")
|
|
136
|
+
return;
|
|
137
|
+
const cached = JSON.parse(storage()?.getItem(SET_KEY) ?? "null");
|
|
138
|
+
if (!cached || cached.tag !== tag)
|
|
139
|
+
return;
|
|
140
|
+
for (const [name, entry] of Object.entries(cached.icons ?? {})) {
|
|
141
|
+
const icon = NAME.test(name) && typeof entry?.svg === "string" ? parseSVG(entry.svg) : undefined;
|
|
142
|
+
if (icon)
|
|
143
|
+
setIcons.set(name, icon);
|
|
144
|
+
}
|
|
145
|
+
setCheckedAt = typeof cached.checkedAt === "number" ? cached.checkedAt : 0;
|
|
146
|
+
liveVersion = typeof cached.version === "number" ? cached.version : null;
|
|
147
|
+
setLoaded = true;
|
|
148
|
+
}
|
|
149
|
+
catch {
|
|
150
|
+
return;
|
|
151
|
+
}
|
|
152
|
+
};
|
|
40
153
|
const hydrate = () => {
|
|
154
|
+
syncBundle();
|
|
155
|
+
syncSetKey();
|
|
41
156
|
if (hydrated)
|
|
42
157
|
return;
|
|
43
158
|
hydrated = true;
|
|
@@ -184,10 +299,94 @@ const fetchIcon = (name, version) => {
|
|
|
184
299
|
iconInflight.set(key, request);
|
|
185
300
|
return request;
|
|
186
301
|
};
|
|
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);
|
|
314
|
+
const body = (await response.json().catch(() => ({})));
|
|
315
|
+
if (!response.ok)
|
|
316
|
+
throw new Error(body.error || `HTTP ${response.status}`);
|
|
317
|
+
const next = new Map();
|
|
318
|
+
const raw = {};
|
|
319
|
+
for (const [name, entry] of Object.entries(body.icons ?? {})) {
|
|
320
|
+
if (!NAME.test(name) || typeof entry?.svg !== "string")
|
|
321
|
+
continue;
|
|
322
|
+
const icon = parseSVG(entry.svg);
|
|
323
|
+
if (!icon)
|
|
324
|
+
continue;
|
|
325
|
+
next.set(name, icon);
|
|
326
|
+
raw[name] = { version: Number(entry.version) || 1, svg: entry.svg };
|
|
327
|
+
}
|
|
328
|
+
if (tag !== setFor)
|
|
329
|
+
return;
|
|
330
|
+
setIcons.clear();
|
|
331
|
+
for (const [name, icon] of next)
|
|
332
|
+
setIcons.set(name, icon);
|
|
333
|
+
setCheckedAt = Date.now();
|
|
334
|
+
setLoaded = true;
|
|
335
|
+
liveVersion = typeof body.version === "number" ? body.version : null;
|
|
336
|
+
try {
|
|
337
|
+
if (tag !== "token")
|
|
338
|
+
storage()?.setItem(SET_KEY, JSON.stringify({ tag, checkedAt: setCheckedAt, version: liveVersion, icons: raw }));
|
|
339
|
+
}
|
|
340
|
+
catch {
|
|
341
|
+
notify();
|
|
342
|
+
return;
|
|
343
|
+
}
|
|
344
|
+
notify();
|
|
345
|
+
};
|
|
346
|
+
export const loadSet = (options = {}) => {
|
|
347
|
+
hydrate();
|
|
348
|
+
const tag = sourceTag();
|
|
349
|
+
if (!tag)
|
|
350
|
+
return Promise.resolve();
|
|
351
|
+
const fresh = setLoaded && Date.now() - setCheckedAt < revalidateMs();
|
|
352
|
+
if (fresh && !options.force)
|
|
353
|
+
return Promise.resolve();
|
|
354
|
+
if (!options.force && Date.now() < setRetryAt)
|
|
355
|
+
return Promise.resolve();
|
|
356
|
+
if (setInflight)
|
|
357
|
+
return setInflight;
|
|
358
|
+
const pending = fetchSet(tag)
|
|
359
|
+
.catch((error) => {
|
|
360
|
+
setLoaded = true;
|
|
361
|
+
setRetryAt = Date.now() + SET_RETRY_MS;
|
|
362
|
+
if (!warnedSet) {
|
|
363
|
+
warnedSet = true;
|
|
364
|
+
console.warn(`iconplease: could not load your icon set — ${error instanceof Error ? error.message : String(error)} Falling back to public icons.`);
|
|
365
|
+
}
|
|
366
|
+
notify();
|
|
367
|
+
})
|
|
368
|
+
.finally(() => {
|
|
369
|
+
setInflight = undefined;
|
|
370
|
+
});
|
|
371
|
+
setInflight = pending;
|
|
372
|
+
return pending;
|
|
373
|
+
};
|
|
187
374
|
export const requestIcon = async (name) => {
|
|
188
375
|
if (!NAME.test(name))
|
|
189
376
|
return;
|
|
190
377
|
hydrate();
|
|
378
|
+
if (sourceTag()) {
|
|
379
|
+
if (ownIcon(name)) {
|
|
380
|
+
void loadSet();
|
|
381
|
+
return;
|
|
382
|
+
}
|
|
383
|
+
await loadSet();
|
|
384
|
+
if (ownIcon(name))
|
|
385
|
+
return;
|
|
386
|
+
}
|
|
387
|
+
else if (ownIcon(name)) {
|
|
388
|
+
return;
|
|
389
|
+
}
|
|
191
390
|
const known = state.index?.icons[name];
|
|
192
391
|
if (known && icons.has(keyOf(name, known))) {
|
|
193
392
|
void loadIndex();
|
|
@@ -200,7 +399,11 @@ export const requestIcon = async (name) => {
|
|
|
200
399
|
};
|
|
201
400
|
export const load = async (options = {}) => {
|
|
202
401
|
const { icons: names = [], force = false } = Array.isArray(options) ? { icons: options } : options;
|
|
203
|
-
|
|
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 })]);
|
|
204
407
|
await Promise.all(names.map(requestIcon));
|
|
205
408
|
};
|
|
206
409
|
export const subscribe = (listener) => {
|
|
@@ -215,14 +418,27 @@ export const getSnapshot = () => {
|
|
|
215
418
|
export const getStatus = () => getSnapshot().status;
|
|
216
419
|
export const getIcon = (name) => {
|
|
217
420
|
hydrate();
|
|
421
|
+
const own = ownIcon(name);
|
|
422
|
+
if (own)
|
|
423
|
+
return own;
|
|
218
424
|
const version = state.index?.icons[name];
|
|
219
425
|
return version ? icons.get(keyOf(name, version)) : undefined;
|
|
220
426
|
};
|
|
221
427
|
export const isUnknown = (name) => {
|
|
222
428
|
hydrate();
|
|
429
|
+
if (ownIcon(name))
|
|
430
|
+
return false;
|
|
431
|
+
if (sourceTag() && !setLoaded)
|
|
432
|
+
return false;
|
|
223
433
|
return state.status === "ready" && !!state.index && !(name in state.index.icons);
|
|
224
434
|
};
|
|
225
|
-
export const
|
|
435
|
+
export const setIconNames = () => {
|
|
436
|
+
hydrate();
|
|
437
|
+
if (!appliedBundle)
|
|
438
|
+
return [...setIcons.keys()];
|
|
439
|
+
return liveWins() ? [...setIcons.keys()] : [...bundleOwn.keys()];
|
|
440
|
+
};
|
|
441
|
+
export const iconNames = () => [...new Set([...setIconNames(), ...bundlePublic.keys(), ...Object.keys(getSnapshot().index?.icons ?? {})])];
|
|
226
442
|
export const resetForTests = () => {
|
|
227
443
|
state = { status: "idle", revision: 0 };
|
|
228
444
|
checkedAt = 0;
|
|
@@ -231,6 +447,20 @@ export const resetForTests = () => {
|
|
|
231
447
|
warnedOffline = false;
|
|
232
448
|
icons.clear();
|
|
233
449
|
iconInflight.clear();
|
|
450
|
+
setIcons.clear();
|
|
451
|
+
setFor = undefined;
|
|
452
|
+
setCheckedAt = 0;
|
|
453
|
+
setLoaded = false;
|
|
454
|
+
setInflight = undefined;
|
|
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();
|
|
234
464
|
if (persistTimer)
|
|
235
465
|
clearTimeout(persistTimer);
|
|
236
466
|
persistTimer = undefined;
|
package/dist/types.d.ts
CHANGED
|
@@ -17,7 +17,28 @@ export type IndexPointer = {
|
|
|
17
17
|
};
|
|
18
18
|
export type Config = {
|
|
19
19
|
cdnUrl?: string;
|
|
20
|
+
apiUrl?: string;
|
|
20
21
|
revalidate?: number;
|
|
21
22
|
apiKey?: string;
|
|
23
|
+
token?: TokenSource;
|
|
24
|
+
set?: BundledSet;
|
|
22
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
|
+
}>;
|
|
23
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
|
}
|