@eskais/character 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/CHANGELOG.md +29 -0
- package/LICENSE +21 -0
- package/LICENSE-APACHE-2.0.txt +202 -0
- package/LICENSES.md +17 -0
- package/README.md +136 -2
- package/assets/anny/anny.bin +0 -0
- package/assets/hair/hair.bin +0 -0
- package/dist/engine.d.ts +302 -0
- package/dist/errors.js +49 -0
- package/dist/errors.js.map +1 -0
- package/dist/index.d.ts +9 -0
- package/dist/index.js +525 -0
- package/dist/index.js.map +1 -0
- package/dist/motion.d.ts +1 -0
- package/dist/motion.js +5 -0
- package/dist/motion.js.map +1 -0
- package/dist/react.d.ts +62 -0
- package/dist/react.js +168 -0
- package/dist/react.js.map +1 -0
- package/dist/style.d.ts +32 -0
- package/dist/style.js +152 -0
- package/dist/style.js.map +1 -0
- package/dist/three.d.ts +14 -0
- package/dist/three.js +100 -0
- package/dist/three.js.map +1 -0
- package/dist/worker.d.ts +3 -0
- package/dist/worker.js +42 -0
- package/dist/worker.js.map +1 -0
- package/package.json +147 -4
package/dist/engine.d.ts
ADDED
|
@@ -0,0 +1,302 @@
|
|
|
1
|
+
interface PinnedAsset {
|
|
2
|
+
/** Default location; the host may serve the same bytes from elsewhere (see ScanEngineOptions.assetUrls). */
|
|
3
|
+
url: string;
|
|
4
|
+
sha256: string;
|
|
5
|
+
bytes: number;
|
|
6
|
+
licence: string;
|
|
7
|
+
}
|
|
8
|
+
declare const assetIds: readonly ["mediapipeLoader", "mediapipeWasm", "mediapipeLoaderClassic", "mediapipeWasmClassic", "faceLandmarker", "poseLandmarkerLite", "poseLandmarkerFull", "annyModel", "hairModel"];
|
|
9
|
+
type AssetId = (typeof assetIds)[number];
|
|
10
|
+
declare const pinnedAssets: Record<AssetId, PinnedAsset>;
|
|
11
|
+
declare class AssetLoadError extends Error {
|
|
12
|
+
name: string;
|
|
13
|
+
}
|
|
14
|
+
declare class AssetIntegrityError extends Error {
|
|
15
|
+
name: string;
|
|
16
|
+
}
|
|
17
|
+
type AssetUrls = Partial<Record<AssetId, string>>;
|
|
18
|
+
type Delegate = "CPU" | "GPU";
|
|
19
|
+
declare const scanErrorCodes: readonly [
|
|
20
|
+
/** No face in the face photo. */
|
|
21
|
+
"no-face",
|
|
22
|
+
/** A photo couldn't be decoded. */
|
|
23
|
+
"unreadable-image",
|
|
24
|
+
/** The browser lacks something else the engine needs (workers, WebAssembly, OffscreenCanvas) or the page isn't secure. */
|
|
25
|
+
"unsupported",
|
|
26
|
+
/** The browser lacks WebGL2, which MediaPipe needs even on its CPU delegate. */
|
|
27
|
+
"webgl2-unavailable",
|
|
28
|
+
/** A downloaded model or asset didn't match its pinned size or SHA-256. */
|
|
29
|
+
"asset-integrity",
|
|
30
|
+
/** A model or asset couldn't be downloaded because the browser is offline. */
|
|
31
|
+
"offline",
|
|
32
|
+
/** A model or asset couldn't be downloaded for another reason (blocked, server error). */
|
|
33
|
+
"asset-load",
|
|
34
|
+
/** The worker crashed or couldn't start. */
|
|
35
|
+
"worker", "internal"];
|
|
36
|
+
type ScanErrorCode = (typeof scanErrorCodes)[number];
|
|
37
|
+
/** The browser lacks something the engine needs (WebGL2 today). */
|
|
38
|
+
declare class CapabilityError extends Error {
|
|
39
|
+
name: string;
|
|
40
|
+
}
|
|
41
|
+
declare class ScanError extends Error {
|
|
42
|
+
readonly code: ScanErrorCode;
|
|
43
|
+
name: string;
|
|
44
|
+
constructor(code: ScanErrorCode, message: string);
|
|
45
|
+
}
|
|
46
|
+
declare const phenotypeLabels: readonly ["gender", "age", "muscle", "weight", "height", "proportions"];
|
|
47
|
+
type PhenotypeLabel = (typeof phenotypeLabels)[number];
|
|
48
|
+
type Phenotype = Record<PhenotypeLabel, number>;
|
|
49
|
+
declare const bodyFeatureNames: readonly ["shoulderWidth", "hipWidth", "upperArm", "forearm", "thigh", "shin", "torso", "neckToNose", "chestWidth", "waistWidth", "hipSilhouette", "thighWidth", "calfWidth", "neckWidth"];
|
|
50
|
+
type BodyFeatureName = (typeof bodyFeatureNames)[number];
|
|
51
|
+
type BodyFeatures = Record<BodyFeatureName, number>;
|
|
52
|
+
type HairLength = "none" | "buzz" | "short" | "medium" | "long";
|
|
53
|
+
type HairShape = "none" | "painted" | "straight" | "wavy" | "updo" | "braid" | "afro";
|
|
54
|
+
interface HairStyle {
|
|
55
|
+
id: string;
|
|
56
|
+
label: string;
|
|
57
|
+
length: HairLength;
|
|
58
|
+
shape: HairShape;
|
|
59
|
+
/** Shell thickness for the fallback, metres; 0 for no geometry. */
|
|
60
|
+
thickness: number;
|
|
61
|
+
/** Asset style with the fitted geometry; null for no mesh ("none", the painted "buzz"). */
|
|
62
|
+
asset: string | null;
|
|
63
|
+
}
|
|
64
|
+
declare const hairCatalogue: readonly HairStyle[];
|
|
65
|
+
/** sRGB colour as "#rrggbb". */
|
|
66
|
+
type Hex = `#${string}`;
|
|
67
|
+
interface ScanInput {
|
|
68
|
+
/** A front photo of the face. */
|
|
69
|
+
face: Blob | ImageBitmap;
|
|
70
|
+
/** A full-body front photo (A-pose, fitted clothes). Optional: without it the body stays at the prior. */
|
|
71
|
+
body?: Blob | ImageBitmap;
|
|
72
|
+
}
|
|
73
|
+
interface ScanHints {
|
|
74
|
+
/** Stature, when the user gives it: photos alone don't carry absolute scale. */
|
|
75
|
+
heightCm?: number;
|
|
76
|
+
}
|
|
77
|
+
interface ScanOptions {
|
|
78
|
+
signal?: AbortSignal;
|
|
79
|
+
hints?: ScanHints;
|
|
80
|
+
/** The look of the finished character; defaults to soft toon, stylize 0.5, casual outfit. */
|
|
81
|
+
look?: LookOptions;
|
|
82
|
+
}
|
|
83
|
+
type StyleId = "soft-toon" | "cel-outline" | "low-poly" | "clay";
|
|
84
|
+
type OutfitId = "casual" | "hoodie" | "none";
|
|
85
|
+
interface CharacterLook {
|
|
86
|
+
style: StyleId;
|
|
87
|
+
/** 0 keeps the fitted proportions; 1 is the strongest stylisation (larger head and eyes, smaller nose and mouth). */
|
|
88
|
+
stylize: number;
|
|
89
|
+
/** "none" shows the fitted body in underwear: meant for internal use, not for display. */
|
|
90
|
+
outfit: OutfitId;
|
|
91
|
+
}
|
|
92
|
+
type LookOptions = Partial<CharacterLook>;
|
|
93
|
+
interface RestyleOptions extends LookOptions {
|
|
94
|
+
/** A hair style id from `character.hair.options`. */
|
|
95
|
+
hair?: string;
|
|
96
|
+
colors?: Partial<CharacterColors>;
|
|
97
|
+
}
|
|
98
|
+
type ScanStage = "load" | "detect-face" | "detect-body" | "fit-body" | "fit-face" | "colors" | "hair" | "export";
|
|
99
|
+
interface CharacterColors {
|
|
100
|
+
skin: Hex;
|
|
101
|
+
eyes: Hex;
|
|
102
|
+
hair: Hex;
|
|
103
|
+
brows: Hex;
|
|
104
|
+
/** null when no beard was found. */
|
|
105
|
+
beard: Hex | null;
|
|
106
|
+
}
|
|
107
|
+
interface HairChoice {
|
|
108
|
+
id: string;
|
|
109
|
+
length: HairLength;
|
|
110
|
+
/** Every style the user can switch to. */
|
|
111
|
+
options: {
|
|
112
|
+
id: string;
|
|
113
|
+
label: string;
|
|
114
|
+
length: HairLength;
|
|
115
|
+
}[];
|
|
116
|
+
}
|
|
117
|
+
interface CharacterParams {
|
|
118
|
+
phenotype: Phenotype;
|
|
119
|
+
/** Face modifier values in [-1, 1], by label. */
|
|
120
|
+
face: Record<string, number>;
|
|
121
|
+
}
|
|
122
|
+
interface Character {
|
|
123
|
+
/** glTF 2.0 binary: skinned body, eyes and hair, with every morph target and the fitted weights as defaults. */
|
|
124
|
+
glb: Uint8Array;
|
|
125
|
+
/** Morph target names of the body mesh, as in the GLB's `extras.targetNames`. */
|
|
126
|
+
targetNames: string[];
|
|
127
|
+
/** Fitted morph weights, aligned with `targetNames`. */
|
|
128
|
+
weights: Float32Array;
|
|
129
|
+
params: CharacterParams;
|
|
130
|
+
colors: CharacterColors;
|
|
131
|
+
hair: HairChoice;
|
|
132
|
+
look: CharacterLook & {
|
|
133
|
+
styles: {
|
|
134
|
+
id: StyleId;
|
|
135
|
+
label: string;
|
|
136
|
+
}[];
|
|
137
|
+
outfits: OutfitId[];
|
|
138
|
+
};
|
|
139
|
+
quality: {
|
|
140
|
+
face: number;
|
|
141
|
+
body: number | null;
|
|
142
|
+
warnings: string[];
|
|
143
|
+
};
|
|
144
|
+
}
|
|
145
|
+
type ScanEvent =
|
|
146
|
+
/**
|
|
147
|
+
* Models downloading (or coming from the HTTP cache) before the first scan, between the "load" stage's start and end:
|
|
148
|
+
* bytes after decompression, of everything the scan needs.
|
|
149
|
+
*/
|
|
150
|
+
{
|
|
151
|
+
type: "download";
|
|
152
|
+
loaded: number;
|
|
153
|
+
total: number;
|
|
154
|
+
} |
|
|
155
|
+
/** A stage started (ms omitted) or finished (ms is its duration). "load" only happens when the engine isn't loaded. */
|
|
156
|
+
{
|
|
157
|
+
type: "stage";
|
|
158
|
+
stage: ScanStage;
|
|
159
|
+
ms?: number;
|
|
160
|
+
} |
|
|
161
|
+
/**
|
|
162
|
+
* Landmarks for the UI to light up: x, y pairs normalised to the original photo (x by its width, y by its height;
|
|
163
|
+
* MediaPipe maps its letterboxed input back before returning them). `aspect` is that photo's width / height, so no
|
|
164
|
+
* letterbox correction applies. Points may fall slightly outside 0..1 when a feature is cut off by the frame.
|
|
165
|
+
*/
|
|
166
|
+
{
|
|
167
|
+
type: "landmarks";
|
|
168
|
+
source: "face" | "body";
|
|
169
|
+
points: Float32Array;
|
|
170
|
+
aspect: number;
|
|
171
|
+
} |
|
|
172
|
+
/**
|
|
173
|
+
* The person's segmentation mask for a photo, after its landmarks: confidence 0–255, row-major, at most 256 px on
|
|
174
|
+
* the long side, with the photo's aspect ratio (width / height ≈ the landmarks' aspect). For transitions that send
|
|
175
|
+
* the photo's person pixels onto the character and its background away; the photo itself never leaves the host.
|
|
176
|
+
*/
|
|
177
|
+
{
|
|
178
|
+
type: "mask";
|
|
179
|
+
source: "face" | "body";
|
|
180
|
+
width: number;
|
|
181
|
+
height: number;
|
|
182
|
+
data: Uint8Array;
|
|
183
|
+
} |
|
|
184
|
+
/** The base character: mean shape with every morph target, weights at zero. Sent once, before fitting. */
|
|
185
|
+
{
|
|
186
|
+
type: "model";
|
|
187
|
+
glb: Uint8Array;
|
|
188
|
+
targetNames: string[];
|
|
189
|
+
} |
|
|
190
|
+
/** Weights while the fit converges, aligned with the model's `targetNames`; `value` is 0..1 overall progress. */
|
|
191
|
+
{
|
|
192
|
+
type: "progress";
|
|
193
|
+
value: number;
|
|
194
|
+
weights: Float32Array;
|
|
195
|
+
} | {
|
|
196
|
+
type: "done";
|
|
197
|
+
character: Character;
|
|
198
|
+
} |
|
|
199
|
+
/**
|
|
200
|
+
* The scan failed; always the last event. Cancelling through the AbortSignal is not a failure: the iterator throws
|
|
201
|
+
* the signal's AbortError instead.
|
|
202
|
+
*/
|
|
203
|
+
{
|
|
204
|
+
type: "error";
|
|
205
|
+
error: {
|
|
206
|
+
code: ScanErrorCode;
|
|
207
|
+
message: string;
|
|
208
|
+
};
|
|
209
|
+
};
|
|
210
|
+
type WorkerResponse = {
|
|
211
|
+
type: "ready";
|
|
212
|
+
delegate: Delegate;
|
|
213
|
+
ms: number;
|
|
214
|
+
} | {
|
|
215
|
+
type: "download";
|
|
216
|
+
loaded: number;
|
|
217
|
+
total: number;
|
|
218
|
+
} | {
|
|
219
|
+
type: "init-error";
|
|
220
|
+
code: ScanErrorCode;
|
|
221
|
+
message: string;
|
|
222
|
+
} | {
|
|
223
|
+
type: "event";
|
|
224
|
+
id: number;
|
|
225
|
+
event: ScanEvent;
|
|
226
|
+
} | {
|
|
227
|
+
type: "end";
|
|
228
|
+
id: number;
|
|
229
|
+
} | {
|
|
230
|
+
type: "restyled";
|
|
231
|
+
id: number;
|
|
232
|
+
character: Character;
|
|
233
|
+
} | {
|
|
234
|
+
type: "error";
|
|
235
|
+
id: number;
|
|
236
|
+
code: ScanErrorCode;
|
|
237
|
+
message: string;
|
|
238
|
+
} | {
|
|
239
|
+
type: "detected";
|
|
240
|
+
id: number;
|
|
241
|
+
landmarks: Float32Array | null;
|
|
242
|
+
blendshapes: Record<string, number> | null;
|
|
243
|
+
features: BodyFeatures | null;
|
|
244
|
+
ms: number;
|
|
245
|
+
};
|
|
246
|
+
interface ScanEngineOptions {
|
|
247
|
+
/** Where to load each pinned asset from, when the host serves its own copies (same bytes, same SHA-256). */
|
|
248
|
+
assetUrls?: AssetUrls;
|
|
249
|
+
/** MediaPipe delegate: "auto" tries the GPU and falls back to the CPU. */
|
|
250
|
+
delegate?: Delegate | "auto";
|
|
251
|
+
/** Pose model: "lite" (5.8 MB) or "full" (9.4 MB, more accurate). */
|
|
252
|
+
poseModel?: "lite" | "full";
|
|
253
|
+
/**
|
|
254
|
+
* Where the worker script is served, for bundlers that don't emit `new Worker(new URL(…, import.meta.url))` targets
|
|
255
|
+
* (bun's): copy `@eskais/character/worker` (dist/worker.js) to your static files and point here. Same origin only.
|
|
256
|
+
*/
|
|
257
|
+
workerUrl?: string | URL;
|
|
258
|
+
/** Creates the worker yourself; overrides `workerUrl`. */
|
|
259
|
+
createWorker?: () => Worker;
|
|
260
|
+
}
|
|
261
|
+
interface DownloadProgress {
|
|
262
|
+
loaded: number;
|
|
263
|
+
total: number;
|
|
264
|
+
}
|
|
265
|
+
interface LoadOptions {
|
|
266
|
+
signal?: AbortSignal;
|
|
267
|
+
/** Bytes after decompression, of everything a scan needs. */
|
|
268
|
+
onProgress?: (progress: DownloadProgress) => void;
|
|
269
|
+
}
|
|
270
|
+
interface Loaded {
|
|
271
|
+
/** Whether MediaPipe got the GPU. */
|
|
272
|
+
delegate: Delegate;
|
|
273
|
+
ms: number;
|
|
274
|
+
}
|
|
275
|
+
interface ScanEngine {
|
|
276
|
+
/**
|
|
277
|
+
* Starts the worker and downloads the models, if they aren't loaded yet. Optional: `scan()` does it. Rejects with a
|
|
278
|
+
* ScanError ("unsupported", "webgl2-unavailable", "offline", "asset-load", "asset-integrity" or "worker"); the next
|
|
279
|
+
* call tries again. Aborting stops the download when nothing else waits for it.
|
|
280
|
+
*/
|
|
281
|
+
load(options?: LoadOptions): Promise<Loaded>;
|
|
282
|
+
/** `load()` as a property: reading it starts the download. */
|
|
283
|
+
readonly ready: Promise<Loaded>;
|
|
284
|
+
scan(input: ScanInput, options?: ScanOptions): AsyncGenerator<ScanEvent, void, undefined>;
|
|
285
|
+
/**
|
|
286
|
+
* Re-exports a scanned character with another style, stylisation, outfit, hair or colours, without the photo:
|
|
287
|
+
* everything it needs is in the Character. Rejects with a ScanError.
|
|
288
|
+
*/
|
|
289
|
+
restyle(character: Character, options: RestyleOptions): Promise<Character>;
|
|
290
|
+
/** Test hook: landmarks of one image, without a scan. */
|
|
291
|
+
detect(kind: "face" | "body", image: Blob | ImageBitmap): Promise<Extract<WorkerResponse, {
|
|
292
|
+
type: "detected";
|
|
293
|
+
}>>;
|
|
294
|
+
/**
|
|
295
|
+
* Stops the worker and frees its memory (models, WASM heap, WebGL context). Scans in flight throw an AbortError. The
|
|
296
|
+
* engine stays usable: the next scan loads again, from the HTTP cache.
|
|
297
|
+
*/
|
|
298
|
+
dispose(): void;
|
|
299
|
+
}
|
|
300
|
+
/** Creating an engine does nothing: no worker and no network until the first `scan()`, `load()` or `restyle()`. */
|
|
301
|
+
declare function createScanEngine(options?: ScanEngineOptions): ScanEngine;
|
|
302
|
+
export { AssetLoadError as A, hairCatalogue as C, scanErrorCodes as D, ScanErrorCode as E, pinnedAssets as F, AssetId as M, PinnedAsset as N, Delegate as O, assetIds as P, HairStyle as S, ScanError as T, ScanInput as _, createScanEngine as a, StyleId as b, CharacterLook as c, Hex as d, LookOptions as f, ScanHints as g, ScanEvent as h, ScanEngineOptions as i, AssetUrls as j, AssetIntegrityError as k, CharacterParams as l, RestyleOptions as m, LoadOptions as n, Character as o, OutfitId as p, ScanEngine as r, CharacterColors as s, DownloadProgress as t, HairChoice as u, ScanOptions as v, CapabilityError as w, HairLength as x, ScanStage as y };
|
package/dist/errors.js
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
// src/scan/loader.ts
|
|
2
|
+
var AssetLoadError = class extends Error {
|
|
3
|
+
name = "AssetLoadError";
|
|
4
|
+
};
|
|
5
|
+
/** The browser reports it has no connection. */
|
|
6
|
+
var AssetOfflineError = class extends AssetLoadError {
|
|
7
|
+
name = "AssetOfflineError";
|
|
8
|
+
};
|
|
9
|
+
var AssetIntegrityError = class extends Error {
|
|
10
|
+
name = "AssetIntegrityError";
|
|
11
|
+
};
|
|
12
|
+
// src/scan/errors.ts
|
|
13
|
+
const scanErrorCodes = [
|
|
14
|
+
"no-face",
|
|
15
|
+
"unreadable-image",
|
|
16
|
+
"unsupported",
|
|
17
|
+
"webgl2-unavailable",
|
|
18
|
+
"asset-integrity",
|
|
19
|
+
"offline",
|
|
20
|
+
"asset-load",
|
|
21
|
+
"worker",
|
|
22
|
+
"internal"
|
|
23
|
+
];
|
|
24
|
+
/** The browser lacks something the engine needs (WebGL2 today). */
|
|
25
|
+
var CapabilityError = class extends Error {
|
|
26
|
+
name = "CapabilityError";
|
|
27
|
+
};
|
|
28
|
+
var ScanError = class extends Error {
|
|
29
|
+
code;
|
|
30
|
+
name = "ScanError";
|
|
31
|
+
constructor(code, message) {
|
|
32
|
+
super(message);
|
|
33
|
+
this.code = code;
|
|
34
|
+
}
|
|
35
|
+
};
|
|
36
|
+
function errorCode(error) {
|
|
37
|
+
if (error instanceof ScanError) return error.code;
|
|
38
|
+
if (error instanceof CapabilityError) return "webgl2-unavailable";
|
|
39
|
+
if (error instanceof AssetIntegrityError) return "asset-integrity";
|
|
40
|
+
if (error instanceof AssetOfflineError) return "offline";
|
|
41
|
+
if (error instanceof AssetLoadError) return "asset-load";
|
|
42
|
+
return "internal";
|
|
43
|
+
}
|
|
44
|
+
function errorMessage(error) {
|
|
45
|
+
return error instanceof Error ? error.message : "The scan failed.";
|
|
46
|
+
}
|
|
47
|
+
export { scanErrorCodes as a, errorMessage as i, ScanError as n, AssetIntegrityError as o, errorCode as r, AssetLoadError as s, CapabilityError as t };
|
|
48
|
+
|
|
49
|
+
//# sourceMappingURL=errors.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"errors.js","names":[],"sources":["../src/scan/loader.ts","../src/scan/errors.ts"],"sourcesContent":["// The only module allowed to touch the network (lint: character/no-network-outside-loader). It fetches pinned assets\n// and verifies their SHA-256 before anything uses them; it never sends data, only GETs.\n\nimport { pinnedAssets, type AssetId } from \"./assets.ts\"\n\nexport class AssetLoadError extends Error {\n override name = \"AssetLoadError\"\n}\n\n/** The browser reports it has no connection. */\nexport class AssetOfflineError extends AssetLoadError {\n override name = \"AssetOfflineError\"\n}\n\nexport class AssetIntegrityError extends Error {\n override name = \"AssetIntegrityError\"\n}\n\nfunction hex(buffer: ArrayBuffer): string {\n return Array.from(new Uint8Array(buffer), (byte) => byte.toString(16).padStart(2, \"0\")).join(\"\")\n}\n\nexport type AssetUrls = Partial<Record<AssetId, string>>\n\nexport interface FetchOptions {\n signal?: AbortSignal\n /** Bytes of this asset received so far (decompressed, so they end at the pinned size). */\n onProgress?: (id: AssetId, loaded: number) => void\n}\n\n/**\n * Whether this code runs in a classic worker. Bundlers differ: Vite and webpack start `new Worker(…, { type: \"module\" })`\n * as a module worker, Next's Turbopack as a classic one that loads chunks with importScripts. MediaPipe ships a loader\n * for each. A module worker throws on importScripts, even with no arguments; a classic one does nothing.\n */\nexport function isClassicWorker(): boolean {\n const scope = globalThis as { importScripts?: (...urls: string[]) => void }\n if (typeof scope.importScripts !== \"function\") return false\n try {\n scope.importScripts()\n return true\n } catch {\n return false\n }\n}\n\n/**\n * Fetches a pinned asset from the host's copy when there is one, else from its pinned URL; when the host's copy can't\n * be loaded at all (a bundler that didn't emit it), from the pinned URL. Either way the bytes must match the pin.\n */\nexport async function fetchPinned(id: AssetId, urls: AssetUrls, options: FetchOptions = {}): Promise<ArrayBuffer> {\n const pinned = pinnedAssets[id]\n const own = urls[id]\n if (own && own !== pinned.url)\n try {\n return await fetchFrom(id, own, options)\n } catch (error) {\n if (!(error instanceof AssetLoadError)) throw error\n }\n return fetchFrom(id, pinned.url, options)\n}\n\n/** The body as it arrives, into one buffer of the pinned size: nothing longer than the pin is kept. */\nasync function readBody(id: AssetId, response: Response, onProgress: FetchOptions[\"onProgress\"]): Promise<Uint8Array> {\n const pinned = pinnedAssets[id]\n const bytes = new Uint8Array(pinned.bytes)\n let loaded = 0\n const reader = response.body?.getReader()\n if (!reader) return new Uint8Array(await response.arrayBuffer())\n for (;;) {\n // oxlint-disable-next-line no-await-in-loop -- chunks arrive in order\n const { done, value } = await reader.read()\n if (done) break\n if (loaded + value.byteLength > pinned.bytes) {\n // oxlint-disable-next-line no-await-in-loop -- the loop ends here\n await reader.cancel()\n throw new AssetIntegrityError(`${id} is larger than its pinned ${String(pinned.bytes)} bytes.`)\n }\n bytes.set(value, loaded)\n loaded += value.byteLength\n onProgress?.(id, loaded)\n }\n return loaded === pinned.bytes ? bytes : bytes.subarray(0, loaded)\n}\n\nasync function fetchFrom(id: AssetId, url: string, { signal, onProgress }: FetchOptions): Promise<ArrayBuffer> {\n const pinned = pinnedAssets[id]\n let response: Response\n try {\n response = await fetch(url, {\n method: \"GET\",\n credentials: \"omit\",\n referrerPolicy: \"no-referrer\",\n cache: \"force-cache\",\n ...(signal ? { signal } : {}),\n })\n } catch (error) {\n if (signal?.aborted) throw error\n throw failedRequest(id)\n }\n if (!response.ok) throw new AssetLoadError(`Could not load ${id} (${String(response.status)}).`)\n // A dev server or a static host that answers a missing file with its index page: not our file, so not a tampered one.\n if (response.headers.get(\"content-type\")?.startsWith(\"text/html\"))\n throw new AssetLoadError(`Could not load ${id}: the server answered with a page.`)\n let bytes: Uint8Array\n try {\n bytes = await readBody(id, response, onProgress)\n } catch (error) {\n if (signal?.aborted || error instanceof AssetIntegrityError) throw error\n throw failedRequest(id)\n }\n if (bytes.byteLength !== pinned.bytes)\n throw new AssetIntegrityError(`${id} is ${String(bytes.byteLength)} bytes; the pin says ${String(pinned.bytes)}.`)\n const digest = hex(await crypto.subtle.digest(\"SHA-256\", bytes as Uint8Array<ArrayBuffer>))\n if (digest !== pinned.sha256) throw new AssetIntegrityError(`${id} does not match its pinned SHA-256.`)\n return bytes.buffer as ArrayBuffer\n}\n\nfunction failedRequest(id: AssetId): AssetLoadError {\n return navigator.onLine === false\n ? new AssetOfflineError(`Could not load ${id}: the browser is offline.`)\n : new AssetLoadError(`Could not load ${id}: the request failed.`)\n}\n\n/** A verified asset as a same-origin blob URL, for MediaPipe's loader, which wants URLs. */\nexport async function pinnedBlobUrl(\n id: AssetId,\n urls: AssetUrls,\n type: string,\n options: FetchOptions = {},\n): Promise<string> {\n const bytes = await fetchPinned(id, urls, options)\n return URL.createObjectURL(new Blob([bytes], { type }))\n}\n","// Scan failures as stable codes, so the UI can react without parsing messages. Classes don't survive postMessage, so\n// the worker sends the code and the main thread rebuilds a ScanError.\n\nimport { AssetIntegrityError, AssetLoadError, AssetOfflineError } from \"./loader.ts\"\n\nexport const scanErrorCodes = [\n /** No face in the face photo. */\n \"no-face\",\n /** A photo couldn't be decoded. */\n \"unreadable-image\",\n /** The browser lacks something else the engine needs (workers, WebAssembly, OffscreenCanvas) or the page isn't secure. */\n \"unsupported\",\n /** The browser lacks WebGL2, which MediaPipe needs even on its CPU delegate. */\n \"webgl2-unavailable\",\n /** A downloaded model or asset didn't match its pinned size or SHA-256. */\n \"asset-integrity\",\n /** A model or asset couldn't be downloaded because the browser is offline. */\n \"offline\",\n /** A model or asset couldn't be downloaded for another reason (blocked, server error). */\n \"asset-load\",\n /** The worker crashed or couldn't start. */\n \"worker\",\n \"internal\",\n] as const\nexport type ScanErrorCode = (typeof scanErrorCodes)[number]\n\n/** The browser lacks something the engine needs (WebGL2 today). */\nexport class CapabilityError extends Error {\n override name = \"CapabilityError\"\n}\n\nexport class ScanError extends Error {\n override name = \"ScanError\"\n constructor(\n readonly code: ScanErrorCode,\n message: string,\n ) {\n super(message)\n }\n}\n\nexport function errorCode(error: unknown): ScanErrorCode {\n if (error instanceof ScanError) return error.code\n if (error instanceof CapabilityError) return \"webgl2-unavailable\"\n if (error instanceof AssetIntegrityError) return \"asset-integrity\"\n if (error instanceof AssetOfflineError) return \"offline\"\n if (error instanceof AssetLoadError) return \"asset-load\"\n return \"internal\"\n}\n\nexport function errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : \"The scan failed.\"\n}\n"],"mappings":";AAKA,IAAa,iBAAb,cAAoC,MAAM;CAC/B,OAAO;AAClB;;AAGA,IAAa,oBAAb,cAAuC,eAAe;CAC3C,OAAO;AAClB;AAEA,IAAa,sBAAb,cAAyC,MAAM;CACpC,OAAO;AAClB;;ACXA,MAAa,iBAAiB;CAE5B;CAEA;CAEA;CAEA;CAEA;CAEA;CAEA;CAEA;CACA;AACF;;AAIA,IAAa,kBAAb,cAAqC,MAAM;CAChC,OAAO;AAClB;AAEA,IAAa,YAAb,cAA+B,MAAM;CAGxB;CAFF,OAAO;CAChB,YACW,MACT,SACA;EACA,MAAM,OAAO;EAHJ,KAAA,OAAA;CAIX;AACF;AAEA,SAAgB,UAAU,OAA+B;CACvD,IAAI,iBAAiB,WAAW,OAAO,MAAM;CAC7C,IAAI,iBAAiB,iBAAiB,OAAO;CAC7C,IAAI,iBAAiB,qBAAqB,OAAO;CACjD,IAAI,iBAAiB,mBAAmB,OAAO;CAC/C,IAAI,iBAAiB,gBAAgB,OAAO;CAC5C,OAAO;AACT;AAEA,SAAgB,aAAa,OAAwB;CACnD,OAAO,iBAAiB,QAAQ,MAAM,UAAU;AAClD"}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import { A as AssetLoadError, C as hairCatalogue, D as scanErrorCodes, E as ScanErrorCode, F as pinnedAssets, M as AssetId, N as PinnedAsset, O as Delegate, P as assetIds, S as HairStyle, T as ScanError, _ as ScanInput, a as createScanEngine, b as StyleId, c as CharacterLook, d as Hex, f as LookOptions, g as ScanHints, h as ScanEvent, i as ScanEngineOptions, j as AssetUrls, k as AssetIntegrityError, l as CharacterParams, m as RestyleOptions, n as LoadOptions, o as Character, p as OutfitId, r as ScanEngine, s as CharacterColors, t as DownloadProgress, u as HairChoice, v as ScanOptions, w as CapabilityError, x as HairLength, y as ScanStage } from "./engine.js";
|
|
2
|
+
import { i as stylePresets, n as StylePreset, r as styleIds } from "./style.js";
|
|
3
|
+
export declare const outfitIds: readonly ["casual", "hoodie", "none"];
|
|
4
|
+
export declare const defaultLook: CharacterLook;
|
|
5
|
+
/** One-call form of the contract: `for await (const e of scanCharacter({ face, body }, { signal }))`. */
|
|
6
|
+
export declare function scanCharacter(input: ScanInput, options?: ScanOptions & {
|
|
7
|
+
engine?: ScanEngineOptions;
|
|
8
|
+
}): AsyncGenerator<ScanEvent, void, undefined>;
|
|
9
|
+
export { type AssetId, AssetIntegrityError, AssetLoadError, type AssetUrls, CapabilityError, type Character, type CharacterColors, type CharacterLook, type CharacterParams, type Delegate, type DownloadProgress, type HairChoice, type HairLength, type HairStyle, type Hex, type LoadOptions, type LookOptions, type OutfitId, type PinnedAsset, type RestyleOptions, type ScanEngine, type ScanEngineOptions, ScanError, type ScanErrorCode, type ScanEvent, type ScanHints, type ScanInput, type ScanOptions, type ScanStage, type StyleId, type StylePreset, assetIds, createScanEngine, hairCatalogue, pinnedAssets, scanErrorCodes, styleIds, stylePresets };
|