picgo-plugin-tinify 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/dist/config.js ADDED
@@ -0,0 +1,171 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.pluginConfig = exports.apiOverride = exports.getSettings = exports.tinypngApiKey = exports.configuredEngine = exports.parseMinSize = exports.parsePreserve = exports.parseBackground = exports.parseConvert = exports.getUserConfig = exports.ConfigError = exports.PRESERVE_KEYS = exports.CONVERT_CHOICES = exports.ENGINES = exports.CONFIG_KEY = exports.PLUGIN_NAME = void 0;
4
+ exports.PLUGIN_NAME = 'picgo-plugin-tinify';
5
+ exports.CONFIG_KEY = exports.PLUGIN_NAME;
6
+ exports.ENGINES = ['tinypng'];
7
+ exports.CONVERT_CHOICES = ['none', 'avif', 'webp', 'jpeg', 'png'];
8
+ exports.PRESERVE_KEYS = ['copyright', 'creation', 'location'];
9
+ class ConfigError extends Error {
10
+ constructor(message) {
11
+ super(message);
12
+ this.name = 'ConfigError';
13
+ }
14
+ }
15
+ exports.ConfigError = ConfigError;
16
+ const getUserConfig = (ctx) => ctx.getConfig(exports.CONFIG_KEY) ?? {};
17
+ exports.getUserConfig = getUserConfig;
18
+ const parseConvert = ($T, value) => {
19
+ const v = (value ?? '').trim().toLowerCase();
20
+ const normalized = v === 'jpg' ? 'jpeg' : v;
21
+ if (!normalized || normalized === 'none') {
22
+ return undefined;
23
+ }
24
+ if (!exports.CONVERT_CHOICES.includes(normalized)) {
25
+ throw new ConfigError($T('TINIFY_INVALID_CONVERT', { value: value ?? '', formats: exports.CONVERT_CHOICES.join(', ') }));
26
+ }
27
+ return normalized;
28
+ };
29
+ exports.parseConvert = parseConvert;
30
+ const parseBackground = ($T, value) => {
31
+ const v = (value ?? '').trim();
32
+ if (!v) {
33
+ return 'white';
34
+ }
35
+ if (/^(white|black)$/i.test(v)) {
36
+ return v.toLowerCase();
37
+ }
38
+ if (/^#[0-9a-f]{6}$/i.test(v)) {
39
+ return v;
40
+ }
41
+ throw new ConfigError($T('TINIFY_INVALID_BACKGROUND', { value: v }));
42
+ };
43
+ exports.parseBackground = parseBackground;
44
+ const parsePreserve = ($T, value) => {
45
+ const list = Array.isArray(value) ? value : (value ?? '').split(/[\s,]+/);
46
+ const keys = list.map(v => v.trim().toLowerCase()).filter(Boolean);
47
+ for (const key of keys) {
48
+ if (!exports.PRESERVE_KEYS.includes(key)) {
49
+ throw new ConfigError($T('TINIFY_INVALID_PRESERVE', { value: key, keys: exports.PRESERVE_KEYS.join(', ') }));
50
+ }
51
+ }
52
+ return [...new Set(keys)];
53
+ };
54
+ exports.parsePreserve = parsePreserve;
55
+ const parseMinSize = ($T, value) => {
56
+ const raw = typeof value === 'number' ? String(value) : (value ?? '').trim();
57
+ if (!raw) {
58
+ return 0;
59
+ }
60
+ const kb = Number(raw);
61
+ if (!Number.isFinite(kb) || kb < 0) {
62
+ throw new ConfigError($T('TINIFY_INVALID_MIN_SIZE', { value: raw }));
63
+ }
64
+ return Math.round(kb * 1024);
65
+ };
66
+ exports.parseMinSize = parseMinSize;
67
+ /** The configured engine id, `tinypng` when unset; undefined when it names no known engine. */
68
+ const configuredEngine = (config) => {
69
+ const engine = (config.engine ?? '').trim() || 'tinypng';
70
+ return exports.ENGINES.includes(engine) ? engine : undefined;
71
+ };
72
+ exports.configuredEngine = configuredEngine;
73
+ /** `TINYPNG_API_KEY` when set, else the saved key. */
74
+ const tinypngApiKey = (config, env = process.env) => (env.TINYPNG_API_KEY ?? '').trim() || (config.tinypngApiKey ?? '').trim();
75
+ exports.tinypngApiKey = tinypngApiKey;
76
+ /** Reads and validates the plugin config. Throws ConfigError with a message meant for the user. */
77
+ const getSettings = (ctx, $T, env = process.env) => {
78
+ const config = (0, exports.getUserConfig)(ctx);
79
+ const engine = (config.engine ?? '').trim() || 'tinypng';
80
+ if (!exports.ENGINES.includes(engine)) {
81
+ throw new ConfigError($T('TINIFY_UNKNOWN_ENGINE', { value: engine }));
82
+ }
83
+ const apiKey = (0, exports.tinypngApiKey)(config, env);
84
+ if (engine === 'tinypng' && !apiKey) {
85
+ throw new ConfigError($T('TINIFY_NO_API_KEY'));
86
+ }
87
+ return {
88
+ engine: engine,
89
+ tinypngApiKey: apiKey,
90
+ convert: (0, exports.parseConvert)($T, config.convert),
91
+ background: (0, exports.parseBackground)($T, config.background),
92
+ preserve: (0, exports.parsePreserve)($T, config.preserve),
93
+ minSizeBytes: (0, exports.parseMinSize)($T, config.minSize)
94
+ };
95
+ };
96
+ exports.getSettings = getSettings;
97
+ /** Test hook, not shown in the UI: point the TinyPNG engine at a mock server. */
98
+ const apiOverride = (env = process.env) => env.TINIFY_API_URL?.trim() ? env.TINIFY_API_URL.trim() : undefined;
99
+ exports.apiOverride = apiOverride;
100
+ const pluginConfig = (ctx, $T) => {
101
+ const config = (0, exports.getUserConfig)(ctx);
102
+ const preserve = Array.isArray(config.preserve) ? config.preserve : [];
103
+ return [
104
+ {
105
+ name: 'engine',
106
+ type: 'list',
107
+ get alias() { return $T('TINIFY_CONFIG_ENGINE'); },
108
+ get message() { return $T('TINIFY_CONFIG_ENGINE_TIP'); },
109
+ choices: [{ name: 'TinyPNG', value: 'tinypng' }],
110
+ default: config.engine ?? 'tinypng',
111
+ required: true
112
+ },
113
+ {
114
+ name: 'tinypngApiKey',
115
+ type: 'password',
116
+ get alias() { return $T('TINIFY_CONFIG_TINYPNG_API_KEY'); },
117
+ get message() { return $T('TINIFY_CONFIG_TINYPNG_API_KEY_TIP'); },
118
+ default: config.tinypngApiKey ?? '',
119
+ required: true
120
+ },
121
+ {
122
+ name: 'convert',
123
+ type: 'list',
124
+ get alias() { return $T('TINIFY_CONFIG_CONVERT'); },
125
+ get message() { return $T('TINIFY_CONFIG_CONVERT_TIP'); },
126
+ get choices() {
127
+ return [
128
+ { name: $T('TINIFY_CONFIG_CONVERT_NONE'), value: 'none' },
129
+ { name: 'AVIF', value: 'avif' },
130
+ { name: 'WEBP', value: 'webp' },
131
+ { name: 'JPEG', value: 'jpeg' },
132
+ { name: 'PNG', value: 'png' }
133
+ ];
134
+ },
135
+ default: config.convert ?? 'none',
136
+ required: false
137
+ },
138
+ {
139
+ name: 'background',
140
+ type: 'input',
141
+ get alias() { return $T('TINIFY_CONFIG_BACKGROUND'); },
142
+ get message() { return $T('TINIFY_CONFIG_BACKGROUND_TIP'); },
143
+ default: config.background ?? 'white',
144
+ required: false
145
+ },
146
+ {
147
+ name: 'preserve',
148
+ type: 'checkbox',
149
+ get alias() { return $T('TINIFY_CONFIG_PRESERVE'); },
150
+ get message() { return $T('TINIFY_CONFIG_PRESERVE_TIP'); },
151
+ get choices() {
152
+ return [
153
+ { name: $T('TINIFY_CONFIG_PRESERVE_COPYRIGHT'), value: 'copyright', checked: preserve.includes('copyright') },
154
+ { name: $T('TINIFY_CONFIG_PRESERVE_CREATION'), value: 'creation', checked: preserve.includes('creation') },
155
+ { name: $T('TINIFY_CONFIG_PRESERVE_LOCATION'), value: 'location', checked: preserve.includes('location') }
156
+ ];
157
+ },
158
+ default: preserve,
159
+ required: false
160
+ },
161
+ {
162
+ name: 'minSize',
163
+ type: 'input',
164
+ get alias() { return $T('TINIFY_CONFIG_MIN_SIZE'); },
165
+ get message() { return $T('TINIFY_CONFIG_MIN_SIZE_TIP'); },
166
+ default: config.minSize === undefined ? '0' : String(config.minSize),
167
+ required: false
168
+ }
169
+ ];
170
+ };
171
+ exports.pluginConfig = pluginConfig;
@@ -0,0 +1,12 @@
1
+ import type { IPicGo } from 'picgo';
2
+ import { type EngineId, type Settings } from '../config';
3
+ import type { ImageFormat } from '../format';
4
+ import { type HttpTransport } from '../http';
5
+ import type { Translate } from '../i18n';
6
+ import type { CompressionEngine } from './types';
7
+ export type { CompressionEngine, CompressOptions, CompressResult, ConvertFormat, PreserveKey } from './types';
8
+ export { EngineError } from './types';
9
+ /** Formats each engine accepts, known before any key is checked. */
10
+ export declare const ENGINE_INPUT_FORMATS: Record<EngineId, readonly ImageFormat[]>;
11
+ /** Builds the engine chosen in the config. Add a case here for each new engine. */
12
+ export declare const createEngine: (ctx: IPicGo, settings: Settings, $T: Translate, transport?: HttpTransport) => CompressionEngine;
@@ -0,0 +1,20 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createEngine = exports.ENGINE_INPUT_FORMATS = exports.EngineError = void 0;
4
+ const config_1 = require("../config");
5
+ const http_1 = require("../http");
6
+ const tinypng_1 = require("./tinypng");
7
+ var types_1 = require("./types");
8
+ Object.defineProperty(exports, "EngineError", { enumerable: true, get: function () { return types_1.EngineError; } });
9
+ /** Formats each engine accepts, known before any key is checked. */
10
+ exports.ENGINE_INPUT_FORMATS = {
11
+ tinypng: tinypng_1.TINYPNG_INPUT_FORMATS
12
+ };
13
+ /** Builds the engine chosen in the config. Add a case here for each new engine. */
14
+ const createEngine = (ctx, settings, $T, transport = (0, http_1.createPicGoTransport)(ctx)) => {
15
+ switch (settings.engine) {
16
+ case 'tinypng':
17
+ return new tinypng_1.TinyPngEngine({ apiKey: settings.tinypngApiKey, transport, $T, baseUrl: (0, config_1.apiOverride)() });
18
+ }
19
+ };
20
+ exports.createEngine = createEngine;
@@ -0,0 +1,33 @@
1
+ import { type ImageFormat } from '../format';
2
+ import { type HttpTransport } from '../http';
3
+ import type { Translate } from '../i18n';
4
+ import { type CompressionEngine, type CompressOptions, type CompressResult } from './types';
5
+ export declare const TINYPNG_API_URL = "https://api.tinify.com";
6
+ export declare const TINYPNG_INPUT_FORMATS: readonly ImageFormat[];
7
+ export interface TinyPngOptions {
8
+ apiKey: string;
9
+ transport: HttpTransport;
10
+ $T: Translate;
11
+ /** Test hook: a mock server instead of api.tinify.com. */
12
+ baseUrl?: string;
13
+ }
14
+ /**
15
+ * TinyPNG (Tinify) HTTP API: upload to `/shrink`, then download the output, or POST options
16
+ * (convert, preserve) to the output URL to get the processed image in one request.
17
+ * https://tinypng.com/developers/reference
18
+ */
19
+ export declare class TinyPngEngine implements CompressionEngine {
20
+ private readonly options;
21
+ readonly id = "tinypng";
22
+ readonly name = "TinyPNG";
23
+ readonly inputFormats: readonly ImageFormat[];
24
+ compressionCount?: number;
25
+ private readonly auth;
26
+ private readonly baseUrl;
27
+ constructor(options: TinyPngOptions);
28
+ usage(): string | undefined;
29
+ compress(input: Buffer, options: CompressOptions): Promise<CompressResult>;
30
+ private outputUrl;
31
+ private send;
32
+ private toError;
33
+ }
@@ -0,0 +1,116 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.TinyPngEngine = exports.TINYPNG_INPUT_FORMATS = exports.TINYPNG_API_URL = void 0;
4
+ const format_1 = require("../format");
5
+ const http_1 = require("../http");
6
+ const types_1 = require("./types");
7
+ exports.TINYPNG_API_URL = 'https://api.tinify.com';
8
+ exports.TINYPNG_INPUT_FORMATS = ['png', 'jpeg', 'webp', 'avif', 'jxl', 'heic'];
9
+ const parseError = (res) => {
10
+ try {
11
+ const json = JSON.parse(res.body.toString('utf8'));
12
+ return { error: json.error ?? '', message: json.message ?? '' };
13
+ }
14
+ catch {
15
+ return { error: '', message: res.body.toString('utf8').slice(0, 200) };
16
+ }
17
+ };
18
+ /**
19
+ * TinyPNG (Tinify) HTTP API: upload to `/shrink`, then download the output, or POST options
20
+ * (convert, preserve) to the output URL to get the processed image in one request.
21
+ * https://tinypng.com/developers/reference
22
+ */
23
+ class TinyPngEngine {
24
+ options;
25
+ id = 'tinypng';
26
+ name = 'TinyPNG';
27
+ inputFormats = exports.TINYPNG_INPUT_FORMATS;
28
+ compressionCount;
29
+ auth;
30
+ baseUrl;
31
+ constructor(options) {
32
+ this.options = options;
33
+ this.auth = `Basic ${Buffer.from(`api:${options.apiKey}`).toString('base64')}`;
34
+ this.baseUrl = (options.baseUrl ?? exports.TINYPNG_API_URL).replace(/\/+$/, '');
35
+ }
36
+ usage() {
37
+ return this.compressionCount === undefined ? undefined : this.options.$T('TINIFY_COMPRESSION_COUNT', { count: String(this.compressionCount) });
38
+ }
39
+ async compress(input, options) {
40
+ const shrink = await this.send({ method: 'POST', url: `${this.baseUrl}/shrink`, body: input, signal: options.signal });
41
+ if (shrink.status !== 201) {
42
+ throw this.toError(shrink);
43
+ }
44
+ const location = shrink.headers.location ?? this.outputUrl(shrink);
45
+ if (!location) {
46
+ throw new types_1.EngineError(this.options.$T('TINIFY_ERROR_REQUEST', { status: String(shrink.status), message: 'no output URL' }));
47
+ }
48
+ const commands = {};
49
+ if (options.convert) {
50
+ commands.convert = { type: format_1.MIME_TYPES[options.convert] };
51
+ if (options.convert === 'jpeg') {
52
+ // Without a background TinyPNG refuses to turn a transparent image into JPEG.
53
+ commands.transform = { background: options.background ?? 'white' };
54
+ }
55
+ }
56
+ if (options.preserve && options.preserve.length > 0) {
57
+ commands.preserve = options.preserve;
58
+ }
59
+ const hasCommands = Object.keys(commands).length > 0;
60
+ const output = await this.send(hasCommands
61
+ ? { method: 'POST', url: location, body: commands, signal: options.signal }
62
+ : { method: 'GET', url: location, signal: options.signal });
63
+ if (output.status !== 200) {
64
+ throw this.toError(output);
65
+ }
66
+ const format = (0, format_1.formatFromMime)(output.headers['content-type']) ?? (0, format_1.detectFormat)(output.body);
67
+ if (!format) {
68
+ throw new types_1.EngineError(this.options.$T('TINIFY_ERROR_REQUEST', { status: String(output.status), message: `unexpected content type ${output.headers['content-type'] ?? ''}` }));
69
+ }
70
+ return { buffer: output.body, format };
71
+ }
72
+ outputUrl(res) {
73
+ try {
74
+ return JSON.parse(res.body.toString('utf8')).output?.url;
75
+ }
76
+ catch {
77
+ return undefined;
78
+ }
79
+ }
80
+ async send(req) {
81
+ let res;
82
+ try {
83
+ res = await this.options.transport({ ...req, headers: { ...req.headers, Authorization: this.auth } });
84
+ }
85
+ catch (e) {
86
+ if (e instanceof http_1.NetworkError) {
87
+ throw new types_1.EngineError(this.options.$T('TINIFY_ERROR_NETWORK', { message: e.message }));
88
+ }
89
+ throw e;
90
+ }
91
+ const count = Number(res.headers['compression-count']);
92
+ if (Number.isFinite(count) && res.headers['compression-count'] !== undefined) {
93
+ this.compressionCount = count;
94
+ }
95
+ return res;
96
+ }
97
+ toError(res) {
98
+ const { $T } = this.options;
99
+ const { message } = parseError(res);
100
+ const status = String(res.status);
101
+ if (res.status === 401) {
102
+ return new types_1.EngineError($T('TINIFY_ERROR_UNAUTHORIZED'), { fatal: true });
103
+ }
104
+ if (res.status === 429) {
105
+ return new types_1.EngineError($T('TINIFY_ERROR_LIMIT', { message }), { fatal: true });
106
+ }
107
+ if (res.status === 415) {
108
+ return new types_1.EngineError($T('TINIFY_ERROR_UNSUPPORTED'), { unsupported: true });
109
+ }
110
+ if (res.status >= 500) {
111
+ return new types_1.EngineError($T('TINIFY_ERROR_SERVER', { status }));
112
+ }
113
+ return new types_1.EngineError($T('TINIFY_ERROR_REQUEST', { status, message }));
114
+ }
115
+ }
116
+ exports.TinyPngEngine = TinyPngEngine;
@@ -0,0 +1,41 @@
1
+ import type { ImageFormat } from '../format';
2
+ export type ConvertFormat = 'avif' | 'webp' | 'jpeg' | 'png';
3
+ export type PreserveKey = 'copyright' | 'creation' | 'location';
4
+ export interface CompressOptions {
5
+ /** Target format; undefined keeps the input format. */
6
+ convert?: ConvertFormat;
7
+ /** Fill for transparent areas when converting to JPEG: `white`, `black` or `#RRGGBB`. */
8
+ background?: string;
9
+ preserve?: PreserveKey[];
10
+ signal?: AbortSignal;
11
+ }
12
+ export interface CompressResult {
13
+ buffer: Buffer;
14
+ format: ImageFormat;
15
+ }
16
+ /**
17
+ * A compression service. New engines implement this and register in `engines/index.ts`;
18
+ * the upload hook and the CLI only talk to this interface.
19
+ */
20
+ export interface CompressionEngine {
21
+ readonly id: string;
22
+ /** Shown to users, e.g. in the CLI progress line. */
23
+ readonly name: string;
24
+ /** Input formats the engine accepts. */
25
+ readonly inputFormats: readonly ImageFormat[];
26
+ compress: (input: Buffer, options: CompressOptions) => Promise<CompressResult>;
27
+ /** One line about remaining quota for the logs, if the engine knows it. */
28
+ usage?: () => string | undefined;
29
+ }
30
+ export interface EngineErrorOptions {
31
+ /** Other images will fail the same way (bad key, quota used up), so batch work should stop. */
32
+ fatal?: boolean;
33
+ /** The engine cannot read this file; it is skipped like any other unsupported file, not reported as a failure. */
34
+ unsupported?: boolean;
35
+ }
36
+ /** An error meant for the user. */
37
+ export declare class EngineError extends Error {
38
+ readonly fatal: boolean;
39
+ readonly unsupported: boolean;
40
+ constructor(message: string, options?: EngineErrorOptions);
41
+ }
@@ -0,0 +1,15 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.EngineError = void 0;
4
+ /** An error meant for the user. */
5
+ class EngineError extends Error {
6
+ fatal;
7
+ unsupported;
8
+ constructor(message, options = {}) {
9
+ super(message);
10
+ this.name = 'EngineError';
11
+ this.fatal = options.fatal ?? false;
12
+ this.unsupported = options.unsupported ?? false;
13
+ }
14
+ }
15
+ exports.EngineError = EngineError;
@@ -0,0 +1,15 @@
1
+ export type ImageFormat = 'png' | 'jpeg' | 'webp' | 'avif' | 'jxl' | 'heic' | 'gif';
2
+ export declare const MIME_TYPES: Record<ImageFormat, string>;
3
+ export declare const formatFromMime: (mime: string | undefined) => ImageFormat | undefined;
4
+ /** Reads the format from the file's magic bytes, so a wrong extension does not matter. */
5
+ export declare const detectFormat: (buf: Buffer) => ImageFormat | undefined;
6
+ /**
7
+ * The extension for a file in `format`. Keeps the old spelling when it already names the
8
+ * same format (`.jpeg`, `.JPG`), so a file that only got smaller keeps its name.
9
+ */
10
+ export declare const extnameFor: (format: ImageFormat, current?: string) => string;
11
+ /** Replaces the extension of `fileName` (or appends one), e.g. `a.png` → `a.webp`. */
12
+ export declare const replaceExtname: (fileName: string, extname: string) => string;
13
+ export declare const currentExtname: (fileName: string) => string;
14
+ export declare const formatBytes: (bytes: number) => string;
15
+ export declare const formatRatio: (before: number, after: number) => string;
package/dist/format.js ADDED
@@ -0,0 +1,104 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.formatRatio = exports.formatBytes = exports.currentExtname = exports.replaceExtname = exports.extnameFor = exports.detectFormat = exports.formatFromMime = exports.MIME_TYPES = void 0;
4
+ exports.MIME_TYPES = {
5
+ png: 'image/png',
6
+ jpeg: 'image/jpeg',
7
+ webp: 'image/webp',
8
+ avif: 'image/avif',
9
+ jxl: 'image/jxl',
10
+ heic: 'image/heic',
11
+ gif: 'image/gif'
12
+ };
13
+ const EXTNAMES = {
14
+ png: '.png',
15
+ jpeg: '.jpg',
16
+ webp: '.webp',
17
+ avif: '.avif',
18
+ jxl: '.jxl',
19
+ heic: '.heic',
20
+ gif: '.gif'
21
+ };
22
+ const formatFromMime = (mime) => {
23
+ const type = (mime ?? '').split(';')[0].trim().toLowerCase();
24
+ const found = Object.keys(exports.MIME_TYPES).find(f => exports.MIME_TYPES[f] === type);
25
+ return found ?? (type === 'image/jpg' ? 'jpeg' : undefined);
26
+ };
27
+ exports.formatFromMime = formatFromMime;
28
+ const ascii = (buf, start, end) => buf.subarray(start, end).toString('latin1');
29
+ /** Reads the format from the file's magic bytes, so a wrong extension does not matter. */
30
+ const detectFormat = (buf) => {
31
+ if (buf.length >= 8 && buf.readUInt32BE(0) === 0x89504e47 && buf.readUInt32BE(4) === 0x0d0a1a0a) {
32
+ return 'png';
33
+ }
34
+ if (buf.length >= 3 && buf[0] === 0xff && buf[1] === 0xd8 && buf[2] === 0xff) {
35
+ return 'jpeg';
36
+ }
37
+ if (buf.length >= 12 && ascii(buf, 0, 4) === 'RIFF' && ascii(buf, 8, 12) === 'WEBP') {
38
+ return 'webp';
39
+ }
40
+ if (buf.length >= 6 && (ascii(buf, 0, 6) === 'GIF87a' || ascii(buf, 0, 6) === 'GIF89a')) {
41
+ return 'gif';
42
+ }
43
+ // Bare JPEG XL codestream, or the JPEG XL container box.
44
+ if (buf.length >= 2 && buf[0] === 0xff && buf[1] === 0x0a) {
45
+ return 'jxl';
46
+ }
47
+ if (buf.length >= 12 && buf.readUInt32BE(0) === 0x0c && ascii(buf, 4, 8) === 'JXL ') {
48
+ return 'jxl';
49
+ }
50
+ // ISO BMFF: the `ftyp` box names the brand.
51
+ if (buf.length >= 12 && ascii(buf, 4, 8) === 'ftyp') {
52
+ const brand = ascii(buf, 8, 12);
53
+ if (brand === 'avif' || brand === 'avis') {
54
+ return 'avif';
55
+ }
56
+ if (['heic', 'heix', 'hevc', 'hevx', 'heim', 'heis', 'mif1', 'msf1'].includes(brand)) {
57
+ return 'heic';
58
+ }
59
+ }
60
+ return undefined;
61
+ };
62
+ exports.detectFormat = detectFormat;
63
+ /**
64
+ * The extension for a file in `format`. Keeps the old spelling when it already names the
65
+ * same format (`.jpeg`, `.JPG`), so a file that only got smaller keeps its name.
66
+ */
67
+ const extnameFor = (format, current = '') => {
68
+ const ext = current.toLowerCase();
69
+ if (ext && (ext === EXTNAMES[format] || (format === 'jpeg' && ext === '.jpeg'))) {
70
+ return current;
71
+ }
72
+ return EXTNAMES[format];
73
+ };
74
+ exports.extnameFor = extnameFor;
75
+ /** Replaces the extension of `fileName` (or appends one), e.g. `a.png` → `a.webp`. */
76
+ const replaceExtname = (fileName, extname) => {
77
+ const dot = fileName.lastIndexOf('.');
78
+ const base = dot > 0 ? fileName.slice(0, dot) : fileName;
79
+ return `${base}${extname}`;
80
+ };
81
+ exports.replaceExtname = replaceExtname;
82
+ const currentExtname = (fileName) => {
83
+ const dot = fileName.lastIndexOf('.');
84
+ return dot > 0 ? fileName.slice(dot) : '';
85
+ };
86
+ exports.currentExtname = currentExtname;
87
+ const formatBytes = (bytes) => {
88
+ if (bytes < 1024) {
89
+ return `${bytes} B`;
90
+ }
91
+ if (bytes < 1024 * 1024) {
92
+ return `${(bytes / 1024).toFixed(1)} KB`;
93
+ }
94
+ return `${(bytes / 1024 / 1024).toFixed(2)} MB`;
95
+ };
96
+ exports.formatBytes = formatBytes;
97
+ const formatRatio = (before, after) => {
98
+ if (before === 0) {
99
+ return '0%';
100
+ }
101
+ const change = Math.round((after - before) / before * 100);
102
+ return `${change > 0 ? '+' : ''}${change}%`;
103
+ };
104
+ exports.formatRatio = formatRatio;
package/dist/http.d.ts ADDED
@@ -0,0 +1,23 @@
1
+ import type { IPicGo } from 'picgo';
2
+ export interface HttpRequest {
3
+ method: 'GET' | 'POST';
4
+ url: string;
5
+ headers?: Record<string, string>;
6
+ /** A Buffer is sent as is; anything else is sent as JSON. */
7
+ body?: Buffer | Record<string, unknown>;
8
+ signal?: AbortSignal;
9
+ timeoutMs?: number;
10
+ }
11
+ export interface HttpResponse {
12
+ status: number;
13
+ /** Lower-cased header names. */
14
+ headers: Record<string, string | undefined>;
15
+ body: Buffer;
16
+ }
17
+ /** Resolves for every HTTP status, rejects only for network failures. */
18
+ export type HttpTransport = (req: HttpRequest) => Promise<HttpResponse>;
19
+ export declare class NetworkError extends Error {
20
+ constructor(message: string);
21
+ }
22
+ /** Sends requests through `ctx.request`, so PicGo's `picBed.proxy` setting applies. */
23
+ export declare const createPicGoTransport: (ctx: IPicGo) => HttpTransport;
package/dist/http.js ADDED
@@ -0,0 +1,72 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createPicGoTransport = exports.NetworkError = void 0;
4
+ class NetworkError extends Error {
5
+ constructor(message) {
6
+ super(message);
7
+ this.name = 'NetworkError';
8
+ }
9
+ }
10
+ exports.NetworkError = NetworkError;
11
+ const normalizeHeaders = (headers) => {
12
+ const result = {};
13
+ if (!headers || typeof headers !== 'object') {
14
+ return result;
15
+ }
16
+ const plain = typeof headers.toJSON === 'function'
17
+ ? headers.toJSON()
18
+ : headers;
19
+ for (const [key, value] of Object.entries(plain)) {
20
+ if (value === undefined || value === null) {
21
+ continue;
22
+ }
23
+ result[key.toLowerCase()] = Array.isArray(value) ? value.join(', ') : typeof value === 'string' ? value : JSON.stringify(value);
24
+ }
25
+ return result;
26
+ };
27
+ /** Sends requests through `ctx.request`, so PicGo's `picBed.proxy` setting applies. */
28
+ const createPicGoTransport = (ctx) => {
29
+ const request = ctx.request;
30
+ return async (req) => {
31
+ const headers = { ...(req.headers ?? {}) };
32
+ let data;
33
+ if (Buffer.isBuffer(req.body)) {
34
+ data = req.body;
35
+ headers['Content-Type'] ??= 'application/octet-stream';
36
+ }
37
+ else if (req.body !== undefined) {
38
+ data = JSON.stringify(req.body);
39
+ headers['Content-Type'] = 'application/json';
40
+ }
41
+ let res;
42
+ try {
43
+ res = await request({
44
+ method: req.method,
45
+ url: req.url,
46
+ headers,
47
+ data,
48
+ responseType: 'arraybuffer',
49
+ signal: req.signal,
50
+ timeout: req.timeoutMs ?? 120000,
51
+ validateStatus: () => true,
52
+ resolveWithFullResponse: true
53
+ });
54
+ }
55
+ catch (e) {
56
+ const message = e?.message ?? String(e);
57
+ throw new NetworkError(message || 'Network error');
58
+ }
59
+ const raw = res.data;
60
+ const body = Buffer.isBuffer(raw)
61
+ ? raw
62
+ : raw instanceof ArrayBuffer
63
+ ? Buffer.from(raw)
64
+ : Buffer.from(typeof raw === 'string' ? raw : JSON.stringify(raw ?? ''));
65
+ return {
66
+ status: res.status ?? res.statusCode ?? 0,
67
+ headers: normalizeHeaders(res.headers),
68
+ body
69
+ };
70
+ };
71
+ };
72
+ exports.createPicGoTransport = createPicGoTransport;
@@ -0,0 +1,45 @@
1
+ export declare const en: {
2
+ TINIFY_CONFIG_ENGINE: string;
3
+ TINIFY_CONFIG_ENGINE_TIP: string;
4
+ TINIFY_CONFIG_TINYPNG_API_KEY: string;
5
+ TINIFY_CONFIG_TINYPNG_API_KEY_TIP: string;
6
+ TINIFY_CONFIG_CONVERT: string;
7
+ TINIFY_CONFIG_CONVERT_TIP: string;
8
+ TINIFY_CONFIG_CONVERT_NONE: string;
9
+ TINIFY_CONFIG_BACKGROUND: string;
10
+ TINIFY_CONFIG_BACKGROUND_TIP: string;
11
+ TINIFY_CONFIG_PRESERVE: string;
12
+ TINIFY_CONFIG_PRESERVE_TIP: string;
13
+ TINIFY_CONFIG_PRESERVE_COPYRIGHT: string;
14
+ TINIFY_CONFIG_PRESERVE_CREATION: string;
15
+ TINIFY_CONFIG_PRESERVE_LOCATION: string;
16
+ TINIFY_CONFIG_MIN_SIZE: string;
17
+ TINIFY_CONFIG_MIN_SIZE_TIP: string;
18
+ TINIFY_NO_API_KEY: string;
19
+ TINIFY_INVALID_CONVERT: string;
20
+ TINIFY_INVALID_BACKGROUND: string;
21
+ TINIFY_INVALID_MIN_SIZE: string;
22
+ TINIFY_INVALID_PRESERVE: string;
23
+ TINIFY_UNKNOWN_ENGINE: string;
24
+ TINIFY_ERROR_UNAUTHORIZED: string;
25
+ TINIFY_ERROR_LIMIT: string;
26
+ TINIFY_ERROR_UNSUPPORTED: string;
27
+ TINIFY_ERROR_SERVER: string;
28
+ TINIFY_ERROR_REQUEST: string;
29
+ TINIFY_ERROR_NETWORK: string;
30
+ TINIFY_COMPRESSED: string;
31
+ TINIFY_SKIP_SMALL: string;
32
+ TINIFY_SKIP_UNSUPPORTED: string;
33
+ TINIFY_SKIP_NOT_SMALLER: string;
34
+ TINIFY_FAILED_ITEM: string;
35
+ TINIFY_UPLOAD_ORIGINAL: string;
36
+ TINIFY_NOTIFY_FAILED_TITLE: string;
37
+ TINIFY_NOTIFY_FAILED_BODY: string;
38
+ TINIFY_PROGRESS: string;
39
+ TINIFY_COMPRESSION_COUNT: string;
40
+ TINIFY_CLI_WROTE: string;
41
+ TINIFY_CLI_NOT_FILE: string;
42
+ TINIFY_CLI_SUMMARY: string;
43
+ TINIFY_CLI_STOPPED: string;
44
+ };
45
+ export type ILocalesKey = keyof typeof en;