@haatlabs-core/provider-background 0.0.0-stage → 0.10.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 ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "{}"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 Haatlabs
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,59 @@
1
- # Temporary Holding Version
1
+ # @haatlabs-core/provider-background
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
+ ## Install
4
+
5
+ pnpm add @haatlabs-core/provider-background
6
+
7
+ It leaves one package to your app, so the app holds one copy: `sharp`.
8
+
9
+ ## What it does
10
+
11
+ Background removal by a rembg service, called directly or through a services gateway.
12
+ `cutoutFromService(baseUrl, image, options)` returns the cut-out (an RGBA PNG the size of the
13
+ image); `outlineFromService` returns its alpha channel as a grey PNG. The image must be a
14
+ WebP the caller made itself. Every answer is checked as a file from a stranger: a PNG by
15
+ its bytes, with alpha, the size sent, at most 25 megapixels, at most 30 MiB. `sharp` is a
16
+ peer: the app's own, with its settings, is the one used. The package leaves sharp's globals
17
+ to the app; on a small host, call `sharp.cache(false)` and `sharp.concurrency(1)`.
18
+
19
+ ## Options
20
+
21
+ `model` (`BACKGROUND_MODEL`, `u2netp`, by default), `fetch`, `timeoutMs` (10 s),
22
+ `maxReplyBytes` (30 MiB), `maxImageBytes` (20 MiB, the gateway's own cap: a larger image is
23
+ refused before any request, not transient), `gatewayKey`, `call` and `signal`.
24
+
25
+ ## Errors
26
+
27
+ `BackgroundRemovalError(message, transient, { retryAfterMs?, cause? })`. `transient`: the
28
+ service is away, slow, busy or failing (a 429 or 5xx, no answer, a time out); otherwise the
29
+ same image would get the same answer. A 429 or 5xx carries `retryAfterMs` from its
30
+ Retry-After (seconds or a date, at most five minutes). The message never quotes the
31
+ service. A caller's abort is rethrown as theirs.
32
+
33
+ ## Gateway and deadlines
34
+
35
+ With `gatewayKey`, `call` (tier, priority, `deadlineMs`) goes to the gateway, tier 4 in the
36
+ background without one. The time limit is `timeoutMs`, or `call.deadlineMs` when that is
37
+ sooner (`localTimeoutMs`; a deadline that is not a finite number is none), and the gateway is
38
+ given that limit, never longer. The deadline is this call's: a caller's retry starts it again;
39
+ pass `signal` for a hard limit. Through the gateway a refused status carries an
40
+ `UpstreamStatusError` as its cause: `isGatewayRefusal(error)` is true for the gateway's 401
41
+ and 403.
42
+
43
+ ## Fixtures
44
+
45
+ `@haatlabs-core/provider-background/fixtures`: `backgroundFixtures.image` (an 8 x 6 WebP) and
46
+ `backgroundFixtures.cutout` (the RGBA PNG answered for it, which passes every check). Made
47
+ with sharp in the shape rembg answers, not recorded; each read is a fresh copy.
48
+
49
+ ## Testing
50
+
51
+ `pnpm --filter @haatlabs-core/provider-background test`: unit tests against a fake `fetch`.
52
+
53
+ ## Hosted services
54
+
55
+ Without a rembg service of your own, `createBackgroundRemover({ mode: 'haatlabs', apiKey })`
56
+ sends the image (at most 5 MB) to the Haatlabs API on RapidAPI and reads the signed cut-out it
57
+ answers with: a PNG with an alpha channel, which may be smaller than the image when the API
58
+ scaled a large one down. `createBackgroundRemover({ mode: 'service', baseUrl, gatewayKey })` is
59
+ `cutoutFromService`. See `@haatlabs-core/services` and https://haatlabs.shop/docs/services/
@@ -0,0 +1,80 @@
1
+ import type { CallContext } from '@haatlabs-core/providers';
2
+ /** The model the service is asked for when none is named: the one its image holds by default. */
3
+ export declare const BACKGROUND_MODEL = "u2netp";
4
+ export declare const DEFAULT_BACKGROUND_TIMEOUT_MS = 10000;
5
+ /** A cut-out of the largest image sent is a few megabytes; more than this is not one. */
6
+ export declare const DEFAULT_MAX_REPLY_BYTES: number;
7
+ /** The gateway's own cap on a request. */
8
+ export declare const DEFAULT_MAX_IMAGE_BYTES: number;
9
+ /**
10
+ * The service could not give a cut-out. `transient`: it may another time (it is away,
11
+ * slow or failing); otherwise asking again with the same image would get the same.
12
+ * `retryAfterMs`: how long a 429 or 5xx asked to be left alone (its Retry-After, at most
13
+ * five minutes). Through the gateway, a refused status carries an UpstreamStatusError as its
14
+ * `cause` (`isGatewayRefusal` reads it). The message is ours: nothing the service said is
15
+ * carried in it.
16
+ */
17
+ export declare class BackgroundRemovalError extends Error {
18
+ readonly transient: boolean;
19
+ readonly retryAfterMs?: number;
20
+ constructor(message: string, transient: boolean, options?: {
21
+ retryAfterMs?: number;
22
+ cause?: unknown;
23
+ });
24
+ }
25
+ export interface BackgroundRemovalOptions {
26
+ /** The model to ask for: the one the service's image holds. */
27
+ model?: string;
28
+ fetch?: typeof fetch;
29
+ timeoutMs?: number;
30
+ maxReplyBytes?: number;
31
+ /** The largest image sent; a larger one is refused before any request. */
32
+ maxImageBytes?: number;
33
+ /** haatlabs-shared's key; null or absent calls the service directly. */
34
+ gatewayKey?: string | null;
35
+ /**
36
+ * Who the call is for: tier, priority, deadline. The deadline, when sooner than
37
+ * `timeoutMs`, is the time limit, and the one the gateway is given; it is this call's
38
+ * alone (a caller's retry starts it again): pass `signal` for a hard limit.
39
+ */
40
+ call?: CallContext;
41
+ /** The caller's: its abort is rethrown as it is. */
42
+ signal?: AbortSignal;
43
+ }
44
+ /**
45
+ * Asks the background removal service (rembg) for the cut-out of an image: the image with
46
+ * everything but the product made transparent, as a PNG the size of the image.
47
+ *
48
+ * `image` must be a WebP this application made itself, never a file as it came from the web.
49
+ * `baseUrl` must come from configuration, never from a request. The answer is treated as a
50
+ * file from a stranger: its type is told from its bytes, it is held to a size, it must be the
51
+ * size that was sent and have an alpha channel.
52
+ */
53
+ export declare function cutoutFromService(baseUrl: string, image: Buffer, options?: BackgroundRemovalOptions): Promise<Buffer>;
54
+ /**
55
+ * Where the product is in an image, as an outline: a grey PNG the size of the image, white
56
+ * where the product is and black where it is not. The cut-out's alpha channel.
57
+ */
58
+ export declare function outlineFromService(baseUrl: string, image: Buffer, options?: BackgroundRemovalOptions): Promise<Buffer>;
59
+ /** Where cut-outs come from: your own rembg service (or the gateway), or the Haatlabs API. */
60
+ export type BackgroundRemoverConfig = {
61
+ mode: 'service';
62
+ baseUrl: string;
63
+ gatewayKey?: string | null;
64
+ } | {
65
+ mode: 'haatlabs';
66
+ /** Your RapidAPI key for the Haatlabs API (`@haatlabs-core/services`). */
67
+ apiKey: string;
68
+ /** The API's address, when not RapidAPI's (a test's fake API). */
69
+ baseUrl?: string;
70
+ };
71
+ export interface BackgroundRemover {
72
+ /** The cut-out: a PNG with an alpha channel. */
73
+ cutout(image: Buffer, options?: BackgroundRemovalOptions): Promise<Buffer>;
74
+ }
75
+ /**
76
+ * A background remover by configuration. `service` is `cutoutFromService`; `haatlabs` sends
77
+ * the image (at most 5 MB) to the Haatlabs API and reads the signed cut-out it answers with.
78
+ * The API may scale a large image down, so its cut-out can be smaller than the image sent.
79
+ */
80
+ export declare function createBackgroundRemover(config: BackgroundRemoverConfig): BackgroundRemover;
@@ -0,0 +1,241 @@
1
+ import sharp from 'sharp';
2
+ import { gatewayErrorOf, gatewayHeadersFor, localTimeoutMs, retryAfterMsOf, sniffImageType, UpstreamStatusError, sharedCall, } from '@haatlabs-core/providers';
3
+ import { isAppError } from '@haatlabs-core/errors';
4
+ import { createHaatlabsApi, MAX_UPLOAD_BYTES } from '@haatlabs-core/services';
5
+ /** The model the service is asked for when none is named: the one its image holds by default. */
6
+ export const BACKGROUND_MODEL = 'u2netp';
7
+ export const DEFAULT_BACKGROUND_TIMEOUT_MS = 10_000;
8
+ /** A cut-out of the largest image sent is a few megabytes; more than this is not one. */
9
+ export const DEFAULT_MAX_REPLY_BYTES = 30 * 1024 * 1024;
10
+ /** The gateway's own cap on a request. */
11
+ export const DEFAULT_MAX_IMAGE_BYTES = 20 * 1024 * 1024;
12
+ const MAX_REPLY_PIXELS = 25_000_000;
13
+ const HTTP_BAD_REQUEST = 400;
14
+ const HTTP_UNAUTHORIZED = 401;
15
+ const HTTP_FORBIDDEN = 403;
16
+ const HTTP_SERVER_ERROR = 500;
17
+ const HTTP_TOO_MANY_REQUESTS = 429;
18
+ const NO_ANSWER = 'The background removal service did not answer';
19
+ const BAD_ANSWER = 'The background removal service gave an answer that cannot be used';
20
+ /**
21
+ * The service could not give a cut-out. `transient`: it may another time (it is away,
22
+ * slow or failing); otherwise asking again with the same image would get the same.
23
+ * `retryAfterMs`: how long a 429 or 5xx asked to be left alone (its Retry-After, at most
24
+ * five minutes). Through the gateway, a refused status carries an UpstreamStatusError as its
25
+ * `cause` (`isGatewayRefusal` reads it). The message is ours: nothing the service said is
26
+ * carried in it.
27
+ */
28
+ export class BackgroundRemovalError extends Error {
29
+ transient;
30
+ retryAfterMs;
31
+ constructor(message, transient, options = {}) {
32
+ super(message, options.cause === undefined ? undefined : { cause: options.cause });
33
+ this.transient = transient;
34
+ this.name = 'BackgroundRemovalError';
35
+ if (options.retryAfterMs !== undefined)
36
+ this.retryAfterMs = options.retryAfterMs;
37
+ }
38
+ }
39
+ /** The caller's abort is rethrown as theirs. */
40
+ function throwIfCallerAborted(signal) {
41
+ if (!signal?.aborted)
42
+ return;
43
+ const reason = signal.reason;
44
+ throw reason instanceof Error
45
+ ? reason
46
+ : new DOMException('The removal was aborted', 'AbortError');
47
+ }
48
+ /** Reads a reply up to a limit, and stops reading as soon as it is passed. */
49
+ async function readUpTo(response, limit) {
50
+ const reader = response.body?.getReader();
51
+ if (!reader)
52
+ return Buffer.alloc(0);
53
+ const chunks = [];
54
+ let total = 0;
55
+ for (;;) {
56
+ const { done, value } = await reader.read();
57
+ if (done)
58
+ break;
59
+ total += value.byteLength;
60
+ if (total > limit) {
61
+ await reader.cancel().catch(() => undefined);
62
+ return null;
63
+ }
64
+ chunks.push(value);
65
+ }
66
+ return Buffer.concat(chunks);
67
+ }
68
+ /**
69
+ * Asks the background removal service (rembg) for the cut-out of an image: the image with
70
+ * everything but the product made transparent, as a PNG the size of the image.
71
+ *
72
+ * `image` must be a WebP this application made itself, never a file as it came from the web.
73
+ * `baseUrl` must come from configuration, never from a request. The answer is treated as a
74
+ * file from a stranger: its type is told from its bytes, it is held to a size, it must be the
75
+ * size that was sent and have an alpha channel.
76
+ */
77
+ export async function cutoutFromService(baseUrl, image, options = {}) {
78
+ const send = options.fetch ?? fetch;
79
+ const timeoutMs = options.timeoutMs ?? DEFAULT_BACKGROUND_TIMEOUT_MS;
80
+ if (image.length > (options.maxImageBytes ?? DEFAULT_MAX_IMAGE_BYTES)) {
81
+ throw new BackgroundRemovalError('The image is too large to send for background removal', false);
82
+ }
83
+ const asked = await sharp(image).metadata();
84
+ const form = new FormData();
85
+ form.append('file', new File([image], 'image.webp', { type: 'image/webp' }));
86
+ form.append('model', options.model ?? BACKGROUND_MODEL);
87
+ const limitMs = localTimeoutMs(timeoutMs, options.call);
88
+ const gatewayKey = options.gatewayKey ?? null;
89
+ const timeout = AbortSignal.timeout(limitMs);
90
+ const signal = options.signal ? AbortSignal.any([timeout, options.signal]) : timeout;
91
+ let reply;
92
+ try {
93
+ const response = await sharedCall('rembg', () => send(`${baseUrl.replace(/\/+$/, '')}/api/remove`, {
94
+ method: 'POST',
95
+ body: form,
96
+ // The gateway is given no longer than this call waits for it.
97
+ headers: gatewayHeadersFor(gatewayKey, options.call && { ...options.call, deadlineMs: limitMs }, limitMs),
98
+ redirect: 'error',
99
+ signal,
100
+ }), (answer) => answer.status);
101
+ if (!response.ok) {
102
+ const status = response.status;
103
+ let cause;
104
+ if (gatewayKey) {
105
+ // gatewayErrorOf reads at most 2 KiB of the body and lets the rest go.
106
+ const word = await gatewayErrorOf(response);
107
+ cause = new UpstreamStatusError(status, word, status === HTTP_UNAUTHORIZED || status === HTTP_FORBIDDEN, status === HTTP_BAD_REQUEST && word === 'bad_request');
108
+ }
109
+ else
110
+ await response.body?.cancel().catch(() => undefined);
111
+ const transient = status === HTTP_TOO_MANY_REQUESTS || status >= HTTP_SERVER_ERROR;
112
+ throw new BackgroundRemovalError(`${NO_ANSWER} (HTTP ${status})`, transient, {
113
+ retryAfterMs: transient ? retryAfterMsOf(response.headers) : undefined,
114
+ cause,
115
+ });
116
+ }
117
+ reply = await readUpTo(response, options.maxReplyBytes ?? DEFAULT_MAX_REPLY_BYTES);
118
+ }
119
+ catch (error) {
120
+ if (options.signal?.aborted) {
121
+ const reason = options.signal.reason;
122
+ throw reason instanceof Error
123
+ ? reason
124
+ : new DOMException('The removal was aborted', 'AbortError');
125
+ }
126
+ if (error instanceof BackgroundRemovalError)
127
+ throw error;
128
+ // Away, refused, cut off or too slow: none of them says anything about the image.
129
+ throw new BackgroundRemovalError(NO_ANSWER, true);
130
+ }
131
+ throwIfCallerAborted(options.signal);
132
+ if (reply === null || sniffImageType(reply) !== 'png') {
133
+ throw new BackgroundRemovalError(BAD_ANSWER, false);
134
+ }
135
+ try {
136
+ const answered = await sharp(reply, { limitInputPixels: MAX_REPLY_PIXELS }).metadata();
137
+ if (!answered.hasAlpha || answered.width !== asked.width || answered.height !== asked.height) {
138
+ throw new BackgroundRemovalError(BAD_ANSWER, false);
139
+ }
140
+ }
141
+ catch (error) {
142
+ if (error instanceof BackgroundRemovalError)
143
+ throw error;
144
+ throw new BackgroundRemovalError(BAD_ANSWER, false);
145
+ }
146
+ return reply;
147
+ }
148
+ /**
149
+ * Where the product is in an image, as an outline: a grey PNG the size of the image, white
150
+ * where the product is and black where it is not. The cut-out's alpha channel.
151
+ */
152
+ export async function outlineFromService(baseUrl, image, options = {}) {
153
+ const cutout = await cutoutFromService(baseUrl, image, options);
154
+ try {
155
+ return await sharp(cutout, { limitInputPixels: MAX_REPLY_PIXELS, failOn: 'error' })
156
+ .extractChannel('alpha')
157
+ .toColourspace('b-w')
158
+ .png()
159
+ .toBuffer();
160
+ }
161
+ catch {
162
+ throw new BackgroundRemovalError(BAD_ANSWER, false);
163
+ }
164
+ }
165
+ /**
166
+ * A background remover by configuration. `service` is `cutoutFromService`; `haatlabs` sends
167
+ * the image (at most 5 MB) to the Haatlabs API and reads the signed cut-out it answers with.
168
+ * The API may scale a large image down, so its cut-out can be smaller than the image sent.
169
+ */
170
+ export function createBackgroundRemover(config) {
171
+ if (config.mode === 'service') {
172
+ return {
173
+ cutout: (image, options = {}) => cutoutFromService(config.baseUrl, image, {
174
+ ...options,
175
+ gatewayKey: options.gatewayKey ?? config.gatewayKey ?? null,
176
+ }),
177
+ };
178
+ }
179
+ return {
180
+ async cutout(image, options = {}) {
181
+ const send = options.fetch ?? fetch;
182
+ const timeoutMs = options.timeoutMs ?? DEFAULT_BACKGROUND_TIMEOUT_MS * 3;
183
+ if (image.length > MAX_UPLOAD_BYTES) {
184
+ throw new BackgroundRemovalError('The image is too large to send for background removal (5 MB at most)', false);
185
+ }
186
+ const api = createHaatlabsApi({
187
+ apiKey: config.apiKey,
188
+ timeoutMs,
189
+ fetch: send,
190
+ ...(config.baseUrl
191
+ ? { baseUrl: config.baseUrl, host: new URL(config.baseUrl).hostname }
192
+ : {}),
193
+ });
194
+ let url;
195
+ try {
196
+ url = (await api.images.removeBackground({ image })).url;
197
+ }
198
+ catch (error) {
199
+ throwIfCallerAborted(options.signal);
200
+ const transient = isAppError(error) ? error.transient : true;
201
+ throw new BackgroundRemovalError(isAppError(error) ? error.message : NO_ANSWER, transient, {
202
+ cause: error,
203
+ });
204
+ }
205
+ let reply;
206
+ try {
207
+ const timeout = AbortSignal.timeout(timeoutMs);
208
+ const response = await send(url, {
209
+ redirect: 'error',
210
+ signal: options.signal ? AbortSignal.any([timeout, options.signal]) : timeout,
211
+ });
212
+ if (!response.ok) {
213
+ await response.body?.cancel().catch(() => undefined);
214
+ throw new BackgroundRemovalError(`${NO_ANSWER} (HTTP ${response.status})`, true);
215
+ }
216
+ reply = await readUpTo(response, options.maxReplyBytes ?? DEFAULT_MAX_REPLY_BYTES);
217
+ }
218
+ catch (error) {
219
+ throwIfCallerAborted(options.signal);
220
+ if (error instanceof BackgroundRemovalError)
221
+ throw error;
222
+ throw new BackgroundRemovalError(NO_ANSWER, true);
223
+ }
224
+ if (reply === null || sniffImageType(reply) !== 'png') {
225
+ throw new BackgroundRemovalError(BAD_ANSWER, false);
226
+ }
227
+ try {
228
+ const answered = await sharp(reply, { limitInputPixels: MAX_REPLY_PIXELS }).metadata();
229
+ if (!answered.hasAlpha)
230
+ throw new BackgroundRemovalError(BAD_ANSWER, false);
231
+ }
232
+ catch (error) {
233
+ if (error instanceof BackgroundRemovalError)
234
+ throw error;
235
+ throw new BackgroundRemovalError(BAD_ANSWER, false);
236
+ }
237
+ return reply;
238
+ },
239
+ };
240
+ }
241
+ //# sourceMappingURL=background.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"background.js","sourceRoot":"","sources":["../src/background.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,MAAM,OAAO,CAAC;AAC1B,OAAO,EACL,cAAc,EACd,iBAAiB,EACjB,cAAc,EACd,cAAc,EACd,cAAc,EACd,mBAAmB,EACnB,UAAU,GACX,MAAM,qBAAqB,CAAC;AAE7B,OAAO,EAAE,UAAU,EAAE,MAAM,kBAAkB,CAAC;AAC9C,OAAO,EAAE,iBAAiB,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AAEzE,iGAAiG;AACjG,MAAM,CAAC,MAAM,gBAAgB,GAAG,QAAQ,CAAC;AACzC,MAAM,CAAC,MAAM,6BAA6B,GAAG,MAAM,CAAC;AACpD,yFAAyF;AACzF,MAAM,CAAC,MAAM,uBAAuB,GAAG,EAAE,GAAG,IAAI,GAAG,IAAI,CAAC;AACxD,0CAA0C;AAC1C,MAAM,CAAC,MAAM,uBAAuB,GAAG,EAAE,GAAG,IAAI,GAAG,IAAI,CAAC;AACxD,MAAM,gBAAgB,GAAG,UAAU,CAAC;AACpC,MAAM,gBAAgB,GAAG,GAAG,CAAC;AAC7B,MAAM,iBAAiB,GAAG,GAAG,CAAC;AAC9B,MAAM,cAAc,GAAG,GAAG,CAAC;AAC3B,MAAM,iBAAiB,GAAG,GAAG,CAAC;AAC9B,MAAM,sBAAsB,GAAG,GAAG,CAAC;AACnC,MAAM,SAAS,GAAG,+CAA+C,CAAC;AAClE,MAAM,UAAU,GA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gB,EAAE,gBAAgB,EAAE,CAAC,CAAC,QAAQ,EAAE,CAAC;gBACvF,IAAI,CAAC,QAAQ,CAAC,QAAQ;oBAAE,MAAM,IAAI,sBAAsB,CAAC,UAAU,EAAE,KAAK,CAAC,CAAC;YAC9E,CAAC;YAAC,OAAO,KAAK,EAAE,CAAC;gBACf,IAAI,KAAK,YAAY,sBAAsB;oBAAE,MAAM,KAAK,CAAC;gBACzD,MAAM,IAAI,sBAAsB,CAAC,UAAU,EAAE,KAAK,CAAC,CAAC;YACtD,CAAC;YACD,OAAO,KAAK,CAAC;QACf,CAAC;KACF,CAAC;AACJ,CAAC"}
@@ -0,0 +1,80 @@
1
+ import type { CallContext } from '@haatlabs-core/providers';
2
+ /** The model the service is asked for when none is named: the one its image holds by default. */
3
+ export declare const BACKGROUND_MODEL = "u2netp";
4
+ export declare const DEFAULT_BACKGROUND_TIMEOUT_MS = 10000;
5
+ /** A cut-out of the largest image sent is a few megabytes; more than this is not one. */
6
+ export declare const DEFAULT_MAX_REPLY_BYTES: number;
7
+ /** The gateway's own cap on a request. */
8
+ export declare const DEFAULT_MAX_IMAGE_BYTES: number;
9
+ /**
10
+ * The service could not give a cut-out. `transient`: it may another time (it is away,
11
+ * slow or failing); otherwise asking again with the same image would get the same.
12
+ * `retryAfterMs`: how long a 429 or 5xx asked to be left alone (its Retry-After, at most
13
+ * five minutes). Through the gateway, a refused status carries an UpstreamStatusError as its
14
+ * `cause` (`isGatewayRefusal` reads it). The message is ours: nothing the service said is
15
+ * carried in it.
16
+ */
17
+ export declare class BackgroundRemovalError extends Error {
18
+ readonly transient: boolean;
19
+ readonly retryAfterMs?: number;
20
+ constructor(message: string, transient: boolean, options?: {
21
+ retryAfterMs?: number;
22
+ cause?: unknown;
23
+ });
24
+ }
25
+ export interface BackgroundRemovalOptions {
26
+ /** The model to ask for: the one the service's image holds. */
27
+ model?: string;
28
+ fetch?: typeof fetch;
29
+ timeoutMs?: number;
30
+ maxReplyBytes?: number;
31
+ /** The largest image sent; a larger one is refused before any request. */
32
+ maxImageBytes?: number;
33
+ /** haatlabs-shared's key; null or absent calls the service directly. */
34
+ gatewayKey?: string | null;
35
+ /**
36
+ * Who the call is for: tier, priority, deadline. The deadline, when sooner than
37
+ * `timeoutMs`, is the time limit, and the one the gateway is given; it is this call's
38
+ * alone (a caller's retry starts it again): pass `signal` for a hard limit.
39
+ */
40
+ call?: CallContext;
41
+ /** The caller's: its abort is rethrown as it is. */
42
+ signal?: AbortSignal;
43
+ }
44
+ /**
45
+ * Asks the background removal service (rembg) for the cut-out of an image: the image with
46
+ * everything but the product made transparent, as a PNG the size of the image.
47
+ *
48
+ * `image` must be a WebP this application made itself, never a file as it came from the web.
49
+ * `baseUrl` must come from configuration, never from a request. The answer is treated as a
50
+ * file from a stranger: its type is told from its bytes, it is held to a size, it must be the
51
+ * size that was sent and have an alpha channel.
52
+ */
53
+ export declare function cutoutFromService(baseUrl: string, image: Buffer, options?: BackgroundRemovalOptions): Promise<Buffer>;
54
+ /**
55
+ * Where the product is in an image, as an outline: a grey PNG the size of the image, white
56
+ * where the product is and black where it is not. The cut-out's alpha channel.
57
+ */
58
+ export declare function outlineFromService(baseUrl: string, image: Buffer, options?: BackgroundRemovalOptions): Promise<Buffer>;
59
+ /** Where cut-outs come from: your own rembg service (or the gateway), or the Haatlabs API. */
60
+ export type BackgroundRemoverConfig = {
61
+ mode: 'service';
62
+ baseUrl: string;
63
+ gatewayKey?: string | null;
64
+ } | {
65
+ mode: 'haatlabs';
66
+ /** Your RapidAPI key for the Haatlabs API (`@haatlabs-core/services`). */
67
+ apiKey: string;
68
+ /** The API's address, when not RapidAPI's (a test's fake API). */
69
+ baseUrl?: string;
70
+ };
71
+ export interface BackgroundRemover {
72
+ /** The cut-out: a PNG with an alpha channel. */
73
+ cutout(image: Buffer, options?: BackgroundRemovalOptions): Promise<Buffer>;
74
+ }
75
+ /**
76
+ * A background remover by configuration. `service` is `cutoutFromService`; `haatlabs` sends
77
+ * the image (at most 5 MB) to the Haatlabs API and reads the signed cut-out it answers with.
78
+ * The API may scale a large image down, so its cut-out can be smaller than the image sent.
79
+ */
80
+ export declare function createBackgroundRemover(config: BackgroundRemoverConfig): BackgroundRemover;
@@ -0,0 +1,240 @@
1
+ var __create = Object.create;
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __getProtoOf = Object.getPrototypeOf;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ var __export = (target, all) => {
8
+ for (var name in all)
9
+ __defProp(target, name, { get: all[name], enumerable: true });
10
+ };
11
+ var __copyProps = (to, from, except, desc) => {
12
+ if (from && typeof from === "object" || typeof from === "function") {
13
+ for (let key of __getOwnPropNames(from))
14
+ if (!__hasOwnProp.call(to, key) && key !== except)
15
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
16
+ }
17
+ return to;
18
+ };
19
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
20
+ // If the importer is in node compatibility mode or this is not an ESM
21
+ // file that has been converted to a CommonJS file using a Babel-
22
+ // compatible transform (i.e. "__esModule" has not been set), then set
23
+ // "default" to the CommonJS "module.exports" for node compatibility.
24
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
25
+ mod
26
+ ));
27
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
28
+ var background_exports = {};
29
+ __export(background_exports, {
30
+ BACKGROUND_MODEL: () => BACKGROUND_MODEL,
31
+ BackgroundRemovalError: () => BackgroundRemovalError,
32
+ DEFAULT_BACKGROUND_TIMEOUT_MS: () => DEFAULT_BACKGROUND_TIMEOUT_MS,
33
+ DEFAULT_MAX_IMAGE_BYTES: () => DEFAULT_MAX_IMAGE_BYTES,
34
+ DEFAULT_MAX_REPLY_BYTES: () => DEFAULT_MAX_REPLY_BYTES,
35
+ createBackgroundRemover: () => createBackgroundRemover,
36
+ cutoutFromService: () => cutoutFromService,
37
+ outlineFromService: () => outlineFromService
38
+ });
39
+ module.exports = __toCommonJS(background_exports);
40
+ var import_sharp = __toESM(require("sharp"));
41
+ var import_providers = require("@haatlabs-core/providers");
42
+ var import_errors = require("@haatlabs-core/errors");
43
+ var import_services = require("@haatlabs-core/services");
44
+ const BACKGROUND_MODEL = "u2netp";
45
+ const DEFAULT_BACKGROUND_TIMEOUT_MS = 1e4;
46
+ const DEFAULT_MAX_REPLY_BYTES = 30 * 1024 * 1024;
47
+ const DEFAULT_MAX_IMAGE_BYTES = 20 * 1024 * 1024;
48
+ const MAX_REPLY_PIXELS = 25e6;
49
+ const HTTP_BAD_REQUEST = 400;
50
+ const HTTP_UNAUTHORIZED = 401;
51
+ const HTTP_FORBIDDEN = 403;
52
+ const HTTP_SERVER_ERROR = 500;
53
+ const HTTP_TOO_MANY_REQUESTS = 429;
54
+ const NO_ANSWER = "The background removal service did not answer";
55
+ const BAD_ANSWER = "The background removal service gave an answer that cannot be used";
56
+ class BackgroundRemovalError extends Error {
57
+ transient;
58
+ retryAfterMs;
59
+ constructor(message, transient, options = {}) {
60
+ super(message, options.cause === void 0 ? void 0 : { cause: options.cause });
61
+ this.transient = transient;
62
+ this.name = "BackgroundRemovalError";
63
+ if (options.retryAfterMs !== void 0)
64
+ this.retryAfterMs = options.retryAfterMs;
65
+ }
66
+ }
67
+ function throwIfCallerAborted(signal) {
68
+ if (!signal?.aborted)
69
+ return;
70
+ const reason = signal.reason;
71
+ throw reason instanceof Error ? reason : new DOMException("The removal was aborted", "AbortError");
72
+ }
73
+ async function readUpTo(response, limit) {
74
+ const reader = response.body?.getReader();
75
+ if (!reader)
76
+ return Buffer.alloc(0);
77
+ const chunks = [];
78
+ let total = 0;
79
+ for (; ; ) {
80
+ const { done, value } = await reader.read();
81
+ if (done)
82
+ break;
83
+ total += value.byteLength;
84
+ if (total > limit) {
85
+ await reader.cancel().catch(() => void 0);
86
+ return null;
87
+ }
88
+ chunks.push(value);
89
+ }
90
+ return Buffer.concat(chunks);
91
+ }
92
+ async function cutoutFromService(baseUrl, image, options = {}) {
93
+ const send = options.fetch ?? fetch;
94
+ const timeoutMs = options.timeoutMs ?? DEFAULT_BACKGROUND_TIMEOUT_MS;
95
+ if (image.length > (options.maxImageBytes ?? DEFAULT_MAX_IMAGE_BYTES)) {
96
+ throw new BackgroundRemovalError("The image is too large to send for background removal", false);
97
+ }
98
+ const asked = await (0, import_sharp.default)(image).metadata();
99
+ const form = new FormData();
100
+ form.append("file", new File([image], "image.webp", { type: "image/webp" }));
101
+ form.append("model", options.model ?? BACKGROUND_MODEL);
102
+ const limitMs = (0, import_providers.localTimeoutMs)(timeoutMs, options.call);
103
+ const gatewayKey = options.gatewayKey ?? null;
104
+ const timeout = AbortSignal.timeout(limitMs);
105
+ const signal = options.signal ? AbortSignal.any([timeout, options.signal]) : timeout;
106
+ let reply;
107
+ try {
108
+ const response = await (0, import_providers.sharedCall)("rembg", () => send(`${baseUrl.replace(/\/+$/, "")}/api/remove`, {
109
+ method: "POST",
110
+ body: form,
111
+ // The gateway is given no longer than this call waits for it.
112
+ headers: (0, import_providers.gatewayHeadersFor)(gatewayKey, options.call && { ...options.call, deadlineMs: limitMs }, limitMs),
113
+ redirect: "error",
114
+ signal
115
+ }), (answer) => answer.status);
116
+ if (!response.ok) {
117
+ const status = response.status;
118
+ let cause;
119
+ if (gatewayKey) {
120
+ const word = await (0, import_providers.gatewayErrorOf)(response);
121
+ cause = new import_providers.UpstreamStatusError(status, word, status === HTTP_UNAUTHORIZED || status === HTTP_FORBIDDEN, status === HTTP_BAD_REQUEST && word === "bad_request");
122
+ } else
123
+ await response.body?.cancel().catch(() => void 0);
124
+ const transient = status === HTTP_TOO_MANY_REQUESTS || status >= HTTP_SERVER_ERROR;
125
+ throw new BackgroundRemovalError(`${NO_ANSWER} (HTTP ${status})`, transient, {
126
+ retryAfterMs: transient ? (0, import_providers.retryAfterMsOf)(response.headers) : void 0,
127
+ cause
128
+ });
129
+ }
130
+ reply = await readUpTo(response, options.maxReplyBytes ?? DEFAULT_MAX_REPLY_BYTES);
131
+ } catch (error) {
132
+ if (options.signal?.aborted) {
133
+ const reason = options.signal.reason;
134
+ throw reason instanceof Error ? reason : new DOMException("The removal was aborted", "AbortError");
135
+ }
136
+ if (error instanceof BackgroundRemovalError)
137
+ throw error;
138
+ throw new BackgroundRemovalError(NO_ANSWER, true);
139
+ }
140
+ throwIfCallerAborted(options.signal);
141
+ if (reply === null || (0, import_providers.sniffImageType)(reply) !== "png") {
142
+ throw new BackgroundRemovalError(BAD_ANSWER, false);
143
+ }
144
+ try {
145
+ const answered = await (0, import_sharp.default)(reply, { limitInputPixels: MAX_REPLY_PIXELS }).metadata();
146
+ if (!answered.hasAlpha || answered.width !== asked.width || answered.height !== asked.height) {
147
+ throw new BackgroundRemovalError(BAD_ANSWER, false);
148
+ }
149
+ } catch (error) {
150
+ if (error instanceof BackgroundRemovalError)
151
+ throw error;
152
+ throw new BackgroundRemovalError(BAD_ANSWER, false);
153
+ }
154
+ return reply;
155
+ }
156
+ async function outlineFromService(baseUrl, image, options = {}) {
157
+ const cutout = await cutoutFromService(baseUrl, image, options);
158
+ try {
159
+ return await (0, import_sharp.default)(cutout, { limitInputPixels: MAX_REPLY_PIXELS, failOn: "error" }).extractChannel("alpha").toColourspace("b-w").png().toBuffer();
160
+ } catch {
161
+ throw new BackgroundRemovalError(BAD_ANSWER, false);
162
+ }
163
+ }
164
+ function createBackgroundRemover(config) {
165
+ if (config.mode === "service") {
166
+ return {
167
+ cutout: (image, options = {}) => cutoutFromService(config.baseUrl, image, {
168
+ ...options,
169
+ gatewayKey: options.gatewayKey ?? config.gatewayKey ?? null
170
+ })
171
+ };
172
+ }
173
+ return {
174
+ async cutout(image, options = {}) {
175
+ const send = options.fetch ?? fetch;
176
+ const timeoutMs = options.timeoutMs ?? DEFAULT_BACKGROUND_TIMEOUT_MS * 3;
177
+ if (image.length > import_services.MAX_UPLOAD_BYTES) {
178
+ throw new BackgroundRemovalError("The image is too large to send for background removal (5 MB at most)", false);
179
+ }
180
+ const api = (0, import_services.createHaatlabsApi)({
181
+ apiKey: config.apiKey,
182
+ timeoutMs,
183
+ fetch: send,
184
+ ...config.baseUrl ? { baseUrl: config.baseUrl, host: new URL(config.baseUrl).hostname } : {}
185
+ });
186
+ let url;
187
+ try {
188
+ url = (await api.images.removeBackground({ image })).url;
189
+ } catch (error) {
190
+ throwIfCallerAborted(options.signal);
191
+ const transient = (0, import_errors.isAppError)(error) ? error.transient : true;
192
+ throw new BackgroundRemovalError((0, import_errors.isAppError)(error) ? error.message : NO_ANSWER, transient, {
193
+ cause: error
194
+ });
195
+ }
196
+ let reply;
197
+ try {
198
+ const timeout = AbortSignal.timeout(timeoutMs);
199
+ const response = await send(url, {
200
+ redirect: "error",
201
+ signal: options.signal ? AbortSignal.any([timeout, options.signal]) : timeout
202
+ });
203
+ if (!response.ok) {
204
+ await response.body?.cancel().catch(() => void 0);
205
+ throw new BackgroundRemovalError(`${NO_ANSWER} (HTTP ${response.status})`, true);
206
+ }
207
+ reply = await readUpTo(response, options.maxReplyBytes ?? DEFAULT_MAX_REPLY_BYTES);
208
+ } catch (error) {
209
+ throwIfCallerAborted(options.signal);
210
+ if (error instanceof BackgroundRemovalError)
211
+ throw error;
212
+ throw new BackgroundRemovalError(NO_ANSWER, true);
213
+ }
214
+ if (reply === null || (0, import_providers.sniffImageType)(reply) !== "png") {
215
+ throw new BackgroundRemovalError(BAD_ANSWER, false);
216
+ }
217
+ try {
218
+ const answered = await (0, import_sharp.default)(reply, { limitInputPixels: MAX_REPLY_PIXELS }).metadata();
219
+ if (!answered.hasAlpha)
220
+ throw new BackgroundRemovalError(BAD_ANSWER, false);
221
+ } catch (error) {
222
+ if (error instanceof BackgroundRemovalError)
223
+ throw error;
224
+ throw new BackgroundRemovalError(BAD_ANSWER, false);
225
+ }
226
+ return reply;
227
+ }
228
+ };
229
+ }
230
+ // Annotate the CommonJS export names for ESM import in node:
231
+ 0 && (module.exports = {
232
+ BACKGROUND_MODEL,
233
+ BackgroundRemovalError,
234
+ DEFAULT_BACKGROUND_TIMEOUT_MS,
235
+ DEFAULT_MAX_IMAGE_BYTES,
236
+ DEFAULT_MAX_REPLY_BYTES,
237
+ createBackgroundRemover,
238
+ cutoutFromService,
239
+ outlineFromService
240
+ });
@@ -0,0 +1,10 @@
1
+ /**
2
+ * One exchange with the background removal service, for tests that must not reach it: an
3
+ * 8 x 6 WebP of the kind sent, and the cut-out answered for it (an RGBA PNG the same size,
4
+ * its left half kept). Made with sharp in the shape rembg answers, not recorded. Each read
5
+ * is a fresh copy.
6
+ */
7
+ export declare const backgroundFixtures: {
8
+ readonly image: Buffer;
9
+ readonly cutout: Buffer;
10
+ };
@@ -0,0 +1,34 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
3
+ var __getOwnPropNames = Object.getOwnPropertyNames;
4
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
5
+ var __export = (target, all) => {
6
+ for (var name in all)
7
+ __defProp(target, name, { get: all[name], enumerable: true });
8
+ };
9
+ var __copyProps = (to, from, except, desc) => {
10
+ if (from && typeof from === "object" || typeof from === "function") {
11
+ for (let key of __getOwnPropNames(from))
12
+ if (!__hasOwnProp.call(to, key) && key !== except)
13
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
14
+ }
15
+ return to;
16
+ };
17
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
18
+ var fixtures_exports = {};
19
+ __export(fixtures_exports, {
20
+ backgroundFixtures: () => backgroundFixtures
21
+ });
22
+ module.exports = __toCommonJS(fixtures_exports);
23
+ const backgroundFixtures = {
24
+ get image() {
25
+ return Buffer.from("UklGRiIAAABXRUJQVlA4TBYAAAAvB0ABAAfQzGY2s/8BgCD8b5uI6H8I", "base64");
26
+ },
27
+ get cutout() {
28
+ return Buffer.from("iVBORw0KGgoAAAANSUhEUgAAAAgAAAAGCAYAAAD+Bd/7AAAACXBIWXMAAAPoAAAD6AG1e1JrAAAAFUlEQVQI12OYOXPmfzTMgIwZhoICAFCfbfnbwRq3AAAAAElFTkSuQmCC", "base64");
29
+ }
30
+ };
31
+ // Annotate the CommonJS export names for ESM import in node:
32
+ 0 && (module.exports = {
33
+ backgroundFixtures
34
+ });
@@ -0,0 +1 @@
1
+ export * from './background.js';
@@ -0,0 +1,21 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
3
+ var __getOwnPropNames = Object.getOwnPropertyNames;
4
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
5
+ var __copyProps = (to, from, except, desc) => {
6
+ if (from && typeof from === "object" || typeof from === "function") {
7
+ for (let key of __getOwnPropNames(from))
8
+ if (!__hasOwnProp.call(to, key) && key !== except)
9
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
10
+ }
11
+ return to;
12
+ };
13
+ var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default"));
14
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
15
+ var index_exports = {};
16
+ module.exports = __toCommonJS(index_exports);
17
+ __reExport(index_exports, require("./background.js"), module.exports);
18
+ // Annotate the CommonJS export names for ESM import in node:
19
+ 0 && (module.exports = {
20
+ ...require("./background.js")
21
+ });
@@ -0,0 +1,8 @@
1
+ {
2
+ "type": "commonjs",
3
+ "publishConfig": {
4
+ "access": "public",
5
+ "registry": "https://registry.npmjs.org"
6
+ },
7
+ "platformRegistry": "npm"
8
+ }
@@ -0,0 +1,10 @@
1
+ /**
2
+ * One exchange with the background removal service, for tests that must not reach it: an
3
+ * 8 x 6 WebP of the kind sent, and the cut-out answered for it (an RGBA PNG the same size,
4
+ * its left half kept). Made with sharp in the shape rembg answers, not recorded. Each read
5
+ * is a fresh copy.
6
+ */
7
+ export declare const backgroundFixtures: {
8
+ readonly image: Buffer;
9
+ readonly cutout: Buffer;
10
+ };
@@ -0,0 +1,15 @@
1
+ /**
2
+ * One exchange with the background removal service, for tests that must not reach it: an
3
+ * 8 x 6 WebP of the kind sent, and the cut-out answered for it (an RGBA PNG the same size,
4
+ * its left half kept). Made with sharp in the shape rembg answers, not recorded. Each read
5
+ * is a fresh copy.
6
+ */
7
+ export const backgroundFixtures = {
8
+ get image() {
9
+ return Buffer.from('UklGRiIAAABXRUJQVlA4TBYAAAAvB0ABAAfQzGY2s/8BgCD8b5uI6H8I', 'base64');
10
+ },
11
+ get cutout() {
12
+ return Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAgAAAAGCAYAAAD+Bd/7AAAACXBIWXMAAAPoAAAD6AG1e1JrAAAAFUlEQVQI12OYOXPmfzTMgIwZhoICAFCfbfnbwRq3AAAAAElFTkSuQmCC', 'base64');
13
+ },
14
+ };
15
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/fixtures/index.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,MAAM,CAAC,MAAM,kBAAkB,GAAwD;IACrF,IAAI,KAAK;QACP,OAAO,MAAM,CAAC,IAAI,CAAC,0DAA0D,EAAE,QAAQ,CAAC,CAAC;IAC3F,CAAC;IACD,IAAI,MAAM;QACR,OAAO,MAAM,CAAC,IAAI,CAChB,sIAAsI,EACtI,QAAQ,CACT,CAAC;IACJ,CAAC;CACF,CAAC"}
@@ -0,0 +1 @@
1
+ export * from './background.js';
package/dist/index.js ADDED
@@ -0,0 +1,2 @@
1
+ export * from './background.js';
2
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,iBAAiB,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,71 @@
1
1
  {
2
2
  "name": "@haatlabs-core/provider-background",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.10.0",
4
+ "description": "Background removal through a rembg service.",
5
+ "keywords": [
6
+ "haatlabs",
7
+ "rembg"
8
+ ],
9
+ "homepage": "https://haatlabs.shop/docs/packages/provider-background/",
10
+ "license": "Apache-2.0",
11
+ "type": "module",
12
+ "engines": {
13
+ "node": ">=24"
14
+ },
15
+ "repository": {
16
+ "type": "git",
17
+ "url": "git+https://github.com/Haatlabs/haatlabs-platform.git",
18
+ "directory": "packages/provider-background"
19
+ },
20
+ "publishConfig": {
21
+ "access": "public",
22
+ "registry": "https://registry.npmjs.org"
23
+ },
24
+ "files": [
25
+ "dist"
26
+ ],
27
+ "exports": {
28
+ ".": {
29
+ "import": {
30
+ "types": "./dist/index.d.ts",
31
+ "default": "./dist/index.js"
32
+ },
33
+ "require": {
34
+ "types": "./dist/cjs/index.d.ts",
35
+ "default": "./dist/cjs/index.js"
36
+ }
37
+ },
38
+ "./fixtures": {
39
+ "import": {
40
+ "types": "./dist/fixtures/index.d.ts",
41
+ "default": "./dist/fixtures/index.js"
42
+ },
43
+ "require": {
44
+ "types": "./dist/cjs/fixtures/index.d.ts",
45
+ "default": "./dist/cjs/fixtures/index.js"
46
+ }
47
+ }
48
+ },
49
+ "dependencies": {
50
+ "@haatlabs-core/errors": "0.10.0",
51
+ "@haatlabs-core/providers": "0.10.0",
52
+ "@haatlabs-core/services": "0.10.0"
53
+ },
54
+ "peerDependencies": {
55
+ "sharp": "^0.35.0"
56
+ },
57
+ "devDependencies": {
58
+ "@opentelemetry/sdk-trace-node": "^2.11.0",
59
+ "sharp": "^0.35.5",
60
+ "@haatlabs-core/tsconfig": "0.10.0",
61
+ "@haatlabs-core/observability": "0.10.0",
62
+ "@haatlabs-core/vitest-config": "0.10.0"
63
+ },
64
+ "scripts": {
65
+ "build": "rm -rf dist && tsc -p tsconfig.build.json && node ../../scripts/build-cjs.mjs",
66
+ "typecheck": "tsc --noEmit",
67
+ "test": "vitest run",
68
+ "check:package": "publint --strict && attw --pack . --profile node16"
69
+ },
70
+ "platformRegistry": "npm"
71
+ }