veyce 0.0.0-stage → 0.1.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/LICENSE +21 -0
- package/README.md +185 -2
- package/dist/cli.js +262 -0
- package/dist/index.cjs +196 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +134 -0
- package/dist/index.d.ts +134 -0
- package/dist/index.js +159 -0
- package/dist/index.js.map +1 -0
- package/dist/react.cjs +141 -0
- package/dist/react.cjs.map +1 -0
- package/dist/react.d.cts +63 -0
- package/dist/react.d.ts +63 -0
- package/dist/react.js +115 -0
- package/dist/react.js.map +1 -0
- package/package.json +76 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Mohamed Salah
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,186 @@
|
|
|
1
|
-
#
|
|
1
|
+
# veyce
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Deterministic avatars from your own image library — like DiceBear, but the
|
|
4
|
+
faces are real images served by a veyce avatar service.
|
|
5
|
+
|
|
6
|
+
- **Any seed works.** Email, username, uuid, `"hello world"`: the same seed
|
|
7
|
+
always gets the same image, and it never 404s.
|
|
8
|
+
- **Exact ids work too.** Ask for `raul` and you get `raul`, or a 404.
|
|
9
|
+
- **Both at once.** `{ id, seed }` gives you the id if it exists and falls
|
|
10
|
+
back to the seed if it doesn't.
|
|
11
|
+
- Zero dependencies, ~2 KB gzipped, ESM + CJS + types. Browser, Node 18+,
|
|
12
|
+
Bun, Deno, edge runtimes. Optional React component and a CLI.
|
|
13
|
+
|
|
14
|
+
```bash
|
|
15
|
+
npm install veyce
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
## Quick start
|
|
19
|
+
|
|
20
|
+
```ts
|
|
21
|
+
import { createAvatars } from "veyce";
|
|
22
|
+
|
|
23
|
+
const avatars = createAvatars({
|
|
24
|
+
// baseUrl defaults to https://veyce.vercel.app — pass your own to self-host
|
|
25
|
+
defaults: { collection: "gta-vi", size: 96 },
|
|
26
|
+
});
|
|
27
|
+
|
|
28
|
+
avatars.url({ seed: "ada@example.com" });
|
|
29
|
+
// https://veyce.vercel.app/api/gta-vi?seed=ada%40example.com&size=96
|
|
30
|
+
|
|
31
|
+
avatars.url({ id: "raul", square: true });
|
|
32
|
+
// https://veyce.vercel.app/api/gta-vi?id=raul&size=96&square=true
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
```html
|
|
36
|
+
<img src="https://veyce.vercel.app/api/gta-vi?seed=ada%40example.com&size=96" width="96" height="96" alt="" />
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
`url()` and `srcSet()` are pure string work — no network — so they are safe in
|
|
40
|
+
render functions, templates and server components.
|
|
41
|
+
|
|
42
|
+
## Seed vs id
|
|
43
|
+
|
|
44
|
+
| you pass | you get | unknown value |
|
|
45
|
+
| --- | --- | --- |
|
|
46
|
+
| `seed` | the image the seed hashes onto | never happens — every seed lands somewhere |
|
|
47
|
+
| `id` | that exact image | `404` |
|
|
48
|
+
| `id` + `seed` | the id if it exists, otherwise the seed's image | falls back to the seed |
|
|
49
|
+
| neither | a random image (`no-store`) | — |
|
|
50
|
+
|
|
51
|
+
Seeds are always sent as `?seed=`, so a seed that looks like an id (`raul`), a
|
|
52
|
+
size (`1234`) or a crop (`square`) is still treated as a seed.
|
|
53
|
+
|
|
54
|
+
> The mapping is stable for a fixed library. Adding or removing images in a
|
|
55
|
+
> collection reshuffles which seed lands where. If a user should keep their
|
|
56
|
+
> face forever, pin it — see `resolve()` below.
|
|
57
|
+
|
|
58
|
+
## API
|
|
59
|
+
|
|
60
|
+
### `createAvatars(config)`
|
|
61
|
+
|
|
62
|
+
```ts
|
|
63
|
+
createAvatars({
|
|
64
|
+
baseUrl?: string; // default https://veyce.vercel.app; a trailing /api is fine
|
|
65
|
+
defaults?: AvatarOptions; // merged into every call
|
|
66
|
+
fetch?: typeof fetch; // custom fetch for tests/proxies
|
|
67
|
+
}): AvatarClient
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
### `AvatarOptions`
|
|
71
|
+
|
|
72
|
+
| option | type | default | |
|
|
73
|
+
| --- | --- | --- | --- |
|
|
74
|
+
| `seed` | `string \| number` | — | Anything. Always resolves. |
|
|
75
|
+
| `id` | `string` | — | Exact image id. |
|
|
76
|
+
| `collection` | `string` | all | Narrow to one collection. |
|
|
77
|
+
| `size` | `number` | `80` | 8–2160, clamped. Never upscaled past the source. |
|
|
78
|
+
| `crop` | `square \| portrait \| landscape \| phone \| tablet \| ultrawide` | `square` | Falls back to `square` if the image lacks it. |
|
|
79
|
+
| `fit` | `cover \| full` | `cover` | `full` keeps the aspect ratio, no mask. |
|
|
80
|
+
| `square` | `boolean` | `false` | Square corners instead of a circle. |
|
|
81
|
+
| `format` | `webp \| png \| jpeg` | `webp` | |
|
|
82
|
+
| `background` | hex | `#ffffff` | Corner fill for circle-masked JPEGs. |
|
|
83
|
+
|
|
84
|
+
### Client methods
|
|
85
|
+
|
|
86
|
+
```ts
|
|
87
|
+
avatars.url(options) // string
|
|
88
|
+
avatars.srcSet(options) // "url 1x, url 2x, url 3x"
|
|
89
|
+
await avatars.fetch(options) // { bytes: Uint8Array, contentType, info }
|
|
90
|
+
await avatars.dataUri(options) // "data:image/webp;base64,..."
|
|
91
|
+
await avatars.resolve(options) // AvatarInfo, via HEAD — no image download
|
|
92
|
+
await avatars.list(collection?) // the library index
|
|
93
|
+
avatars.pick(seed, index) // offline seed -> photo, same answer as the API
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
`AvatarInfo` tells you what the API picked:
|
|
97
|
+
|
|
98
|
+
```ts
|
|
99
|
+
{ collection: "gta-vi", id: "cal", crop: "square", size: 96,
|
|
100
|
+
match: "seed", // "id" | "seed" | "random"
|
|
101
|
+
url: "https://veyce.vercel.app/api/gta-vi?id=cal" } // stable, id-addressed
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
#### Pinning a seeded avatar
|
|
105
|
+
|
|
106
|
+
Give a new user a seeded face, then store the id so it survives library changes:
|
|
107
|
+
|
|
108
|
+
```ts
|
|
109
|
+
const { id } = await avatars.resolve({ seed: user.email });
|
|
110
|
+
await db.users.update(user.id, { avatarId: id });
|
|
111
|
+
|
|
112
|
+
// later — exact id, with the email as a safety net if that image is ever removed
|
|
113
|
+
avatars.url({ id: user.avatarId, seed: user.email });
|
|
114
|
+
```
|
|
115
|
+
|
|
116
|
+
#### Offline picks
|
|
117
|
+
|
|
118
|
+
Fetch the index once (cache it), then map seeds locally — useful for batch
|
|
119
|
+
jobs or when you want ids without one request per user:
|
|
120
|
+
|
|
121
|
+
```ts
|
|
122
|
+
const index = await avatars.list("gta-vi");
|
|
123
|
+
const photo = avatars.pick("ada@example.com", index); // { id: "cal", ... }
|
|
124
|
+
```
|
|
125
|
+
|
|
126
|
+
### Standalone helpers
|
|
127
|
+
|
|
128
|
+
```ts
|
|
129
|
+
import { avatarUrl, avatarSrcSet, hashSeed, pick, AvatarError } from "veyce";
|
|
130
|
+
|
|
131
|
+
avatarUrl("https://veyce.vercel.app", { seed: "ada" });
|
|
132
|
+
```
|
|
133
|
+
|
|
134
|
+
Failed requests throw `AvatarError` with `.status` (404 unknown id/collection,
|
|
135
|
+
409 id in several collections) and the parsed `.body`.
|
|
136
|
+
|
|
137
|
+
## React
|
|
138
|
+
|
|
139
|
+
```tsx
|
|
140
|
+
import { Avatar, AvatarProvider, useAvatarUrl } from "veyce/react";
|
|
141
|
+
|
|
142
|
+
export function App() {
|
|
143
|
+
return (
|
|
144
|
+
<AvatarProvider defaults={{ collection: "gta-vi" }}>
|
|
145
|
+
<Avatar seed="ada@example.com" size={48} />
|
|
146
|
+
<Avatar id={user.avatarId} seed={user.email} size={64} square className="rounded-lg" />
|
|
147
|
+
</AvatarProvider>
|
|
148
|
+
);
|
|
149
|
+
}
|
|
150
|
+
```
|
|
151
|
+
|
|
152
|
+
`<Avatar>` renders a plain `<img>` with `width`/`height` set (no layout shift),
|
|
153
|
+
`loading="lazy"`, `decoding="async"` and a 1x/2x/3x `srcSet` (`hiDpi={false}`
|
|
154
|
+
to turn it off). Every other `<img>` prop passes through; the HTML `id`
|
|
155
|
+
attribute is `htmlId` because `id` is the image id. You can also pass
|
|
156
|
+
`baseUrl` straight to `<Avatar>` and skip the provider — or omit it entirely to
|
|
157
|
+
use https://veyce.vercel.app.
|
|
158
|
+
|
|
159
|
+
The entry is marked `"use client"`, so it works from Next.js server components.
|
|
160
|
+
If you only need the URL in a server component, call `avatarUrl()` from the
|
|
161
|
+
main entry instead.
|
|
162
|
+
|
|
163
|
+
## CLI
|
|
164
|
+
|
|
165
|
+
```bash
|
|
166
|
+
npx veyce url --seed ada@example.com -c gta-vi --size 96
|
|
167
|
+
npx veyce get --seed ada@example.com --size 256 -o ada.webp
|
|
168
|
+
npx veyce resolve --seed ada@example.com
|
|
169
|
+
npx veyce list --collection gta-vi
|
|
170
|
+
```
|
|
171
|
+
|
|
172
|
+
Requests go to `https://veyce.vercel.app` unless you pass `--base URL` or set
|
|
173
|
+
`VEYCE_URL`. `veyce --help` lists every flag.
|
|
174
|
+
|
|
175
|
+
## License
|
|
176
|
+
|
|
177
|
+
MIT for the package code — see [LICENSE](LICENSE).
|
|
178
|
+
|
|
179
|
+
This package contains no images. It only builds URLs for, and fetches from, a
|
|
180
|
+
veyce service that you or someone else hosts. The images served by any such
|
|
181
|
+
service belong to their respective owners, not to this package; check the
|
|
182
|
+
service's terms and the rights holder's before storing or redistributing them.
|
|
183
|
+
|
|
184
|
+
veyce is an independent project and is not affiliated with DiceBear, Gravatar,
|
|
185
|
+
Rockstar Games or Take-Two Interactive. Product names are used only to describe
|
|
186
|
+
compatibility or comparison.
|
package/dist/cli.js
ADDED
|
@@ -0,0 +1,262 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
// src/cli.ts
|
|
4
|
+
import { writeFile } from "fs/promises";
|
|
5
|
+
import { parseArgs } from "util";
|
|
6
|
+
|
|
7
|
+
// src/index.ts
|
|
8
|
+
var DEFAULT_BASE_URL = "https://veyce.vercel.app";
|
|
9
|
+
var MIN_SIZE = 8;
|
|
10
|
+
var MAX_SIZE = 2160;
|
|
11
|
+
var DEFAULT_SIZE = 80;
|
|
12
|
+
var FORMATS = ["webp", "png", "jpeg"];
|
|
13
|
+
var AvatarError = class extends Error {
|
|
14
|
+
constructor(message, status, body) {
|
|
15
|
+
super(message);
|
|
16
|
+
this.name = "AvatarError";
|
|
17
|
+
this.status = status;
|
|
18
|
+
this.body = body;
|
|
19
|
+
}
|
|
20
|
+
};
|
|
21
|
+
function hashSeed(seed) {
|
|
22
|
+
const value = String(seed);
|
|
23
|
+
let hash = 0;
|
|
24
|
+
for (let i = 0; i < value.length; i += 1) {
|
|
25
|
+
hash = (hash << 5) - hash + value.charCodeAt(i);
|
|
26
|
+
hash |= 0;
|
|
27
|
+
}
|
|
28
|
+
return Math.abs(hash) || 1;
|
|
29
|
+
}
|
|
30
|
+
function pick(seed, photos) {
|
|
31
|
+
if (!photos.length) return void 0;
|
|
32
|
+
return photos[hashSeed(seed) % photos.length];
|
|
33
|
+
}
|
|
34
|
+
function clampSize(size) {
|
|
35
|
+
if (!Number.isFinite(size)) return DEFAULT_SIZE;
|
|
36
|
+
return Math.min(MAX_SIZE, Math.max(MIN_SIZE, Math.round(size)));
|
|
37
|
+
}
|
|
38
|
+
function apiRoot(baseUrl) {
|
|
39
|
+
const trimmed = (baseUrl || DEFAULT_BASE_URL).replace(/\/+$/, "");
|
|
40
|
+
return /\/api$/.test(trimmed) ? trimmed : `${trimmed}/api`;
|
|
41
|
+
}
|
|
42
|
+
function normalizeHex(value) {
|
|
43
|
+
const hex = value.replace(/^#/, "");
|
|
44
|
+
return /^([0-9a-f]{3}|[0-9a-f]{6})$/i.test(hex) ? hex.toLowerCase() : null;
|
|
45
|
+
}
|
|
46
|
+
function avatarUrl(baseUrl, options = {}) {
|
|
47
|
+
const root = apiRoot(baseUrl);
|
|
48
|
+
const path = options.collection ? `${root}/${encodeURIComponent(options.collection)}` : root;
|
|
49
|
+
const query = new URLSearchParams();
|
|
50
|
+
if (options.id !== void 0 && options.id !== "") query.set("id", options.id);
|
|
51
|
+
if (options.seed !== void 0 && options.seed !== "") query.set("seed", String(options.seed));
|
|
52
|
+
if (options.size !== void 0) query.set("size", String(clampSize(options.size)));
|
|
53
|
+
if (options.crop) query.set("crop", options.crop);
|
|
54
|
+
if (options.fit && options.fit !== "cover") query.set("fit", options.fit);
|
|
55
|
+
if (options.square) query.set("square", "true");
|
|
56
|
+
if (options.format && options.format !== "webp") query.set("format", options.format);
|
|
57
|
+
if (options.background) {
|
|
58
|
+
const hex = normalizeHex(options.background);
|
|
59
|
+
if (!hex) throw new TypeError(`veyce: invalid background "${options.background}".`);
|
|
60
|
+
query.set("bg", hex);
|
|
61
|
+
}
|
|
62
|
+
const qs = query.toString();
|
|
63
|
+
return qs ? `${path}?${qs}` : path;
|
|
64
|
+
}
|
|
65
|
+
function avatarSrcSet(baseUrl, options = {}, densities = [1, 2, 3]) {
|
|
66
|
+
const size = options.size ?? DEFAULT_SIZE;
|
|
67
|
+
const seen = /* @__PURE__ */ new Set();
|
|
68
|
+
return densities.map((density) => ({ density, px: clampSize(size * density) })).filter(({ px }) => seen.has(px) ? false : (seen.add(px), true)).map(({ density, px }) => `${avatarUrl(baseUrl, { ...options, size: px })} ${density}x`).join(", ");
|
|
69
|
+
}
|
|
70
|
+
function readInfo(root, headers, requested) {
|
|
71
|
+
const collection = headers.get("x-photo-collection") ?? "";
|
|
72
|
+
const id = headers.get("x-photo-id") ?? "";
|
|
73
|
+
const match = headers.get("x-photo-match") ?? "id";
|
|
74
|
+
return {
|
|
75
|
+
collection,
|
|
76
|
+
id,
|
|
77
|
+
crop: headers.get("x-photo-crop") ?? "square",
|
|
78
|
+
size: Number(headers.get("x-photo-size") ?? requested),
|
|
79
|
+
match,
|
|
80
|
+
url: avatarUrl(root, { collection, id })
|
|
81
|
+
};
|
|
82
|
+
}
|
|
83
|
+
async function fail(response) {
|
|
84
|
+
let body;
|
|
85
|
+
let message = response.status === 404 ? "veyce: no image matches (unknown id or collection) \u2014 pass a `seed` to always get one" : response.status === 409 ? "veyce: that id exists in several collections \u2014 pass `collection`" : `veyce: request failed with ${response.status}`;
|
|
86
|
+
try {
|
|
87
|
+
body = await response.json();
|
|
88
|
+
const error = body?.error;
|
|
89
|
+
if (typeof error === "string") message = `veyce: ${error}`;
|
|
90
|
+
} catch {
|
|
91
|
+
}
|
|
92
|
+
throw new AvatarError(message, response.status, body);
|
|
93
|
+
}
|
|
94
|
+
function toBase64(bytes) {
|
|
95
|
+
const B = globalThis.Buffer;
|
|
96
|
+
if (B) return B.from(bytes).toString("base64");
|
|
97
|
+
let binary = "";
|
|
98
|
+
for (let i = 0; i < bytes.length; i += 32768) {
|
|
99
|
+
binary += String.fromCharCode(...bytes.subarray(i, i + 32768));
|
|
100
|
+
}
|
|
101
|
+
return btoa(binary);
|
|
102
|
+
}
|
|
103
|
+
function createAvatars(config = {}) {
|
|
104
|
+
const root = apiRoot(config.baseUrl);
|
|
105
|
+
const defaults = config.defaults ?? {};
|
|
106
|
+
const doFetch = (input, init) => {
|
|
107
|
+
const f = config.fetch ?? globalThis.fetch;
|
|
108
|
+
if (!f) throw new Error("veyce: no global fetch; pass `fetch` in the config.");
|
|
109
|
+
return f(input, init);
|
|
110
|
+
};
|
|
111
|
+
const merge = (options) => ({ ...defaults, ...options });
|
|
112
|
+
const client = {
|
|
113
|
+
baseUrl: root,
|
|
114
|
+
url: (options) => avatarUrl(root, merge(options)),
|
|
115
|
+
srcSet: (options, densities) => avatarSrcSet(root, merge(options), densities),
|
|
116
|
+
async fetch(options) {
|
|
117
|
+
const merged = merge(options);
|
|
118
|
+
const response = await doFetch(avatarUrl(root, merged));
|
|
119
|
+
if (!response.ok) return fail(response);
|
|
120
|
+
const bytes = new Uint8Array(await response.arrayBuffer());
|
|
121
|
+
return {
|
|
122
|
+
bytes,
|
|
123
|
+
contentType: response.headers.get("content-type") ?? `image/${merged.format ?? "webp"}`,
|
|
124
|
+
info: readInfo(root, response.headers, merged.size ?? DEFAULT_SIZE)
|
|
125
|
+
};
|
|
126
|
+
},
|
|
127
|
+
async dataUri(options) {
|
|
128
|
+
const { bytes, contentType } = await client.fetch(options);
|
|
129
|
+
return `data:${contentType};base64,${toBase64(bytes)}`;
|
|
130
|
+
},
|
|
131
|
+
async resolve(options) {
|
|
132
|
+
const merged = merge(options);
|
|
133
|
+
const response = await doFetch(avatarUrl(root, merged), { method: "HEAD" });
|
|
134
|
+
if (!response.ok) return fail(response);
|
|
135
|
+
return readInfo(root, response.headers, merged.size ?? DEFAULT_SIZE);
|
|
136
|
+
},
|
|
137
|
+
async list(collection = defaults.collection) {
|
|
138
|
+
const qs = collection ? `?collection=${encodeURIComponent(collection)}` : "";
|
|
139
|
+
const response = await doFetch(`${root}/photos${qs}`);
|
|
140
|
+
if (!response.ok) return fail(response);
|
|
141
|
+
return await response.json();
|
|
142
|
+
},
|
|
143
|
+
pick(seed, index) {
|
|
144
|
+
return pick(seed, Array.isArray(index) ? index : index.photos);
|
|
145
|
+
}
|
|
146
|
+
};
|
|
147
|
+
return client;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
// src/cli.ts
|
|
151
|
+
var HELP = `veyce \u2014 avatars from your image library
|
|
152
|
+
|
|
153
|
+
Usage
|
|
154
|
+
veyce url [options] print the avatar URL
|
|
155
|
+
veyce get [options] -o FILE download the avatar
|
|
156
|
+
veyce resolve [options] which image a seed/id lands on (JSON)
|
|
157
|
+
veyce list [--collection C] list every image id (JSON)
|
|
158
|
+
|
|
159
|
+
Options
|
|
160
|
+
--base URL service URL (or set VEYCE_URL; default https://veyce.vercel.app)
|
|
161
|
+
-s, --seed TEXT any string: email, username, uuid... always resolves
|
|
162
|
+
-i, --id ID exact image id (404 if unknown, unless --seed is also given)
|
|
163
|
+
-c, --collection C collection, e.g. gta-vi
|
|
164
|
+
--size N 8-2160 (default 80)
|
|
165
|
+
--crop NAME square | portrait | landscape | phone | tablet | ultrawide
|
|
166
|
+
--fit full keep original aspect ratio
|
|
167
|
+
--square square corners instead of a circle
|
|
168
|
+
--format F webp | png | jpeg
|
|
169
|
+
--bg HEX JPEG corner fill
|
|
170
|
+
-o, --out FILE output file for \`get\` (default: <id-or-seed>.<format>)
|
|
171
|
+
-h, --help
|
|
172
|
+
|
|
173
|
+
Examples
|
|
174
|
+
veyce url --seed ada@example.com --size 96
|
|
175
|
+
veyce get --seed ada@example.com -c gta-vi --size 256 -o ada.webp
|
|
176
|
+
`;
|
|
177
|
+
async function main() {
|
|
178
|
+
const { values, positionals } = parseArgs({
|
|
179
|
+
allowPositionals: true,
|
|
180
|
+
options: {
|
|
181
|
+
base: { type: "string" },
|
|
182
|
+
seed: { type: "string", short: "s" },
|
|
183
|
+
id: { type: "string", short: "i" },
|
|
184
|
+
collection: { type: "string", short: "c" },
|
|
185
|
+
size: { type: "string" },
|
|
186
|
+
crop: { type: "string" },
|
|
187
|
+
fit: { type: "string" },
|
|
188
|
+
square: { type: "boolean" },
|
|
189
|
+
format: { type: "string" },
|
|
190
|
+
bg: { type: "string" },
|
|
191
|
+
out: { type: "string", short: "o" },
|
|
192
|
+
help: { type: "boolean", short: "h" }
|
|
193
|
+
}
|
|
194
|
+
});
|
|
195
|
+
const command = positionals[0];
|
|
196
|
+
if (values.help || !command) {
|
|
197
|
+
process.stdout.write(HELP);
|
|
198
|
+
return command || values.help ? 0 : 1;
|
|
199
|
+
}
|
|
200
|
+
const baseUrl = values.base ?? process.env.VEYCE_URL ?? DEFAULT_BASE_URL;
|
|
201
|
+
if (values.format && !FORMATS.includes(values.format)) {
|
|
202
|
+
process.stderr.write(`veyce: --format must be one of ${FORMATS.join(", ")}.
|
|
203
|
+
`);
|
|
204
|
+
return 1;
|
|
205
|
+
}
|
|
206
|
+
if (values.fit && values.fit !== "full" && values.fit !== "cover") {
|
|
207
|
+
process.stderr.write("veyce: --fit must be cover or full.\n");
|
|
208
|
+
return 1;
|
|
209
|
+
}
|
|
210
|
+
const options = {
|
|
211
|
+
seed: values.seed,
|
|
212
|
+
id: values.id,
|
|
213
|
+
collection: values.collection,
|
|
214
|
+
size: values.size !== void 0 ? Number(values.size) : void 0,
|
|
215
|
+
crop: values.crop,
|
|
216
|
+
fit: values.fit,
|
|
217
|
+
square: values.square,
|
|
218
|
+
format: values.format,
|
|
219
|
+
background: values.bg
|
|
220
|
+
};
|
|
221
|
+
const avatars = createAvatars({ baseUrl });
|
|
222
|
+
switch (command) {
|
|
223
|
+
case "url":
|
|
224
|
+
process.stdout.write(`${avatars.url(options)}
|
|
225
|
+
`);
|
|
226
|
+
return 0;
|
|
227
|
+
case "resolve":
|
|
228
|
+
process.stdout.write(`${JSON.stringify(await avatars.resolve(options), null, 2)}
|
|
229
|
+
`);
|
|
230
|
+
return 0;
|
|
231
|
+
case "list":
|
|
232
|
+
process.stdout.write(`${JSON.stringify(await avatars.list(values.collection), null, 2)}
|
|
233
|
+
`);
|
|
234
|
+
return 0;
|
|
235
|
+
case "get": {
|
|
236
|
+
const image = await avatars.fetch(options);
|
|
237
|
+
const ext = image.contentType.split("/")[1] ?? "webp";
|
|
238
|
+
const name = (values.id ?? values.seed ?? image.info.id).replace(/[^\w.@-]+/g, "_");
|
|
239
|
+
const out = values.out ?? `${name}.${ext}`;
|
|
240
|
+
await writeFile(out, image.bytes);
|
|
241
|
+
process.stderr.write(
|
|
242
|
+
`saved ${out} (${image.info.collection}/${image.info.id}, ${image.info.size}px, matched by ${image.info.match})
|
|
243
|
+
`
|
|
244
|
+
);
|
|
245
|
+
return 0;
|
|
246
|
+
}
|
|
247
|
+
default:
|
|
248
|
+
process.stderr.write(`veyce: unknown command "${command}".
|
|
249
|
+
|
|
250
|
+
${HELP}`);
|
|
251
|
+
return 1;
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
main().then(
|
|
255
|
+
(code) => process.exit(code),
|
|
256
|
+
(error) => {
|
|
257
|
+
const message = error instanceof AvatarError || error instanceof Error ? error.message : String(error);
|
|
258
|
+
process.stderr.write(`${message}
|
|
259
|
+
`);
|
|
260
|
+
process.exit(1);
|
|
261
|
+
}
|
|
262
|
+
);
|
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,196 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __export = (target, all) => {
|
|
7
|
+
for (var name in all)
|
|
8
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
+
};
|
|
10
|
+
var __copyProps = (to, from, except, desc) => {
|
|
11
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
+
for (let key of __getOwnPropNames(from))
|
|
13
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
+
|
|
20
|
+
// src/index.ts
|
|
21
|
+
var src_exports = {};
|
|
22
|
+
__export(src_exports, {
|
|
23
|
+
AvatarError: () => AvatarError,
|
|
24
|
+
CROPS: () => CROPS,
|
|
25
|
+
DEFAULT_BASE_URL: () => DEFAULT_BASE_URL,
|
|
26
|
+
DEFAULT_SIZE: () => DEFAULT_SIZE,
|
|
27
|
+
FORMATS: () => FORMATS,
|
|
28
|
+
MAX_SIZE: () => MAX_SIZE,
|
|
29
|
+
MIN_SIZE: () => MIN_SIZE,
|
|
30
|
+
avatarSrcSet: () => avatarSrcSet,
|
|
31
|
+
avatarUrl: () => avatarUrl,
|
|
32
|
+
clampSize: () => clampSize,
|
|
33
|
+
createAvatars: () => createAvatars,
|
|
34
|
+
hashSeed: () => hashSeed,
|
|
35
|
+
pick: () => pick
|
|
36
|
+
});
|
|
37
|
+
module.exports = __toCommonJS(src_exports);
|
|
38
|
+
var DEFAULT_BASE_URL = "https://veyce.vercel.app";
|
|
39
|
+
var MIN_SIZE = 8;
|
|
40
|
+
var MAX_SIZE = 2160;
|
|
41
|
+
var DEFAULT_SIZE = 80;
|
|
42
|
+
var CROPS = ["square", "portrait", "landscape", "phone", "tablet", "ultrawide"];
|
|
43
|
+
var FORMATS = ["webp", "png", "jpeg"];
|
|
44
|
+
var AvatarError = class extends Error {
|
|
45
|
+
constructor(message, status, body) {
|
|
46
|
+
super(message);
|
|
47
|
+
this.name = "AvatarError";
|
|
48
|
+
this.status = status;
|
|
49
|
+
this.body = body;
|
|
50
|
+
}
|
|
51
|
+
};
|
|
52
|
+
function hashSeed(seed) {
|
|
53
|
+
const value = String(seed);
|
|
54
|
+
let hash = 0;
|
|
55
|
+
for (let i = 0; i < value.length; i += 1) {
|
|
56
|
+
hash = (hash << 5) - hash + value.charCodeAt(i);
|
|
57
|
+
hash |= 0;
|
|
58
|
+
}
|
|
59
|
+
return Math.abs(hash) || 1;
|
|
60
|
+
}
|
|
61
|
+
function pick(seed, photos) {
|
|
62
|
+
if (!photos.length) return void 0;
|
|
63
|
+
return photos[hashSeed(seed) % photos.length];
|
|
64
|
+
}
|
|
65
|
+
function clampSize(size) {
|
|
66
|
+
if (!Number.isFinite(size)) return DEFAULT_SIZE;
|
|
67
|
+
return Math.min(MAX_SIZE, Math.max(MIN_SIZE, Math.round(size)));
|
|
68
|
+
}
|
|
69
|
+
function apiRoot(baseUrl) {
|
|
70
|
+
const trimmed = (baseUrl || DEFAULT_BASE_URL).replace(/\/+$/, "");
|
|
71
|
+
return /\/api$/.test(trimmed) ? trimmed : `${trimmed}/api`;
|
|
72
|
+
}
|
|
73
|
+
function normalizeHex(value) {
|
|
74
|
+
const hex = value.replace(/^#/, "");
|
|
75
|
+
return /^([0-9a-f]{3}|[0-9a-f]{6})$/i.test(hex) ? hex.toLowerCase() : null;
|
|
76
|
+
}
|
|
77
|
+
function avatarUrl(baseUrl, options = {}) {
|
|
78
|
+
const root = apiRoot(baseUrl);
|
|
79
|
+
const path = options.collection ? `${root}/${encodeURIComponent(options.collection)}` : root;
|
|
80
|
+
const query = new URLSearchParams();
|
|
81
|
+
if (options.id !== void 0 && options.id !== "") query.set("id", options.id);
|
|
82
|
+
if (options.seed !== void 0 && options.seed !== "") query.set("seed", String(options.seed));
|
|
83
|
+
if (options.size !== void 0) query.set("size", String(clampSize(options.size)));
|
|
84
|
+
if (options.crop) query.set("crop", options.crop);
|
|
85
|
+
if (options.fit && options.fit !== "cover") query.set("fit", options.fit);
|
|
86
|
+
if (options.square) query.set("square", "true");
|
|
87
|
+
if (options.format && options.format !== "webp") query.set("format", options.format);
|
|
88
|
+
if (options.background) {
|
|
89
|
+
const hex = normalizeHex(options.background);
|
|
90
|
+
if (!hex) throw new TypeError(`veyce: invalid background "${options.background}".`);
|
|
91
|
+
query.set("bg", hex);
|
|
92
|
+
}
|
|
93
|
+
const qs = query.toString();
|
|
94
|
+
return qs ? `${path}?${qs}` : path;
|
|
95
|
+
}
|
|
96
|
+
function avatarSrcSet(baseUrl, options = {}, densities = [1, 2, 3]) {
|
|
97
|
+
const size = options.size ?? DEFAULT_SIZE;
|
|
98
|
+
const seen = /* @__PURE__ */ new Set();
|
|
99
|
+
return densities.map((density) => ({ density, px: clampSize(size * density) })).filter(({ px }) => seen.has(px) ? false : (seen.add(px), true)).map(({ density, px }) => `${avatarUrl(baseUrl, { ...options, size: px })} ${density}x`).join(", ");
|
|
100
|
+
}
|
|
101
|
+
function readInfo(root, headers, requested) {
|
|
102
|
+
const collection = headers.get("x-photo-collection") ?? "";
|
|
103
|
+
const id = headers.get("x-photo-id") ?? "";
|
|
104
|
+
const match = headers.get("x-photo-match") ?? "id";
|
|
105
|
+
return {
|
|
106
|
+
collection,
|
|
107
|
+
id,
|
|
108
|
+
crop: headers.get("x-photo-crop") ?? "square",
|
|
109
|
+
size: Number(headers.get("x-photo-size") ?? requested),
|
|
110
|
+
match,
|
|
111
|
+
url: avatarUrl(root, { collection, id })
|
|
112
|
+
};
|
|
113
|
+
}
|
|
114
|
+
async function fail(response) {
|
|
115
|
+
let body;
|
|
116
|
+
let message = response.status === 404 ? "veyce: no image matches (unknown id or collection) \u2014 pass a `seed` to always get one" : response.status === 409 ? "veyce: that id exists in several collections \u2014 pass `collection`" : `veyce: request failed with ${response.status}`;
|
|
117
|
+
try {
|
|
118
|
+
body = await response.json();
|
|
119
|
+
const error = body?.error;
|
|
120
|
+
if (typeof error === "string") message = `veyce: ${error}`;
|
|
121
|
+
} catch {
|
|
122
|
+
}
|
|
123
|
+
throw new AvatarError(message, response.status, body);
|
|
124
|
+
}
|
|
125
|
+
function toBase64(bytes) {
|
|
126
|
+
const B = globalThis.Buffer;
|
|
127
|
+
if (B) return B.from(bytes).toString("base64");
|
|
128
|
+
let binary = "";
|
|
129
|
+
for (let i = 0; i < bytes.length; i += 32768) {
|
|
130
|
+
binary += String.fromCharCode(...bytes.subarray(i, i + 32768));
|
|
131
|
+
}
|
|
132
|
+
return btoa(binary);
|
|
133
|
+
}
|
|
134
|
+
function createAvatars(config = {}) {
|
|
135
|
+
const root = apiRoot(config.baseUrl);
|
|
136
|
+
const defaults = config.defaults ?? {};
|
|
137
|
+
const doFetch = (input, init) => {
|
|
138
|
+
const f = config.fetch ?? globalThis.fetch;
|
|
139
|
+
if (!f) throw new Error("veyce: no global fetch; pass `fetch` in the config.");
|
|
140
|
+
return f(input, init);
|
|
141
|
+
};
|
|
142
|
+
const merge = (options) => ({ ...defaults, ...options });
|
|
143
|
+
const client = {
|
|
144
|
+
baseUrl: root,
|
|
145
|
+
url: (options) => avatarUrl(root, merge(options)),
|
|
146
|
+
srcSet: (options, densities) => avatarSrcSet(root, merge(options), densities),
|
|
147
|
+
async fetch(options) {
|
|
148
|
+
const merged = merge(options);
|
|
149
|
+
const response = await doFetch(avatarUrl(root, merged));
|
|
150
|
+
if (!response.ok) return fail(response);
|
|
151
|
+
const bytes = new Uint8Array(await response.arrayBuffer());
|
|
152
|
+
return {
|
|
153
|
+
bytes,
|
|
154
|
+
contentType: response.headers.get("content-type") ?? `image/${merged.format ?? "webp"}`,
|
|
155
|
+
info: readInfo(root, response.headers, merged.size ?? DEFAULT_SIZE)
|
|
156
|
+
};
|
|
157
|
+
},
|
|
158
|
+
async dataUri(options) {
|
|
159
|
+
const { bytes, contentType } = await client.fetch(options);
|
|
160
|
+
return `data:${contentType};base64,${toBase64(bytes)}`;
|
|
161
|
+
},
|
|
162
|
+
async resolve(options) {
|
|
163
|
+
const merged = merge(options);
|
|
164
|
+
const response = await doFetch(avatarUrl(root, merged), { method: "HEAD" });
|
|
165
|
+
if (!response.ok) return fail(response);
|
|
166
|
+
return readInfo(root, response.headers, merged.size ?? DEFAULT_SIZE);
|
|
167
|
+
},
|
|
168
|
+
async list(collection = defaults.collection) {
|
|
169
|
+
const qs = collection ? `?collection=${encodeURIComponent(collection)}` : "";
|
|
170
|
+
const response = await doFetch(`${root}/photos${qs}`);
|
|
171
|
+
if (!response.ok) return fail(response);
|
|
172
|
+
return await response.json();
|
|
173
|
+
},
|
|
174
|
+
pick(seed, index) {
|
|
175
|
+
return pick(seed, Array.isArray(index) ? index : index.photos);
|
|
176
|
+
}
|
|
177
|
+
};
|
|
178
|
+
return client;
|
|
179
|
+
}
|
|
180
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
181
|
+
0 && (module.exports = {
|
|
182
|
+
AvatarError,
|
|
183
|
+
CROPS,
|
|
184
|
+
DEFAULT_BASE_URL,
|
|
185
|
+
DEFAULT_SIZE,
|
|
186
|
+
FORMATS,
|
|
187
|
+
MAX_SIZE,
|
|
188
|
+
MIN_SIZE,
|
|
189
|
+
avatarSrcSet,
|
|
190
|
+
avatarUrl,
|
|
191
|
+
clampSize,
|
|
192
|
+
createAvatars,
|
|
193
|
+
hashSeed,
|
|
194
|
+
pick
|
|
195
|
+
});
|
|
196
|
+
//# sourceMappingURL=index.cjs.map
|