Leon4gr45 commited on
Commit
86e413c
·
verified ·
1 Parent(s): 62119f7

Upload folder using huggingface_hub (part 11)

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +11 -0
  2. node_modules/get-tsconfig/LICENSE +21 -0
  3. node_modules/get-tsconfig/README.md +295 -0
  4. node_modules/get-tsconfig/package.json +44 -0
  5. node_modules/get-tsconfig/skills/get-tsconfig/MIGRATION.md +194 -0
  6. node_modules/get-tsconfig/skills/get-tsconfig/SKILL.md +170 -0
  7. node_modules/gifwrap/.jshintrc +4 -0
  8. node_modules/gifwrap/LICENSE +21 -0
  9. node_modules/gifwrap/README.md +668 -0
  10. node_modules/gifwrap/index.d.ts +153 -0
  11. node_modules/gifwrap/package.json +39 -0
  12. node_modules/gifwrap/src/bitmapimage.js +310 -0
  13. node_modules/gifwrap/src/gif.js +69 -0
  14. node_modules/gifwrap/src/gifcodec.js +404 -0
  15. node_modules/gifwrap/src/gifframe.js +114 -0
  16. node_modules/gifwrap/src/gifutil.js +373 -0
  17. node_modules/gifwrap/src/index.js +16 -0
  18. node_modules/gifwrap/src/omggif.d.ts +56 -0
  19. node_modules/gifwrap/templates/README.hbs +267 -0
  20. node_modules/gifwrap/test/fixtures/count5x7.gif +0 -0
  21. node_modules/gifwrap/test/fixtures/countConstantDelay0.gif +0 -0
  22. node_modules/gifwrap/test/fixtures/countConstantDelay1.gif +0 -0
  23. node_modules/gifwrap/test/fixtures/countConstantDelay3.gif +0 -0
  24. node_modules/gifwrap/test/fixtures/countIncreasingDelay.gif +0 -0
  25. node_modules/gifwrap/test/fixtures/hairstreak.jpg +0 -0
  26. node_modules/gifwrap/test/fixtures/lenna.png +0 -0
  27. node_modules/gifwrap/test/fixtures/nburling-public.gif +0 -0
  28. node_modules/gifwrap/test/fixtures/pelagrina.jpg +0 -0
  29. node_modules/gifwrap/test/fixtures/penguins.png +0 -0
  30. node_modules/gifwrap/test/fixtures/quantized/hairstreak256_Dekker.png +0 -0
  31. node_modules/gifwrap/test/fixtures/quantized/hairstreak256_Sorokin.png +0 -0
  32. node_modules/gifwrap/test/fixtures/quantized/hairstreak256_Wu.png +0 -0
  33. node_modules/gifwrap/test/fixtures/quantized/hairstreak32_Dekker.png +0 -0
  34. node_modules/gifwrap/test/fixtures/quantized/hairstreak32_Sorokin.png +0 -0
  35. node_modules/gifwrap/test/fixtures/quantized/hairstreak32_Wu.png +0 -0
  36. node_modules/gifwrap/test/fixtures/quantized/rosewithtrans256_Dekker.png +0 -0
  37. node_modules/gifwrap/test/fixtures/quantized/rosewithtrans256_Sorokin.png +0 -0
  38. node_modules/gifwrap/test/fixtures/quantized/rosewithtrans256_Wu.png +0 -0
  39. node_modules/gifwrap/test/fixtures/quantized/rosewithtrans32_Dekker.png +0 -0
  40. node_modules/gifwrap/test/fixtures/quantized/rosewithtrans32_Sorokin.png +0 -0
  41. node_modules/gifwrap/test/fixtures/quantized/rosewithtrans32_Wu.png +0 -0
  42. node_modules/gifwrap/test/fixtures/quantized/sculptmap256_Dekker.png +0 -0
  43. node_modules/gifwrap/test/fixtures/quantized/sculptmap256_Dekker_FloydSteinberg.png +0 -0
  44. node_modules/gifwrap/test/fixtures/quantized/sculptmap256_Sorokin.png +0 -0
  45. node_modules/gifwrap/test/fixtures/quantized/sculptmap256_Sorokin_FloydSteinberg.png +0 -0
  46. node_modules/gifwrap/test/fixtures/quantized/sculptmap256_Wu.png +0 -0
  47. node_modules/gifwrap/test/fixtures/quantized/sculptmap256_Wu_FloydSteinberg.png +0 -0
  48. node_modules/gifwrap/test/fixtures/quantized/sculptmap32_Dekker.png +0 -0
  49. node_modules/gifwrap/test/fixtures/quantized/sculptmap32_Sorokin.png +0 -0
  50. node_modules/gifwrap/test/fixtures/quantized/sculptmap32_Wu.png +0 -0
.gitattributes CHANGED
@@ -40,3 +40,14 @@ node_modules/bare-url/prebuilds/win32-arm64/bare-url.bare filter=lfs diff=lfs me
40
  node_modules/bare-url/prebuilds/win32-x64/bare-url.bare filter=lfs diff=lfs merge=lfs -text
41
  node_modules/better-sqlite3/build/Release/better_sqlite3.node filter=lfs diff=lfs merge=lfs -text
42
  node_modules/exif-parser/test/starfish.jpg filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
 
 
 
 
 
40
  node_modules/bare-url/prebuilds/win32-x64/bare-url.bare filter=lfs diff=lfs merge=lfs -text
41
  node_modules/better-sqlite3/build/Release/better_sqlite3.node filter=lfs diff=lfs merge=lfs -text
42
  node_modules/exif-parser/test/starfish.jpg filter=lfs diff=lfs merge=lfs -text
43
+ node_modules/gifwrap/test/fixtures/hairstreak.jpg filter=lfs diff=lfs merge=lfs -text
44
+ node_modules/gifwrap/test/fixtures/lenna.png filter=lfs diff=lfs merge=lfs -text
45
+ node_modules/gifwrap/test/fixtures/nburling-public.gif filter=lfs diff=lfs merge=lfs -text
46
+ node_modules/gifwrap/test/fixtures/quantized/hairstreak256_Dekker.png filter=lfs diff=lfs merge=lfs -text
47
+ node_modules/gifwrap/test/fixtures/quantized/hairstreak256_Sorokin.png filter=lfs diff=lfs merge=lfs -text
48
+ node_modules/gifwrap/test/fixtures/quantized/hairstreak256_Wu.png filter=lfs diff=lfs merge=lfs -text
49
+ node_modules/gifwrap/test/fixtures/quantized/hairstreak32_Dekker.png filter=lfs diff=lfs merge=lfs -text
50
+ node_modules/gifwrap/test/fixtures/quantized/hairstreak32_Sorokin.png filter=lfs diff=lfs merge=lfs -text
51
+ node_modules/gifwrap/test/fixtures/quantized/hairstreak32_Wu.png filter=lfs diff=lfs merge=lfs -text
52
+ node_modules/gifwrap/test/fixtures/quantized/sculptmap256_Sorokin_FloydSteinberg.png filter=lfs diff=lfs merge=lfs -text
53
+ node_modules/gifwrap/test/fixtures/rnaples-offsets-public.gif filter=lfs diff=lfs merge=lfs -text
node_modules/get-tsconfig/LICENSE ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ MIT License
2
+
3
+ Copyright (c) Hiroki Osame <hiroki.osame@gmail.com>
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
node_modules/get-tsconfig/README.md ADDED
@@ -0,0 +1,295 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <p align="center">
2
+ <img width="160" src=".github/logo.webp">
3
+ </p>
4
+ <h1 align="center">
5
+ <sup>get-tsconfig</sup>
6
+ <br>
7
+ <a href="https://npm.im/get-tsconfig"><img src="https://badgen.net/npm/v/get-tsconfig"></a> <a href="https://npm.im/get-tsconfig"><img src="https://badgen.net/npm/dm/get-tsconfig"></a>
8
+ </h1>
9
+
10
+ Find and parse `tsconfig.json` files.
11
+
12
+ ## Features
13
+ - Tiny! `9 kB` Minified + Gzipped
14
+ - Tested against TypeScript for correctness
15
+ - Resolves [`extends`](https://www.typescriptlang.org/tsconfig/#extends)
16
+ - Fully typed `tsconfig.json`
17
+ - Validates and throws parsing errors
18
+
19
+ <br>
20
+
21
+ <p align="center">
22
+ <a href="https://github.com/sponsors/privatenumber/sponsorships?tier_id=398771"><img width="412" src="https://raw.githubusercontent.com/privatenumber/sponsors/master/banners/assets/donate.webp"></a>
23
+ <a href="https://github.com/sponsors/privatenumber/sponsorships?tier_id=397608"><img width="412" src="https://raw.githubusercontent.com/privatenumber/sponsors/master/banners/assets/sponsor.webp"></a>
24
+ </p>
25
+ <p align="center"><sup><i>Already a sponsor?</i> Join the discussion in the <a href="https://github.com/pvtnbr/get-tsconfig">Development repo</a>!</sup></p>
26
+
27
+ ## Install
28
+
29
+ ```bash
30
+ npm install get-tsconfig
31
+ ```
32
+
33
+ ## Why?
34
+
35
+ TypeScript tooling (bundlers, linters, loaders, test runners) needs to read `tsconfig.json` to understand compiler options, path aliases, and file inclusion rules. But TypeScript's own config parser is buried inside the compiler and requires TypeScript as a dependency.
36
+
37
+ `get-tsconfig` provides the same functionality as a lightweight, standalone library — tested against TypeScript for correctness.
38
+
39
+ ## Quick start
40
+
41
+ ```ts
42
+ import { getTsconfig, isFileIncluded, resolvePathAlias } from 'get-tsconfig'
43
+
44
+ // Find and parse the nearest tsconfig.json
45
+ const tsconfig = getTsconfig()
46
+
47
+ // To resolve path aliases (compilerOptions.paths):
48
+ if (tsconfig) {
49
+ const resolved = resolvePathAlias(tsconfig, '@/utils/helper')
50
+ // → ['/project/src/utils/helper']
51
+ }
52
+
53
+ // To check if a file belongs to this tsconfig:
54
+ if (tsconfig && isFileIncluded(tsconfig, '/project/src/index.ts')) {
55
+ // Use tsconfig.config.compilerOptions for transformation
56
+ }
57
+ ```
58
+
59
+ ## Finding & reading tsconfig
60
+
61
+ These functions find, read, and parse tsconfig files from the filesystem. All return a `TsconfigResult`:
62
+
63
+ ```ts
64
+ type TsconfigResult<Config = TsconfigJsonResolved> = {
65
+ path: string
66
+ config: Config
67
+ sources: string[]
68
+ }
69
+ ```
70
+
71
+ - **path**: absolute path to the tsconfig file
72
+ - **config**: the fully resolved config (extends merged, options normalized)
73
+ - **sources**: paths of all tsconfig files that contributed to the resolved config via [`extends`](https://www.typescriptlang.org/tsconfig/#extends). When there are no `extends`, this is just `[path]`. Since `extends` can be an array, the order does not imply a linear chain.
74
+
75
+ ### getTsconfig(searchPath?, options?)
76
+
77
+ Searches for a tsconfig file and parses it. If you already know the path, use [`readTsconfig`](#readtsconfigtsconfigpath-options) instead. Returns `undefined` if not found.
78
+
79
+ #### searchPath
80
+ Type: `string`
81
+
82
+ Default: `process.cwd()`
83
+
84
+ Path to a file or directory. The directory tree is searched up for `tsconfig.json`.
85
+
86
+ #### options
87
+ Type: `GetTsconfigOptions`
88
+
89
+ ```ts
90
+ type GetTsconfigOptions = {
91
+ configName?: string // default: 'tsconfig.json'
92
+ cache?: Map<string, unknown>
93
+ includes?: boolean // default: false
94
+ typescriptVersion?: 'auto' | string | false // default: 'auto'
95
+ }
96
+ ```
97
+
98
+ - **configName**: file name to search for (e.g. `'jsconfig.json'`)
99
+ - **cache**: snapshot cache for fs operations. Reusing after filesystem changes can return stale results.
100
+ - **includes**: when `true`, validates the file is a root file (matched by `include`/`files` globs, not excluded) before accepting the tsconfig. Matches VS Code's Language Server behavior. Default matches `tsc` CLI behavior (nearest tsconfig). Note: this checks glob matching only — a file can still be part of a TypeScript program via transitive imports even if not matched by `include`.
101
+ - **typescriptVersion**: applies unconditional compiler-option defaults from the target TypeScript version. Default `'auto'` detects the installed version; pass an explicit version string to pin, or `false` to disable. See [TypeScript version-aware defaults](#typescript-version-aware-defaults).
102
+
103
+ #### Example
104
+
105
+ ```ts
106
+ import { getTsconfig } from 'get-tsconfig'
107
+
108
+ // Find from current directory
109
+ getTsconfig()
110
+
111
+ // Find from a file path
112
+ getTsconfig('./src/index.ts')
113
+
114
+ // Search for jsconfig.json
115
+ getTsconfig('.', { configName: 'jsconfig.json' })
116
+
117
+ // Language Server behavior — validate the file is included
118
+ getTsconfig('./src/index.ts', { includes: true })
119
+ ```
120
+
121
+ ### findTsconfig(searchPath?, options?)
122
+
123
+ Like `getTsconfig`, but returns only the path (`string | undefined`) without parsing. Same options.
124
+
125
+ ```ts
126
+ import { findTsconfig } from 'get-tsconfig'
127
+
128
+ findTsconfig() // → '/project/tsconfig.json'
129
+ ```
130
+
131
+ ### readTsconfig(tsconfigPath, options?)
132
+
133
+ Reads and resolves a tsconfig at a known path. Used internally by `getTsconfig`.
134
+
135
+ ```ts
136
+ type ReadTsconfigOptions = {
137
+ cache?: Map<string, unknown>
138
+ typescriptVersion?: 'auto' | string | false // default: 'auto'
139
+ }
140
+ ```
141
+
142
+ - **typescriptVersion**: applies unconditional compiler-option defaults from the target TypeScript version. Default `'auto'` detects the installed version; pass an explicit version string to pin, or `false` to disable. See [TypeScript version-aware defaults](#typescript-version-aware-defaults).
143
+
144
+ ```ts
145
+ import { readTsconfig } from 'get-tsconfig'
146
+
147
+ const { path, config } = readTsconfig('./tsconfig.json')
148
+ ```
149
+
150
+ ## Tsconfig `extends`
151
+
152
+ `readTsconfig` and `getTsconfig` fully resolve the [`extends`](https://www.typescriptlang.org/tsconfig/#extends) chain and return a flattened config. These two functions expose the chain for use cases like watch mode and config auditing.
153
+
154
+ ### getExtendsChain(tsconfigPath, options?)
155
+
156
+ Collects the full extends chain. Returns an array of `TsconfigResult<TsconfigJson>` entries — each containing the raw (unmerged) config with `extends` resolved to absolute paths. (`TsconfigJson` is the raw tsconfig.json shape, including the `extends` field.)
157
+
158
+ `chain[0]` is the root. Ancestors follow in resolution order.
159
+
160
+ ```ts
161
+ type GetExtendsChainOptions = {
162
+ cache?: Map<string, unknown>
163
+ }
164
+ ```
165
+
166
+ ```ts
167
+ import { getExtendsChain } from 'get-tsconfig'
168
+
169
+ const chain = getExtendsChain('./tsconfig.json')
170
+ // [
171
+ // { path: '/project/tsconfig.json', config: { extends: '/project/base.json', ... } },
172
+ // { path: '/project/base.json', config: { ... } },
173
+ // ]
174
+
175
+ // Watch all files in the extends chain
176
+ const filesToWatch = chain.map(entry => entry.path)
177
+ ```
178
+
179
+ ### resolveExtendsChain(chain)
180
+
181
+ Merges a collected extends chain into a resolved tsconfig. Pure function — no filesystem access.
182
+
183
+ ```ts
184
+ import { getExtendsChain, resolveExtendsChain } from 'get-tsconfig'
185
+
186
+ const chain = getExtendsChain('./tsconfig.json')
187
+
188
+ // Modify before merging
189
+ chain[0].config.compilerOptions = {
190
+ ...chain[0].config.compilerOptions,
191
+ sourceMap: true
192
+ }
193
+
194
+ const result = resolveExtendsChain(chain)
195
+ // TsconfigResult { path, config, sources }
196
+ ```
197
+
198
+ ## Working with a tsconfig
199
+
200
+ These functions take a parsed `TsconfigResult` (from `getTsconfig` or `readTsconfig`) and answer questions about it. They cache compiled state per tsconfig object — do not mutate the tsconfig after the first call.
201
+
202
+ ### isFileIncluded(tsconfig, filePath)
203
+
204
+ Checks whether an absolute file path matches a tsconfig's `files`, `include`, and `exclude` globs — i.e., whether it's a **root file**. Case sensitivity is auto-detected from the filesystem. Non-absolute paths return `false`.
205
+
206
+ > [!NOTE]
207
+ > This checks glob matching only, not transitive imports. A file outside `include` can still be part of the TypeScript program if it's imported by a root file. `exclude` only filters the initial glob matching — it doesn't prevent transitively imported files from being compiled.
208
+
209
+ ```ts
210
+ import { getTsconfig, isFileIncluded } from 'get-tsconfig'
211
+
212
+ const tsconfig = getTsconfig()
213
+
214
+ if (tsconfig && isFileIncluded(tsconfig, '/path/to/file.ts')) {
215
+ // file is a root file of this tsconfig
216
+ }
217
+ ```
218
+
219
+ ### resolvePathAlias(tsconfig, specifier)
220
+
221
+ Resolves an [import specifier](https://nodejs.org/api/esm.html#terminology) against [`compilerOptions.paths`](https://www.typescriptlang.org/tsconfig#paths). Returns an array of possible file paths, or an empty array if no match. Does not perform actual file resolution.
222
+
223
+ ```ts
224
+ import { getTsconfig, resolvePathAlias } from 'get-tsconfig'
225
+
226
+ const tsconfig = getTsconfig()
227
+
228
+ const tryPaths = tsconfig && resolvePathAlias(tsconfig, '@/utils/helper')
229
+ if (tryPaths?.length) {
230
+ // Check if paths in tryPaths exist
231
+ }
232
+ ```
233
+
234
+ ## TypeScript version-aware defaults
235
+
236
+ TypeScript synthesizes some compiler options when the user doesn't set them — and the synthesized values change between versions. For example, TS 6.0 defaults `moduleResolution` to `'bundler'` and `strict` to `true`, while TS 5.x leaves them unset.
237
+
238
+ By default, `get-tsconfig` mirrors what TypeScript itself would compute by detecting the installed TypeScript version near the tsconfig file:
239
+
240
+ ```ts
241
+ import { readTsconfig } from 'get-tsconfig'
242
+
243
+ // Default: auto-detect TypeScript via node_modules walk-up
244
+ // (or the Yarn Berry pnp API when available). If TS is found, its
245
+ // version-aware defaults are applied. If not, no defaults are added.
246
+ readTsconfig('./tsconfig.json')
247
+
248
+ // Pin a specific version explicitly
249
+ readTsconfig('./tsconfig.json', { typescriptVersion: '6.0.0' })
250
+
251
+ // Opt out — return only what's literally in the file (plus internal
252
+ // derivations like `strict: true` ⇒ strict-family flags)
253
+ readTsconfig('./tsconfig.json', { typescriptVersion: false })
254
+ ```
255
+
256
+ > [!IMPORTANT]
257
+ > Auto-detection means the parsed config can vary with the runtime environment. If you publish a library that runs both at dev time (with TypeScript installed) and in production (without it), pass an explicit version string or `false` for deterministic output.
258
+
259
+ The defaults are tracked per-major (v4, v5, v6) and applied cumulatively. Source-of-truth references for each default live in [`src/version-defaults/`](./src/version-defaults).
260
+
261
+ ## FAQ
262
+
263
+ ### How can I use TypeScript to parse `tsconfig.json`?
264
+ This package is a re-implementation of TypeScript's `tsconfig.json` parser.
265
+
266
+ However, if you already have TypeScript as a dependency, you can simply use it's API:
267
+
268
+ ```ts
269
+ import {
270
+ sys as tsSys,
271
+ findConfigFile,
272
+ readConfigFile,
273
+ parseJsonConfigFileContent
274
+ } from 'typescript'
275
+
276
+ // Find tsconfig.json file
277
+ const tsconfigPath = findConfigFile(process.cwd(), tsSys.fileExists, 'tsconfig.json')
278
+
279
+ // Read tsconfig.json file
280
+ const tsconfigFile = readConfigFile(tsconfigPath, tsSys.readFile)
281
+
282
+ // Resolve extends
283
+ const parsedTsconfig = parseJsonConfigFileContent(
284
+ tsconfigFile.config,
285
+ tsSys,
286
+ path.dirname(tsconfigPath)
287
+ )
288
+ ```
289
+
290
+ ## Sponsors
291
+ <p align="center">
292
+ <a href="https://github.com/sponsors/privatenumber">
293
+ <img src="https://cdn.jsdelivr.net/gh/privatenumber/sponsors/sponsorkit/sponsors.svg">
294
+ </a>
295
+ </p>
node_modules/get-tsconfig/package.json ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name": "get-tsconfig",
3
+ "version": "5.0.0-beta.5",
4
+ "description": "Find and parse the tsconfig.json file from a directory path",
5
+ "keywords": [
6
+ "get-tsconfig",
7
+ "get",
8
+ "typescript",
9
+ "tsconfig",
10
+ "tsconfig.json"
11
+ ],
12
+ "license": "MIT",
13
+ "repository": "privatenumber/get-tsconfig",
14
+ "funding": "https://github.com/privatenumber/get-tsconfig?sponsor=1",
15
+ "author": {
16
+ "name": "Hiroki Osame",
17
+ "email": "hiroki.osame@gmail.com"
18
+ },
19
+ "files": [
20
+ "dist",
21
+ "skills"
22
+ ],
23
+ "sideEffects": false,
24
+ "type": "module",
25
+ "main": "./dist/index.mjs",
26
+ "types": "./dist/index.d.mts",
27
+ "exports": {
28
+ "types": "./dist/index.d.mts",
29
+ "default": "./dist/index.mjs"
30
+ },
31
+ "imports": {
32
+ "#get-tsconfig": {
33
+ "types": "./src/index.ts",
34
+ "development": "./src/index.ts",
35
+ "default": "./dist/index.mjs"
36
+ }
37
+ },
38
+ "engines": {
39
+ "node": ">=20.20.0"
40
+ },
41
+ "dependencies": {
42
+ "resolve-pkg-maps": "^1.0.0"
43
+ }
44
+ }
node_modules/get-tsconfig/skills/get-tsconfig/MIGRATION.md ADDED
@@ -0,0 +1,194 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ name: get-tsconfig-migration
3
+ description: Step-by-step guide for migrating from get-tsconfig v4 to v5. Use when upgrading the dependency, when seeing errors after the upgrade (e.g. parseTsconfig is not a function, TsConfigResult type missing, require() failing), or when adapting code that used createFilesMatcher / createPathsMatcher / parseTsconfig.
4
+ ---
5
+
6
+ # Migrating from get-tsconfig v4 to v5
7
+
8
+ v5 is ESM-only, requires Node 20+, renames most APIs, and applies TypeScript-version-aware defaults to compiler options by default. The renames are mechanical; the behaviour change is silent — code keeps running but parsed configs now include synthesized fields that v4 left `undefined`.
9
+
10
+ > [!IMPORTANT]
11
+ > **The biggest gotcha is the new default behaviour.** If your code branches on `compilerOptions.X === undefined` to mean "the user didn't set X," that check now fails — v5 fills X with the installed TypeScript's default (e.g. `moduleResolution: 'bundler'` for TS 6). Pass `typescriptVersion: false` to opt out. See [TypeScript-version-aware defaults](#typescript-version-aware-defaults).
12
+
13
+ ## Environment
14
+
15
+ | Concern | v4 | v5 |
16
+ |---|---|---|
17
+ | Node | `>=12.20` | `>=20.20` |
18
+ | Module format | CJS + ESM dual build | **ESM only** — `require('get-tsconfig')` no longer works |
19
+
20
+ Stay on `get-tsconfig@4` if you can't move to ESM or upgrade Node.
21
+
22
+ ## API renames
23
+
24
+ ```ts
25
+ // v4
26
+ import {
27
+ parseTsconfig,
28
+ createFilesMatcher,
29
+ createPathsMatcher,
30
+ type TsConfigResult,
31
+ } from 'get-tsconfig'
32
+
33
+ const config = parseTsconfig('./tsconfig.json')
34
+ const filesMatcher = createFilesMatcher({ path, config })
35
+ const pathsMatcher = createPathsMatcher({ path, config })
36
+
37
+ if (filesMatcher(filePath)) { /* ... */ }
38
+ const candidates = pathsMatcher?.('@/foo')
39
+ ```
40
+
41
+ ```ts
42
+ // v5
43
+ import {
44
+ readTsconfig,
45
+ isFileIncluded,
46
+ resolvePathAlias,
47
+ type TsconfigResult,
48
+ } from 'get-tsconfig'
49
+
50
+ const result = readTsconfig('./tsconfig.json')
51
+ if (isFileIncluded(result, filePath)) { /* ... */ }
52
+ const candidates = resolvePathAlias(result, '@/foo')
53
+ ```
54
+
55
+ `createFilesMatcher` / `createPathsMatcher` were factories returning a closure. `isFileIncluded` / `resolvePathAlias` are direct calls — no factory step.
56
+
57
+ ## Signature changes (positional → options)
58
+
59
+ ```ts
60
+ // v4
61
+ getTsconfig(searchPath, configName, cache, includes)
62
+ findTsconfig(searchPath, configName, cache)
63
+ parseTsconfig(path, cache)
64
+
65
+ // v5
66
+ getTsconfig(searchPath, { configName, cache, includes, typescriptVersion })
67
+ findTsconfig(searchPath, { configName, cache, includes })
68
+ readTsconfig(path, { cache, typescriptVersion })
69
+ ```
70
+
71
+ ## Return-value changes
72
+
73
+ ### `getTsconfig`: `null` → `undefined`
74
+
75
+ Replace `=== null` checks. (`findTsconfig` already returned `string | undefined` in v4 — unchanged.)
76
+
77
+ ### `parseTsconfig` raw config → `readTsconfig` wrapper
78
+
79
+ ```ts
80
+ // v4 — returned the resolved compilerOptions directly
81
+ const compilerOptions = parseTsconfig('./tsconfig.json').compilerOptions
82
+
83
+ // v5 — returns TsconfigResult { path, config, sources }
84
+ const compilerOptions = readTsconfig('./tsconfig.json').config.compilerOptions
85
+ ```
86
+
87
+ ### Matcher return shapes
88
+
89
+ | API | v4 return when "no match" | v5 return |
90
+ |---|---|---|
91
+ | `createFilesMatcher(t)(p)` | `undefined` (matched: returned the config) | `isFileIncluded(t, p)` → `boolean` |
92
+ | `createPathsMatcher(t)` | `null` if no `paths`/`baseUrl` | `resolvePathAlias(t, s)` → `string[]` (empty if no aliases) |
93
+
94
+ If you read the matched config out of `createFilesMatcher`'s return value, switch to reading from the `TsconfigResult` you already have:
95
+
96
+ ```ts
97
+ // v4
98
+ const matched = filesMatcher(filePath)
99
+ if (matched) use(matched.compilerOptions)
100
+
101
+ // v5
102
+ if (isFileIncluded(tsconfig, filePath)) use(tsconfig.config.compilerOptions)
103
+ ```
104
+
105
+ Other behaviour changes worth flagging:
106
+
107
+ - **Non-absolute paths.** v4 `createFilesMatcher(t)(relativePath)` **threw** `'filePath must be absolute'`; v5 `isFileIncluded` returns `false` silently. Replace any `try/catch` around the call with an explicit `path.isAbsolute(...)` check.
108
+ - **`caseSensitivePaths` is gone.** `createFilesMatcher(t, false)` had no v5 equivalent — sensitivity is auto-detected via `is-fs-case-sensitive`. If you forced a value for cross-platform tests, handle that at the test layer.
109
+
110
+ ## Type renames and removals
111
+
112
+ | v4 | v5 |
113
+ |---|---|
114
+ | `TsConfigResult` | `TsconfigResult` |
115
+ | `TsConfigJson` | `TsconfigJson` |
116
+ | `TsConfigJsonResolved` | `TsconfigJsonResolved` |
117
+ | `Cache` | `TsconfigCache` |
118
+
119
+ Removed (no replacement — the matcher factories they typed are gone):
120
+
121
+ - **`PathsMatcher`** — was the function type returned by `createPathsMatcher`.
122
+ - **`FileMatcher`** — was the function type returned by `createFilesMatcher`.
123
+
124
+ If you imported either to annotate a variable, just delete the import.
125
+
126
+ ## TypeScript-version-aware defaults
127
+
128
+ v5 detects the installed TypeScript version (default: `'auto'`) and applies its unconditional defaults. Parsed configs now include synthesized fields like `moduleResolution: 'bundler'` (TS 6) or `target: 'es5'` (TS 5) where v4 would have left them `undefined`.
129
+
130
+ ```ts
131
+ // v4
132
+ parseTsconfig('./tsconfig.json').compilerOptions
133
+ // {}
134
+
135
+ // v5 — defaults applied (if TS is installed)
136
+ readTsconfig('./tsconfig.json').config.compilerOptions
137
+ // { strict: true, target: 'es2025', moduleResolution: 'bundler', ... }
138
+
139
+ // v5 with v4 behaviour preserved
140
+ readTsconfig('./tsconfig.json', { typescriptVersion: false }).config.compilerOptions
141
+ // {}
142
+ ```
143
+
144
+ **Pass `typescriptVersion: false`** if any of the following apply:
145
+
146
+ - Your code branches on `compilerOptions.X === undefined` to mean "the user didn't set X."
147
+ - You ship library code that runs both at dev time (with TypeScript installed) and in production (without it). Auto-detection returns `undefined` when TS is missing — output drifts between environments. `false` makes it deterministic.
148
+ - You want byte-for-byte parity with v4 output.
149
+
150
+ You can also pin a specific version: `{ typescriptVersion: '6.0.0' }`.
151
+
152
+ ## Additive APIs in v5 (no migration needed)
153
+
154
+ - **`getExtendsChain(path, options)`** — raw extends chain before merging. Useful for watch mode (`chain.map(e => e.path)`) or modifying configs before merge.
155
+ - **`resolveExtendsChain(chain, options)`** — pure merge function over a chain. No filesystem.
156
+ - **`TsconfigResult.sources`** — paths of every file in the resolved extends chain.
157
+ - **`typescriptVersion` option** — opt out with `false` for v4-style raw output, or pin a specific version string.
158
+
159
+ ## Quick search-and-replace
160
+
161
+ ```sh
162
+ # Macro renames (review the diff afterwards — these may overshoot in comments/strings)
163
+ sed -i '' '
164
+ s/parseTsconfig/readTsconfig/g
165
+ s/createFilesMatcher/isFileIncluded/g
166
+ s/createPathsMatcher/resolvePathAlias/g
167
+ s/TsConfig/Tsconfig/g
168
+ s/\([^A-Za-z0-9_]\)Cache\b/\1TsconfigCache/g
169
+ '
170
+ ```
171
+
172
+ The `Cache` substitution uses a word-boundary lookbehind to avoid mangling identifiers like `cacheMap` or `MyCache`. Review the diff and revert any false positives.
173
+
174
+ Then manually:
175
+
176
+ 1. **Rewrite call sites.** `createFilesMatcher(t)(filePath)` → `isFileIncluded(t, filePath)`. Same for `createPathsMatcher(t)?.(spec)` → `resolvePathAlias(t, spec)`.
177
+ 2. **Convert positional args to options objects** for `getTsconfig` / `findTsconfig` / `readTsconfig`.
178
+ 3. **Replace `=== null`** with `=== undefined` (or `!result`) for `getTsconfig` returns.
179
+ 4. **Update `parseTsconfig` consumers** to access the `.config` property on the result of `readTsconfig`.
180
+ 5. **Decide on `typescriptVersion`.** Default `'auto'` matches what `tsc` would compute. Pass `false` if you ship to TS-less runtimes or rely on `=== undefined` checks.
181
+
182
+ ## Common errors after upgrading
183
+
184
+ | Error | Cause | Fix |
185
+ |---|---|---|
186
+ | `Engine "node" is incompatible` | Bumped to Node 20+ | Upgrade Node, or pin `get-tsconfig@4` |
187
+ | `require('get-tsconfig')` throws `ERR_REQUIRE_ESM` | CJS dropped | Convert consumer to ESM, or pin `get-tsconfig@4` |
188
+ | `TypeError: parseTsconfig is not a function` | Renamed | `parseTsconfig(p)` → `readTsconfig(p).config` |
189
+ | `TypeError: createFilesMatcher is not a function` | Renamed + de-curried | `createFilesMatcher(t)(p)` → `isFileIncluded(t, p)` |
190
+ | `TypeError: createPathsMatcher is not a function` | Renamed + de-curried | `createPathsMatcher(t)?.(s)` → `resolvePathAlias(t, s)` |
191
+ | `Cannot find name 'TsConfigResult'` | Type renamed | `TsConfigResult` → `TsconfigResult` |
192
+ | `Cannot find name 'Cache'` | Type renamed | `Cache` → `TsconfigCache` |
193
+ | `Cannot find name 'PathsMatcher'` or `'FileMatcher'` | Type removed | Delete the import — no replacement |
194
+ | Test snapshots fail with new fields like `moduleResolution: 'bundler'` | Version-aware defaults now applied | Update snapshots, or pass `typescriptVersion: false` to restore v4 output |
node_modules/get-tsconfig/skills/get-tsconfig/SKILL.md ADDED
@@ -0,0 +1,170 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ name: get-tsconfig
3
+ description: Find, parse, and query tsconfig.json files — extends resolution, file matching, path alias resolution. Use when reading tsconfig.json, checking if a file belongs to a tsconfig, resolving TypeScript path aliases, or working with tsconfig extends chains.
4
+ ---
5
+
6
+ # get-tsconfig
7
+
8
+ Lightweight tsconfig.json parser. No TypeScript dependency. Tested against `tsc` for correctness.
9
+
10
+ > [!NOTE]
11
+ > Upgrading from v4? See [MIGRATION.md](./MIGRATION.md) for the API renames, the ESM-only / Node 20+ requirements, and the new version-aware-defaults behaviour.
12
+
13
+ ## API
14
+
15
+ | Function | Purpose | Returns |
16
+ |----------|---------|---------|
17
+ | `getTsconfig(searchPath?, options?)` | Find + parse nearest tsconfig | `TsconfigResult \| undefined` |
18
+ | `findTsconfig(searchPath?, options?)` | Find nearest tsconfig path only | `string \| undefined` |
19
+ | `readTsconfig(path, options?)` | Parse tsconfig at known path | `TsconfigResult` |
20
+ | `isFileIncluded(tsconfig, filePath)` | Check if file is a root file (matches include/exclude/files globs) | `boolean` |
21
+ | `resolvePathAlias(tsconfig, specifier)` | Resolve `compilerOptions.paths` alias | `string[]` |
22
+ | `getExtendsChain(path, options?)` | Get raw extends chain before merging | `TsconfigResult<TsconfigJson>[]` |
23
+ | `resolveExtendsChain(chain)` | Merge a collected chain (pure, no fs) | `TsconfigResult` |
24
+
25
+ ## Types
26
+
27
+ ```ts
28
+ type TsconfigResult<Config = TsconfigJsonResolved> = {
29
+ path: string
30
+ config: Config
31
+ }
32
+
33
+ // TsconfigJson = raw tsconfig shape (includes extends field)
34
+ // TsconfigJsonResolved = TsconfigJson without extends (fully merged)
35
+
36
+ type GetTsconfigOptions = {
37
+ configName?: string // default: 'tsconfig.json' (use 'jsconfig.json' for JS projects)
38
+ cache?: Map<string, unknown>
39
+ includes?: boolean // default: false — when true, validates file is a root file before accepting
40
+ typescriptVersion?: 'auto' | string | false // default: 'auto' — see Use cases
41
+ }
42
+
43
+ type ReadTsconfigOptions = {
44
+ cache?: Map<string, unknown>
45
+ typescriptVersion?: 'auto' | string | false // default: 'auto'
46
+ }
47
+ ```
48
+
49
+ ## Use cases
50
+
51
+ ### Build tool / loader integration
52
+
53
+ ```ts
54
+ import { getTsconfig, isFileIncluded, resolvePathAlias } from 'get-tsconfig'
55
+
56
+ const tsconfig = getTsconfig()
57
+
58
+ // Check if a file should be transformed with this tsconfig's options
59
+ if (tsconfig && isFileIncluded(tsconfig, absoluteFilePath)) {
60
+ const { compilerOptions } = tsconfig.config
61
+ // Pass to esbuild, SWC, etc. as tsconfigRaw
62
+ }
63
+
64
+ // Resolve path aliases (returns candidate paths — check which exist)
65
+ const resolved = tsconfig && resolvePathAlias(tsconfig, '@/utils/helper')
66
+ // → ['/project/src/utils/helper'] or []
67
+ ```
68
+
69
+ ### Monorepo — per-file tsconfig lookup
70
+
71
+ The nearest tsconfig typically applies. Use `getTsconfig` with the file path — it walks up and finds the right one:
72
+
73
+ ```ts
74
+ const cache = new Map()
75
+
76
+ const getConfigForFile = (filePath: string) =>
77
+ getTsconfig(filePath, { cache })
78
+ ```
79
+
80
+ Cache deduplicates filesystem reads across calls. Create a new `Map()` to invalidate after filesystem changes.
81
+
82
+ ### Implied compiler options
83
+
84
+ Implied options are already normalized — no need to check parent flags:
85
+
86
+ ```ts
87
+ const { compilerOptions } = getTsconfig().config
88
+
89
+ compilerOptions.noImplicitAny // true (implied by strict: true)
90
+ compilerOptions.strictNullChecks // true (implied by strict: true)
91
+ compilerOptions.esModuleInterop // true (implied by module: 'nodenext')
92
+ compilerOptions.allowJs // true (implied by checkJs: true)
93
+ ```
94
+
95
+ Options not set and not implied remain `undefined` (not `false`). Use `?? false` for boolean checks.
96
+
97
+ ### Watch mode — extends chain files
98
+
99
+ ```ts
100
+ import { getExtendsChain } from 'get-tsconfig'
101
+
102
+ const chain = getExtendsChain('./tsconfig.json')
103
+ const filesToWatch = chain.map(entry => entry.path)
104
+ ```
105
+
106
+ ### Modify config before merging
107
+
108
+ ```ts
109
+ import { getExtendsChain, resolveExtendsChain } from 'get-tsconfig'
110
+
111
+ const chain = getExtendsChain('./tsconfig.json')
112
+ chain[0].config.compilerOptions = {
113
+ ...chain[0].config.compilerOptions,
114
+ sourceMap: true,
115
+ }
116
+ const result = resolveExtendsChain(chain)
117
+ ```
118
+
119
+ ### Language Server behavior
120
+
121
+ ```ts
122
+ // Default: nearest tsconfig (tsc CLI behavior)
123
+ getTsconfig('./src/index.ts')
124
+
125
+ // Validates file is a root file before accepting (VS Code behavior)
126
+ getTsconfig('./src/index.ts', { includes: true })
127
+ ```
128
+
129
+ ### TypeScript version-aware defaults
130
+
131
+ The parser auto-detects the installed TypeScript version and applies its unconditional defaults (e.g. TS 6.0 sets `moduleResolution: 'bundler'`, `strict: true`). This is the default behavior — the parsed config matches what `tsc` would compute.
132
+
133
+ ```ts
134
+ // Default — auto-detects via node_modules walk-up (or Yarn pnp)
135
+ readTsconfig('./tsconfig.json')
136
+
137
+ // Pin a specific version (deterministic across environments)
138
+ readTsconfig('./tsconfig.json', { typescriptVersion: '6.0.0' })
139
+
140
+ // Disable — return only the literal config + within-config derivations
141
+ readTsconfig('./tsconfig.json', { typescriptVersion: false })
142
+ ```
143
+
144
+ **When to pass `false`:** library code that runs in environments where TypeScript may not be installed (production runtimes, trimmed Docker images). Auto-detection there would return `undefined` and behave inconsistently with dev. Passing `false` makes output deterministic.
145
+
146
+ Per-major changes are tracked in `src/version-defaults/{v4,v5,v6}.ts` with links to the corresponding TypeScript source.
147
+
148
+ ## Understanding `isFileIncluded`
149
+
150
+ Checks whether a file matches `include`/`exclude`/`files` globs — whether it's a **root file**. This is NOT the same as "is this file part of the TypeScript program."
151
+
152
+ | Source | What it adds | Checked by `isFileIncluded`? |
153
+ |--------|-------------|-------------------------------|
154
+ | `include`/`files` globs | Root files | **Yes** |
155
+ | Transitive imports | Files imported by root files (recursive) | No |
156
+ | `@types` packages | Auto-discovered from `node_modules/@types/` | No |
157
+ | Triple-slash directives | `/// <reference path="..." />` | No |
158
+
159
+ - **`exclude` only filters glob matching** — if a root file imports an excluded file, that file is still in the program.
160
+ - **`isFileIncluded` returning `false` doesn't mean the file won't be compiled** — it may be pulled in via imports.
161
+ - For finding the nearest tsconfig regardless of glob matching, use `getTsconfig(filePath)` without `includes`.
162
+
163
+ ## Gotchas
164
+
165
+ | Issue | Detail |
166
+ |-------|--------|
167
+ | Immutable tsconfig objects | `isFileIncluded` and `resolvePathAlias` cache per object identity. Do not mutate after first call. |
168
+ | `extends` must be resolved | `isFileIncluded` throws if `config.extends` is present. Use `getTsconfig`/`readTsconfig` output. |
169
+ | `resolvePathAlias` returns candidates | Returns paths from `compilerOptions.paths`, not verified files. Check existence yourself. |
170
+ | `getExtendsChain` resolves extends | The `extends` field in each entry is an absolute path, not the original string. |
node_modules/gifwrap/.jshintrc ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ {
2
+ "esversion": 6,
3
+ "node": true
4
+ }
node_modules/gifwrap/LICENSE ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ MIT License
2
+
3
+ Copyright © 2017 Joseph T. Lapp
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
node_modules/gifwrap/README.md ADDED
@@ -0,0 +1,668 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # gifwrap
2
+
3
+ A Jimp-compatible library for working with GIFs
4
+
5
+ ## Overview
6
+
7
+ `gifwrap` is a minimalist library for working with GIFs in Javascript, supporting both single- and multi-frame GIFs. It reads GIFs into an internal representation that's easy to work with and allows for making GIFs from scratch. The frame class is structured to make it easy to move images between [`Jimp`](https://github.com/oliver-moran/jimp) and `gifwrap` for more sophisticated image manipulation in `Jimp`, but the module has no dependency on `Jimp`.
8
+
9
+ The library uses Dean McNamee's [`omggif`](https://github.com/deanm/omggif) GIF encoder/decoder by default, but it employs an abstraction that allows using other encoders and decoders as well, once suitably wrapped.
10
+
11
+ At present, the module only works in Node.js. Includes Typescript typings.
12
+
13
+ ## Installation
14
+
15
+ ```
16
+ npm install gifwrap --save
17
+ ```
18
+
19
+ or
20
+
21
+ ```
22
+ yarn add gifwrap
23
+ ```
24
+
25
+ ## Usage
26
+
27
+ You can work with either GIF files or GIF encodings, and you can create GIFs from scratch.
28
+
29
+ The GifFrame class represents a single image frame, and the library largely represents a GIF as an array of GifFrame instances. For example, here is how you create a GIF from scratch:
30
+
31
+ ```js
32
+ const { GifFrame, GifUtil, GifCodec } = require('gifwrap');
33
+ const width = 200, height = 100;
34
+ const frames = [];
35
+
36
+ let frame = new GifFrame(width, height, { delayCentisecs: 10 });
37
+ // modify the pixels at frame.bitmap.data
38
+ frames.push(frame);
39
+ frame = new GifFrame(width, height, { delayCentisecs: 15 });
40
+ // modify the pixels at frame.bitmap.data
41
+ frames.push(frame);
42
+ // add more frames as desired...
43
+
44
+ // to write to a file...
45
+ GifUtil.write("my-creation.gif", frames, { loops: 3 }).then(gif => {
46
+ console.log("written");
47
+ });
48
+
49
+ // to get the byte encoding without writing to a file...
50
+ const codec = new GifCodec();
51
+ codec.encodeGif(frames, { loops: 3 }).then(gif => {
52
+ // byte encoding is now in gif.buffer
53
+ });
54
+
55
+ ```
56
+
57
+ Images are represented within a GifFrame exactly as they are in a `Jimp` image. In particular, each GifFrame instance has a `bitmap` property having the following structure:
58
+
59
+ * `frame.bitmap.width` - Width of image in pixels
60
+ * `frame.bitmap.height` - Height of image in pixels
61
+ * `frame.bitmap.data` - A Node.js Buffer that can be accessed like an array of bytes. Every 4 adjacent bytes represents the RGBA values of a single pixel. These 4 bytes correspond to red, green, blue, and alpha, in that order. Each pixel begins at an index that is a multiple of 4.
62
+
63
+ GIFs do not support partial transparency, so within `frame.bitmap.data`, pixels having alpha value 0x00 are treated as transparent and pixels of non-zero alpha value are treated as opaque. The encoder ignores the RGB values of transparent pixels.
64
+
65
+ `gifwrap` also provides utilities for reading GIF files and for parsing raw encodings:
66
+
67
+ ```js
68
+ const { GifUtil } = require('gifwrap');
69
+ GifUtil.read("fancy.gif").then(inputGif => {
70
+
71
+ inputGif.frames.forEach(frame => {
72
+
73
+ const buf = frame.bitmap.data;
74
+ frame.scanAllCoords((x, y, bi) => {
75
+
76
+ // Halve all grays on right half of image.
77
+
78
+ if (x > inputGif.width / 2) {
79
+ const r = buf[bi];
80
+ const g = buf[bi + 1];
81
+ const b = buf[bi + 2];
82
+ const a = buf[bi + 3];
83
+ if (r === g && r === b && a === 0xFF) {
84
+ buf[bi] /= 2;
85
+ buf[bi + 1] /= 2;
86
+ buf[bi + 2] /= 2;
87
+ }
88
+ }
89
+ });
90
+ });
91
+
92
+ // Pass inputGif to write() to preserve the original GIF's specs.
93
+ return GifUtil.write("modified.gif", inputGif.frames, inputGif).then(outputGif => {
94
+ console.log("modified");
95
+ });
96
+ });
97
+ ```
98
+
99
+ ```js
100
+ const { GifUtil, GifCodec } = require('gifwrap');
101
+ const codec = new GifCodec();
102
+ const byteEncodingBuffer = getByteEncodingForSomeGif();
103
+
104
+ codec.decodeGif(byteEncodingBuffer).then(sourceGif => {
105
+
106
+ const edgeLength = Math.min(sourceGif.width, sourceGif.height);
107
+ sourceGif.frames.forEach(frame => {
108
+
109
+ // Make each frame a centered square of size edgeLength x edgeLength.
110
+ // Note that frames may vary in size and that reframe() works even if
111
+ // the frame's image is smaller than the square. Should this happen,
112
+ // the space surrounding the original image will be transparent.
113
+
114
+ const xOffset = (frame.bitmap.width - edgeLength)/2;
115
+ const yOffset = (frame.bitmap.height - edgeLength)/2;
116
+ frame.reframe(xOffset, yOffset, edgeLength, edgeLength);
117
+ });
118
+
119
+ // The encoder determines GIF size from the frames, not the provided spec (sourceGif).
120
+ return GifUtil.write("modified.gif", sourceGif.frames, sourceGif).then(outputGif => {
121
+ console.log("modified");
122
+ });
123
+ });
124
+ ```
125
+
126
+ Notice that both encoding and decoding yields a GIF object. This is an instance of class Gif, and it provides information about the GIF, such as its size and how many times it loops. Notice also that you never call the Gif constructor to create a GIF. Instead, GIFs are created by providing a GifFrame array and a specification of GIF options. That specification is a subset of the properties of a Gif, so you can pass a previously-loaded Gif as a specification when writing or encoding. The encoder only uses the properties that can't be inferred from the frames -- namely, how many times the GIF loops and how to attempt to package the color tables within the encoding.
127
+
128
+ ## Leveraging Jimp
129
+
130
+ This module was originally written as a wrapper around Jimp images -- hence its name -- and then with frames as subclasses of Jimp images. Neither approach worked out well. The final approach requires just a tad of legwork to use `gifwrap` images within Jimp.
131
+
132
+ Both Jimp images and GifFrame instances share the `bitmap` property. By transferring this property back and forth between Jimp images and GifFrame instances, an image can be moved back and forth between the two libraries.
133
+
134
+ You can construct a GifFrame from a Jimp image as follows:
135
+
136
+ ```js
137
+ const { BitmapImage, GifFrame } = require('gifwrap');
138
+ const Jimp = require('jimp');
139
+ const j = new Jimp(200, 100, 0xFFFFFFFF);
140
+
141
+ // create a frame clone of a Jip bitmap
142
+ const fCopied = new GifFrame(new BitmapImage(j.bitmap));
143
+
144
+ // create a frame that shares a bitmap with Jimp (one way)
145
+ const fShared1 = new GifFrame(j.bitmap);
146
+
147
+ // create a frame that shares a bitmap with Jimp (another way)
148
+ const fShared2 = new GifFrame(1, 1, 0); // any GifFrame
149
+ fShared2.bitmap = j.bitmap;
150
+ ```
151
+
152
+ And you can construct a Jimp instance from a GifFrame image as follows:
153
+
154
+ ```js
155
+ const { BitmapImage, GifFrame } = require('gifwrap');
156
+ const Jimp = require('jimp');
157
+ const frame = new GifFrame(200, 100, 0xFFFFFFFF);
158
+
159
+ // create a Jimp containing a clone of the frame bitmap
160
+ jimpCopied = GifUtil.copyAsJimp(Jimp, frame);
161
+
162
+ // create a Jimp that shares a bitmap with the frame
163
+ jimpShared = GifUtil.shareAsJimp(Jimp, frame);
164
+ ```
165
+
166
+ ## Encoders and Decoders
167
+
168
+ `gifwrap` provides a default GIF encoder/decoder, but it is architected to be able to work with other encoders and decoders. The encoder and decoder may even be separate implementations. Encoders and decoders have varying capabilities, performance measures, and levels of reliability.
169
+
170
+ GifCodec is the default implementation, and it's both an encoder and a decoder. It's an adapter that wraps the [`omggif`](https://github.com/deanm/omggif) module. `omggif` appears to support a broad variety of GIFs, although it cannot produce an interlaced encoding (which there is little need for anyway). Although `omggif` doesn't include a test suite at present, `gifwrap`'s test suite happens to test it reasonably well by virtue of using `omggif` underneath.
171
+
172
+ An encoder need only implement GifCodec's [`encodeGif()`](#GifCodec+encodeGif) method, and a decoder need only implement its [`decodeGif()`](#GifCodec+decodeGif) method. See the descriptions of those methods for the requirement details. Although GifCodec is stateless, so that instances an be reused across multiple encodings and decodings, third party encoders and decoders need not be. However, applications that use the library with stateful encoders will need to be aware of the need to create new instances.
173
+
174
+ To use a third-party encoder or decoder with the GifUtil `write()` and `read()` functions, just pass an instance of the encoder or decoder as the last parameter to `write()` or `read()`, respectively. For example:
175
+
176
+ ```js
177
+ const { GifUtil } = require('gifwrap');
178
+ const SnazzyDecoder = require('gifwrap-snazzy-decoder');
179
+ const AwesomeEncoder = require('gifwrap-awesome-encoder');
180
+
181
+ GifUtil.read("fancy.gif", new SnazzyDecoder()).then(gif =>
182
+
183
+ /*...*/
184
+
185
+ return GifUtil.write("modified.gif", gif.frames, gif, new AwesomeEncoder()).then(newGif => {
186
+ console.log("modified");
187
+ });
188
+ });
189
+ ```
190
+
191
+ ## API Reference
192
+
193
+ The [Typescript typings](https://github.com/jtlapp/gifwrap/blob/master/index.d.ts) provide an exact specification of the API and also serve as a cheat sheet. The classes and namespaces follow:
194
+
195
+ * **gifwrap**
196
+
197
+ * [.**Gif**](#new_Gif_new)
198
+ * [.**BitmapImage**](#BitmapImage)
199
+ * [.**GifFrame**](#GifFrame)
200
+ * [.**GifUtil**](#GifUtil)
201
+ * [.**GifCodec**](#GifCodec)
202
+ * [.**GifError**](#new_GifError_new)
203
+
204
+
205
+ * [BitmapImage](#BitmapImage)
206
+
207
+ * [new BitmapImage()](#new_BitmapImage_new)
208
+
209
+ * [.blit(toImage, toX, toY, fromX, fromY)](#BitmapImage+blit)
210
+
211
+ * [.fillRGBA(rgba)](#BitmapImage+fillRGBA)
212
+
213
+ * [.getRGBA(x, y)](#BitmapImage+getRGBA)
214
+
215
+ * [.getRGBASet()](#BitmapImage+getRGBASet)
216
+
217
+ * [.greyscale()](#BitmapImage+greyscale)
218
+
219
+ * [.reframe(xOffset, yOffset, width, height, fillRGBA)](#BitmapImage+reframe)
220
+
221
+ * [.scale(factor)](#BitmapImage+scale)
222
+
223
+ * [.scanAllCoords(scanHandler)](#BitmapImage+scanAllCoords)
224
+
225
+ * [.scanAllIndexes(scanHandler)](#BitmapImage+scanAllIndexes)
226
+
227
+
228
+
229
+ * [GifFrame](#GifFrame)
230
+
231
+ * [new GifFrame()](#new_GifFrame_new)
232
+
233
+ * [.getPalette()](#GifFrame+getPalette)
234
+
235
+
236
+
237
+ * [GifUtil](#GifUtil)
238
+
239
+ * [.cloneFrames(frames)](#GifUtil.cloneFrames)
240
+
241
+ * [.getColorInfo(frames, maxGlobalIndex)](#GifUtil.getColorInfo)
242
+
243
+ * [.copyAsJimp(Reference, Instance)](#GifUtil.copyAsJimp)
244
+
245
+ * [.getMaxDimensions(frames)](#GifUtil.getMaxDimensions)
246
+
247
+ * [.quantizeDekker(imageOrImages, maxColorIndexes, dither)](#GifUtil.quantizeDekker)
248
+
249
+ * [.quantizeSorokin(imageOrImages, maxColorIndexes, histogram, dither)](#GifUtil.quantizeSorokin)
250
+
251
+ * [.quantizeWu(imageOrImages, maxColorIndexes, significantBits, dither)](#GifUtil.quantizeWu)
252
+
253
+ * [.read(source, decoder)](#GifUtil.read)
254
+
255
+ * [.shareAsJimp(Reference, Instance)](#GifUtil.shareAsJimp)
256
+
257
+ * [.write(path, frames, spec, encoder)](#GifUtil.write)
258
+
259
+
260
+
261
+ * [GifCodec](#GifCodec)
262
+
263
+ * [new GifCodec(options)](#new_GifCodec_new)
264
+
265
+ * [.decodeGif(buffer)](#GifCodec+decodeGif)
266
+
267
+ * [.encodeGif(frames, spec)](#GifCodec+encodeGif)
268
+
269
+
270
+
271
+ <a name="new_Gif_new"></a>
272
+
273
+ ### new Gif(buffer, frames, spec)
274
+
275
+ | Param | Type | Description |
276
+ | --- | --- | --- |
277
+ | buffer | <code>Buffer</code> | A Buffer containing the encoded bytes |
278
+ | frames | [<code>Array.&lt;GifFrame&gt;</code>](#GifFrame) | Array of frames found in the encoding |
279
+ | spec | <code>object</code> | Properties of the encoding as listed above |
280
+
281
+ Gif is a class representing an encoded GIF. It is intended to be a read-only representation of a byte-encoded GIF. Only encoders and decoders should be creating instances of this class.
282
+
283
+ Property | Description
284
+ --- | ---
285
+ width | width of the GIF at its widest
286
+ height | height of the GIF at its highest
287
+ loops | the number of times the GIF should loop before stopping; 0 => loop indefinitely
288
+ usesTransparency | boolean indicating whether at least one frame contains at least one transparent pixel
289
+ colorScope | the scope of the color tables as encoded within the GIF; either Gif.GlobalColorsOnly (== 1) or Gif.LocalColorsOnly (== 2).
290
+ frames | a array of GifFrame instances, one for each frame of the GIF
291
+ buffer | a Buffer holding the encoding's byte data
292
+
293
+ Its constructor should only ever be called by the GIF encoder or decoder.
294
+
295
+ <a name="new_BitmapImage_new"></a>
296
+
297
+ ### new BitmapImage()
298
+ BitmapImage is a class that hold an RGBA (red, green, blue, alpha) representation of an image. It's shape is borrowed from the Jimp package to make it easy to transfer GIF image frames into Jimp and Jimp images into GIF image frames. Each instance has a `bitmap` property having the following properties:
299
+
300
+ Property | Description
301
+ --- | ---
302
+ bitmap.width | width of image in pixels
303
+ bitmap.height | height of image in pixels
304
+ bitmap.data | a Buffer whose every four bytes represents a pixel, each sequential byte of a pixel corresponding to the red, green, blue, and alpha values of the pixel
305
+
306
+ Its constructor supports the following signatures:
307
+
308
+ * new BitmapImage(bitmap: { width: number, height: number, data: Buffer })
309
+ * new BitmapImage(bitmapImage: BitmapImage)
310
+ * new BitmapImage(width: number, height: number, buffer: Buffer)
311
+ * new BitmapImage(width: number, height: number, backgroundRGBA?: number)
312
+
313
+ When a `BitmapImage` is provided, the constructed `BitmapImage` is a deep clone of the provided one, so that each image's pixel data can subsequently be modified without affecting each other.
314
+
315
+ `backgroundRGBA` is an optional parameter representing a pixel as a single number. In hex, the number is as follows: 0xRRGGBBAA, where RR is the red byte, GG the green byte, BB, the blue byte, and AA the alpha value. An AA of 0x00 is considered transparent, and all non-zero AA values are treated as opaque.
316
+
317
+ <a name="BitmapImage+blit"></a>
318
+
319
+ ### *bitmapImage*.blit(toImage, toX, toY, fromX, fromY)
320
+
321
+ | Param | Type | Description |
322
+ | --- | --- | --- |
323
+ | toImage | [<code>BitmapImage</code>](#BitmapImage) | Image into which to copy the square |
324
+ | toX | <code>number</code> | x-coord in toImage of upper-left corner of receiving square |
325
+ | toY | <code>number</code> | y-coord in toImage of upper-left corner of receiving square |
326
+ | fromX | <code>number</code> | x-coord in this image of upper-left corner of source square |
327
+ | fromY | <code>number</code> | y-coord in this image of upper-left corner of source square |
328
+
329
+ Copy a square portion of this image into another image.
330
+
331
+ **Returns**: [<code>BitmapImage</code>](#BitmapImage) - The present image to allow for chaining.
332
+ <a name="BitmapImage+fillRGBA"></a>
333
+
334
+ ### *bitmapImage*.fillRGBA(rgba)
335
+
336
+ | Param | Type | Description |
337
+ | --- | --- | --- |
338
+ | rgba | <code>number</code> | Color with which to fill image, expressed as a singlenumber in the form 0xRRGGBBAA, where AA is 0x00 for transparent and any other value for opaque. |
339
+
340
+ Fills the image with a single color.
341
+
342
+ **Returns**: [<code>BitmapImage</code>](#BitmapImage) - The present image to allow for chaining.
343
+ <a name="BitmapImage+getRGBA"></a>
344
+
345
+ ### *bitmapImage*.getRGBA(x, y)
346
+
347
+ | Param | Type | Description |
348
+ | --- | --- | --- |
349
+ | x | <code>number</code> | x-coord of pixel |
350
+ | y | <code>number</code> | y-coord of pixel |
351
+
352
+ Gets the RGBA number of the pixel at the given coordinate in the form 0xRRGGBBAA, where AA is the alpha value, with alpha 0x00 encoding to transparency in GIFs.
353
+
354
+ **Returns**: <code>number</code> - RGBA of pixel in 0xRRGGBBAA form
355
+ <a name="BitmapImage+getRGBASet"></a>
356
+
357
+ ### *bitmapImage*.getRGBASet()
358
+ Gets a set of all RGBA colors found within the image.
359
+
360
+ **Returns**: <code>Set</code> - Set of all RGBA colors that the image contains.
361
+ <a name="BitmapImage+greyscale"></a>
362
+
363
+ ### *bitmapImage*.greyscale()
364
+ Converts the image to greyscale using inferred Adobe metrics.
365
+
366
+ **Returns**: [<code>BitmapImage</code>](#BitmapImage) - The present image to allow for chaining.
367
+ <a name="BitmapImage+reframe"></a>
368
+
369
+ ### *bitmapImage*.reframe(xOffset, yOffset, width, height, fillRGBA)
370
+
371
+ | Param | Type | Description |
372
+ | --- | --- | --- |
373
+ | xOffset | <code>number</code> | The x-coord offset of the upper-left pixel of the desired image relative to the present image. |
374
+ | yOffset | <code>number</code> | The y-coord offset of the upper-left pixel of the desired image relative to the present image. |
375
+ | width | <code>number</code> | The width of the new image after reframing |
376
+ | height | <code>number</code> | The height of the new image after reframing |
377
+ | fillRGBA | <code>number</code> | The color with which to fill space added to the image as a result of the reframing, in 0xRRGGBBAA format, where AA is 0x00 to indicate transparent and a non-zero value to indicate opaque. This parameter is only required when the reframing exceeds the original boundaries (i.e. does not simply perform a crop). |
378
+
379
+ Reframes the image as if placing a frame around the original image and replacing the original image with the newly framed image. When the new frame is strictly within the boundaries of the original image, this method crops the image. When any of the new boundaries exceed those of the original image, the `fillRGBA` must be provided to indicate the color with which to fill the extra space added to the image.
380
+
381
+ **Returns**: [<code>BitmapImage</code>](#BitmapImage) - The present image to allow for chaining.
382
+ <a name="BitmapImage+scale"></a>
383
+
384
+ ### *bitmapImage*.scale(factor)
385
+
386
+ | Param | Type | Description |
387
+ | --- | --- | --- |
388
+ | factor | <code>number</code> | The factor by which to scale up the image. Must be an integer >= 1. |
389
+
390
+ Scales the image size up by an integer factor. Each pixel of the original image becomes a square of the same color in the new image having a size of `factor` x `factor` pixels.
391
+
392
+ **Returns**: [<code>BitmapImage</code>](#BitmapImage) - The present image to allow for chaining.
393
+ <a name="BitmapImage+scanAllCoords"></a>
394
+
395
+ ### *bitmapImage*.scanAllCoords(scanHandler)
396
+ **See**: scanAllIndexes
397
+
398
+ | Param | Type | Description |
399
+ | --- | --- | --- |
400
+ | scanHandler | <code>function</code> | A function(x: number, y: number, bi: number) to be called for each pixel of the image with that pixel's x-coord, y-coord, and index into the `data` buffer. The function accesses the pixel at this coordinate by accessing the `this.data` at index `bi`. |
401
+
402
+ Scans all coordinates of the image, handing each in turn to the provided handler function.
403
+
404
+ <a name="BitmapImage+scanAllIndexes"></a>
405
+
406
+ ### *bitmapImage*.scanAllIndexes(scanHandler)
407
+ **See**: scanAllCoords
408
+
409
+ | Param | Type | Description |
410
+ | --- | --- | --- |
411
+ | scanHandler | <code>function</code> | A function(bi: number) to be called for each pixel of the image with that pixel's index into the `data` buffer. The pixels is found at index 'bi' within `this.data`. |
412
+
413
+ Scans all pixels of the image, handing the index of each in turn to the provided handler function. Runs a bit faster than `scanAllCoords()`, should the handler not need pixel coordinates.
414
+
415
+ <a name="new_GifFrame_new"></a>
416
+
417
+ ### new GifFrame()
418
+ GifFrame is a class representing an image frame of a GIF. GIFs contain one or more instances of GifFrame.
419
+
420
+ Property | Description
421
+ --- | ---
422
+ xOffset | x-coord of position within GIF at which to render the image (defaults to 0)
423
+ yOffset | y-coord of position within GIF at which to render the image (defaults to 0)
424
+ disposalMethod | GIF disposal method; only relevant when the frames aren't all the same size (defaults to 2, disposing to background color)
425
+ delayCentisecs | duration of the frame in hundreths of a second
426
+ interlaced | boolean indicating whether the frame renders interlaced
427
+
428
+ Its constructor supports the following signatures:
429
+
430
+ * new GifFrame(bitmap: {width: number, height: number, data: Buffer}, options?)
431
+ * new GifFrame(bitmapImage: BitmapImage, options?)
432
+ * new GifFrame(width: number, height: number, buffer: Buffer, options?)
433
+ * new GifFrame(width: number, height: number, backgroundRGBA?: number, options?)
434
+ * new GifFrame(frame: GifFrame)
435
+
436
+ See the base class BitmapImage for a discussion of all parameters but `options` and `frame`. `options` is an optional argument providing initial values for the above-listed GifFrame properties. Each property within option is itself optional.
437
+
438
+ Provide a `frame` to the constructor to create a clone of the provided frame. The new frame includes a copy of the provided frame's pixel data so that each can subsequently be modified without affecting each other.
439
+
440
+ <a name="GifFrame+getPalette"></a>
441
+
442
+ ### *gifFrame*.getPalette()
443
+ Get a summary of the colors found within the frame. The return value is an object of the following form:
444
+
445
+ Property | Description
446
+ --- | ---
447
+ colors | An array of all the opaque colors found within the frame. Each color is given as an RGB number of the form 0xRRGGBB. The array is sorted by increasing number. Will be an empty array when the image is completely transparent.
448
+ usesTransparency | boolean indicating whether there are any transparent pixels within the frame. A pixel is considered transparent if its alpha value is 0x00.
449
+ indexCount | The number of color indexes required to represent this palette of colors. It is equal to the number of opaque colors plus one if the image includes transparency.
450
+
451
+ **Returns**: <code>object</code> - An object representing a color palette as described above.
452
+ <a name="GifUtil.cloneFrames"></a>
453
+
454
+ ### *GifUtil*.cloneFrames(frames)
455
+
456
+ | Param | Type | Description |
457
+ | --- | --- | --- |
458
+ | frames | [<code>Array.&lt;GifFrame&gt;</code>](#GifFrame) | An array of GifFrame instances to clone |
459
+
460
+ cloneFrames() clones provided frames. It's a utility method for cloning an entire array of frames at once.
461
+
462
+ **Returns**: [<code>Array.&lt;GifFrame&gt;</code>](#GifFrame) - An array of GifFrame clones of the provided frames.
463
+ <a name="GifUtil.getColorInfo"></a>
464
+
465
+ ### *GifUtil*.getColorInfo(frames, maxGlobalIndex)
466
+ **Throws**:
467
+
468
+ - [<code>GifError</code>](#GifError) When any frame requires more than 256 color indexes.
469
+
470
+
471
+ | Param | Type | Description |
472
+ | --- | --- | --- |
473
+ | frames | [<code>Array.&lt;GifFrame&gt;</code>](#GifFrame) | Frames to examine for color and transparency. |
474
+ | maxGlobalIndex | <code>number</code> | Maximum number of color indexes (including one for transparency) allowed among the returned compilation of colors. `colors` and `indexCount` are not returned if the number of color indexes required to accommodate all frames exceeds this number. Returns `colors` and `indexCount` by default. |
475
+
476
+ getColorInfo() gets information about the colors used in the provided frames. The method is able to return an array of all colors found across all frames.
477
+
478
+ `maxGlobalIndex` controls whether the computation short-circuits to avoid doing work that the caller doesn't need. The method only returns `colors` and `indexCount` for the colors across all frames when the number of indexes required to store the colors and transparency in a GIF (which is the value of `indexCount`) is less than or equal to `maxGlobalIndex`. Such short-circuiting is useful when the caller just needs to determine whether any frame includes transparency.
479
+
480
+ **Returns**: <code>object</code> - Object containing at least `palettes` and `usesTransparency`. `palettes` is an array of all the palettes returned by GifFrame#getPalette(). `usesTransparency` indicates whether at least one frame uses transparency. If `maxGlobalIndex` is not exceeded, the object also contains `colors`, an array of all colors (RGB) found across all palettes, sorted by increasing value, and `indexCount` indicating the number of indexes required to store the colors and the transparency in a GIF.
481
+ <a name="GifUtil.copyAsJimp"></a>
482
+
483
+ ### *GifUtil*.copyAsJimp(Reference, Instance)
484
+
485
+ | Param | Type | Description |
486
+ | --- | --- | --- |
487
+ | Reference | <code>object</code> | to the Jimp package, keeping this library from being dependent on Jimp. |
488
+ | Instance | <code>bitmapImageToCopy</code> | of BitmapImage (may be a GifUtil) with which to source the Jimp. |
489
+
490
+ copyAsJimp() returns a Jimp that contains a copy of the provided bitmap image (which may be either a BitmapImage or a GifFrame). Modifying the Jimp does not affect the provided bitmap image. This method serves as a macro for simplifying working with Jimp.
491
+
492
+ **Returns**: <code>object</code> - An new instance of Jimp containing a copy of the image in bitmapImageToCopy.
493
+ <a name="GifUtil.getMaxDimensions"></a>
494
+
495
+ ### *GifUtil*.getMaxDimensions(frames)
496
+
497
+ | Param | Type | Description |
498
+ | --- | --- | --- |
499
+ | frames | [<code>Array.&lt;GifFrame&gt;</code>](#GifFrame) | Frames to measure for their aggregate maximum dimensions. |
500
+
501
+ getMaxDimensions() returns the pixel width and height required to accommodate all of the provided frames, according to the offsets and dimensions of each frame.
502
+
503
+ **Returns**: <code>object</code> - An object of the form {maxWidth, maxHeight} indicating the maximum width and height required to accommodate all frames.
504
+ <a name="GifUtil.quantizeDekker"></a>
505
+
506
+ ### *GifUtil*.quantizeDekker(imageOrImages, maxColorIndexes, dither)
507
+
508
+ | Param | Type | Description |
509
+ | --- | --- | --- |
510
+ | imageOrImages | [<code>BitmapImage</code>](#BitmapImage) \| [<code>Array.&lt;BitmapImage&gt;</code>](#BitmapImage) | Image or array of images (such as GifFrame instances) to be color-quantized. Quantizing across multiple images ensures color consistency from frame to frame. |
511
+ | maxColorIndexes | <code>number</code> | The maximum number of color indexes that will exist in the palette after completing quantization. Defaults to 256. |
512
+ | dither | <code>object</code> | (optional) An object configuring the dithering to apply. The properties are as followings, imported from the [`image-q` package](https://github.com/ibezkrovnyi/image-quantization) without explanation: { `ditherAlgorithm`: One of 'FloydSteinberg', 'FalseFloydSteinberg', 'Stucki', 'Atkinson', 'Jarvis', 'Burkes', 'Sierra', 'TwoSierra', 'SierraLite'; `minimumColorDistanceToDither`: (optional) A number defaulting to 0; `serpentine`: (optional) A boolean defaulting to true; `calculateErrorLikeGIMP`: (optional) A boolean defaulting to false. } |
513
+
514
+ Quantizes colors so that there are at most a given number of color indexes (including transparency) across all provided images. Uses an algorithm by Anthony Dekker.
515
+
516
+ The method treats different RGBA combinations as different colors, so if the frame has multiple alpha values or multiple RGB values for an alpha value, the caller may first want to normalize them by converting all transparent pixels to the same RGBA values.
517
+
518
+ The method may increase the number of colors if there are fewer than the provided maximum.
519
+
520
+ <a name="GifUtil.quantizeSorokin"></a>
521
+
522
+ ### *GifUtil*.quantizeSorokin(imageOrImages, maxColorIndexes, histogram, dither)
523
+
524
+ | Param | Type | Description |
525
+ | --- | --- | --- |
526
+ | imageOrImages | [<code>BitmapImage</code>](#BitmapImage) \| [<code>Array.&lt;BitmapImage&gt;</code>](#BitmapImage) | Image or array of images (such as GifFrame instances) to be color-quantized. Quantizing across multiple images ensures color consistency from frame to frame. |
527
+ | maxColorIndexes | <code>number</code> | The maximum number of color indexes that will exist in the palette after completing quantization. Defaults to 256. |
528
+ | histogram | <code>string</code> | (optional) Histogram method: 'top-pop' for global top-population, 'min-pop' for minimum-population threshhold within subregions. Defaults to 'min-pop'. |
529
+ | dither | <code>object</code> | (optional) An object configuring the dithering to apply, as explained for `quantizeDekker()`. |
530
+
531
+ Quantizes colors so that there are at most a given number of color indexes (including transparency) across all provided images. Uses an algorithm by Leon Sorokin. This quantization method differs from the other two by likely never increasing the number of colors, should there be fewer than the provided maximum.
532
+
533
+ The method treats different RGBA combinations as different colors, so if the frame has multiple alpha values or multiple RGB values for an alpha value, the caller may first want to normalize them by converting all transparent pixels to the same RGBA values.
534
+
535
+ <a name="GifUtil.quantizeWu"></a>
536
+
537
+ ### *GifUtil*.quantizeWu(imageOrImages, maxColorIndexes, significantBits, dither)
538
+
539
+ | Param | Type | Description |
540
+ | --- | --- | --- |
541
+ | imageOrImages | [<code>BitmapImage</code>](#BitmapImage) \| [<code>Array.&lt;BitmapImage&gt;</code>](#BitmapImage) | Image or array of images (such as GifFrame instances) to be color-quantized. Quantizing across multiple images ensures color consistency from frame to frame. |
542
+ | maxColorIndexes | <code>number</code> | The maximum number of color indexes that will exist in the palette after completing quantization. Defaults to 256. |
543
+ | significantBits | <code>number</code> | (optional) This is the number of significant high bits in each RGB color channel. Takes integer values from 1 through 8. Higher values correspond to higher quality. Defaults to 5. |
544
+ | dither | <code>object</code> | (optional) An object configuring the dithering to apply, as explained for `quantizeDekker()`. |
545
+
546
+ Quantizes colors so that there are at most a given number of color indexes (including transparency) across all provided images. Uses an algorithm by Xiaolin Wu.
547
+
548
+ The method treats different RGBA combinations as different colors, so if the frame has multiple alpha values or multiple RGB values for an alpha value, the caller may first want to normalize them by converting all transparent pixels to the same RGBA values.
549
+
550
+ The method may increase the number of colors if there are fewer than the provided maximum.
551
+
552
+ <a name="GifUtil.read"></a>
553
+
554
+ ### *GifUtil*.read(source, decoder)
555
+
556
+ | Param | Type | Description |
557
+ | --- | --- | --- |
558
+ | source | <code>string</code> \| <code>Buffer</code> | Source to decode. When a string, it's the GIF filename to load and parse. When a Buffer, it's an encoded GIF to parse. |
559
+ | decoder | <code>object</code> | An optional GIF decoder object implementing the `decode` method of class GifCodec. When provided, the method decodes the GIF using this decoder. When not provided, the method uses GifCodec. |
560
+
561
+ read() decodes an encoded GIF, whether provided as a filename or as a byte buffer.
562
+
563
+ **Returns**: <code>Promise</code> - A Promise that resolves to an instance of the Gif class, representing the decoded GIF.
564
+ <a name="GifUtil.shareAsJimp"></a>
565
+
566
+ ### *GifUtil*.shareAsJimp(Reference, Instance)
567
+
568
+ | Param | Type | Description |
569
+ | --- | --- | --- |
570
+ | Reference | <code>object</code> | to the Jimp package, keeping this library from being dependent on Jimp. |
571
+ | Instance | <code>bitmapImageToShare</code> | of BitmapImage (may be a GifUtil) with which to source the Jimp. |
572
+
573
+ shareAsJimp() returns a Jimp that shares a bitmap with the provided bitmap image (which may be either a BitmapImage or a GifFrame). Modifying the image in either the Jimp or the BitmapImage affects the other objects. This method serves as a macro for simplifying working with Jimp.
574
+
575
+ **Returns**: <code>object</code> - An new instance of Jimp that shares the image in bitmapImageToShare.
576
+ <a name="GifUtil.write"></a>
577
+
578
+ ### *GifUtil*.write(path, frames, spec, encoder)
579
+
580
+ | Param | Type | Description |
581
+ | --- | --- | --- |
582
+ | path | <code>string</code> | Filename to write GIF out as. Will overwrite an existing file. |
583
+ | frames | [<code>Array.&lt;GifFrame&gt;</code>](#GifFrame) | Array of frames to be written into GIF. |
584
+ | spec | <code>object</code> | An optional object that may provide values for `loops` and `colorScope`, as defined for the Gif class. However, `colorSpace` may also take the value Gif.GlobalColorsPreferred (== 0) to indicate that the encoder should attempt to create only a global color table. `loop` defaults to 0, looping indefinitely, and `colorScope` defaults to Gif.GlobalColorsPreferred. |
585
+ | encoder | <code>object</code> | An optional GIF encoder object implementing the `encode` method of class GifCodec. When provided, the method encodes the GIF using this encoder. When not provided, the method uses GifCodec. |
586
+
587
+ write() encodes a GIF and saves it as a file.
588
+
589
+ **Returns**: <code>Promise</code> - A Promise that resolves to an instance of the Gif class, representing the encoded GIF.
590
+ <a name="new_GifCodec_new"></a>
591
+
592
+ ### new GifCodec(options)
593
+
594
+ | Param | Type | Description |
595
+ | --- | --- | --- |
596
+ | options | <code>object</code> | Optionally takes an objection whose only possible property is `transparentRGB`. Images are internally represented in RGBA format, where A is the alpha value of a pixel. When `transparentRGB` is provided, this RGB value (excluding alpha) is assigned to transparent pixels, which are also given alpha value 0x00. (All opaque pixels are given alpha value 0xFF). The RGB color of transparent pixels shouldn't matter for most applications. Defaults to 0x000000. |
597
+
598
+ GifCodec is a class that both encodes and decodes GIFs. It implements both the `encode()` method expected of an encoder and the `decode()` method expected of a decoder, and it wraps the `omggif` GIF encoder/decoder package. GifCodec serves as this library's default encoder and decoder, but it's possible to wrap other GIF encoders and decoders for use by `gifwrap` as well. GifCodec will not encode GIFs with interlacing.
599
+
600
+ Instances of this class are stateless and can be shared across multiple encodings and decodings.
601
+
602
+ Its constructor takes one option argument:
603
+
604
+ <a name="GifCodec+decodeGif"></a>
605
+
606
+ ### *gifCodec*.decodeGif(buffer)
607
+ **Throws**:
608
+
609
+ - [<code>GifError</code>](#GifError) Error upon encountered an encoding-related problem with a GIF, so that the caller can distinguish between software errors and problems with GIFs.
610
+
611
+
612
+ | Param | Type | Description |
613
+ | --- | --- | --- |
614
+ | buffer | <code>Buffer</code> | Bytes of an encoded GIF to decode. |
615
+
616
+ Decodes a GIF from a Buffer to yield an instance of Gif. Transparent pixels of the GIF are given alpha values of 0x00, and opaque pixels are given alpha values of 0xFF. The RGB values of transparent pixels default to 0x000000 but can be overridden by the constructor's `transparentRGB` option.
617
+
618
+ **Returns**: <code>Promise</code> - A Promise that resolves to an instance of the Gif class, representing the encoded GIF.
619
+ <a name="GifCodec+encodeGif"></a>
620
+
621
+ ### *gifCodec*.encodeGif(frames, spec)
622
+ **Throws**:
623
+
624
+ - [<code>GifError</code>](#GifError) Error upon encountered an encoding-related problem with a GIF, so that the caller can distinguish between software errors and problems with GIFs.
625
+
626
+
627
+ | Param | Type | Description |
628
+ | --- | --- | --- |
629
+ | frames | [<code>Array.&lt;GifFrame&gt;</code>](#GifFrame) | Array of frames to encode |
630
+ | spec | <code>object</code> | An optional object that may provide values for `loops` and `colorScope`, as defined for the Gif class. However, `colorSpace` may also take the value Gif.GlobalColorsPreferred (== 0) to indicate that the encoder should attempt to create only a global color table. `loop` defaults to 0, looping indefinitely. Set `loop` to null to disable looping, playing only once. `colorScope` defaults to Gif.GlobalColorsPreferred. |
631
+
632
+ Encodes a GIF from provided frames. Each pixel having an alpha value of 0x00 renders as transparent within the encoding, while all pixels of non-zero alpha value render as opaque.
633
+
634
+ **Returns**: <code>Promise</code> - A Promise that resolves to an instance of the Gif class, representing the encoded GIF.
635
+ <a name="new_GifError_new"></a>
636
+
637
+ ### new GifError(messageOrError)
638
+
639
+ | Param | Type |
640
+ | --- | --- |
641
+ | messageOrError | <code>string</code> \| <code>Error</code> |
642
+
643
+ GifError is a class representing a GIF-related error
644
+
645
+
646
+ ## LICENSE
647
+
648
+ MIT License
649
+
650
+ Copyright © 2017 Joseph T. Lapp
651
+
652
+ Permission is hereby granted, free of charge, to any person obtaining a copy
653
+ of this software and associated documentation files (the "Software"), to deal
654
+ in the Software without restriction, including without limitation the rights
655
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
656
+ copies of the Software, and to permit persons to whom the Software is
657
+ furnished to do so, subject to the following conditions:
658
+
659
+ The above copyright notice and this permission notice shall be included in all
660
+ copies or substantial portions of the Software.
661
+
662
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
663
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
664
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
665
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
666
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
667
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
668
+ SOFTWARE.
node_modules/gifwrap/index.d.ts ADDED
@@ -0,0 +1,153 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ export interface GifSpec {
3
+
4
+ loops?: number;
5
+ colorScope?: 0|1|2;
6
+ }
7
+
8
+ export interface GifEncoder {
9
+ encodeGif(frames: GifFrame[], spec: GifSpec): Promise<Gif>;
10
+ }
11
+
12
+ export interface GifDecoder {
13
+ decodeGif(buffer: Buffer): Promise<Gif>;
14
+ }
15
+
16
+ export class Gif implements GifSpec {
17
+
18
+ static readonly GlobalColorsPreferred: 0;
19
+ static readonly GlobalColorsOnly: 1;
20
+ static readonly LocalColorsOnly: 2;
21
+
22
+ width: number;
23
+ height: number;
24
+ loops: number;
25
+ usesTransparency: boolean;
26
+ colorScope: 0|1|2;
27
+
28
+ frames: GifFrame[];
29
+ buffer: Buffer;
30
+
31
+ constructor(frames: GifFrame[], buffer: Buffer, spec?: GifSpec);
32
+ }
33
+
34
+ export interface GifFrameOptions {
35
+ xOffset?: number;
36
+ yOffset?: number;
37
+ disposalMethod?: 0|1|2|3;
38
+ delayCentisecs?: number;
39
+ isInterlaced?: boolean;
40
+ }
41
+
42
+ export interface JimpBitmap {
43
+ width: number;
44
+ height: number;
45
+ data: Buffer;
46
+ }
47
+
48
+ export interface GifPalette {
49
+ colors: number[];
50
+ indexCount: number;
51
+ usesTransparency: boolean;
52
+ }
53
+
54
+ export class BitmapImage {
55
+ bitmap: JimpBitmap;
56
+
57
+ constructor(bitmap: JimpBitmap);
58
+ constructor(bitmapImage: BitmapImage);
59
+ constructor(width: number, height: number, buffer: Buffer);
60
+ constructor(width: number, height: number, backgroundRGBA?: number);
61
+
62
+ blit(toImage: BitmapImage, toX: number, toY: number, fromX: number, fromY: number,
63
+ fromWidth: number, fromHeight: number): this;
64
+ fillRGBA(color: number): this;
65
+ getRGBA(x: number, y: number): number;
66
+ getRGBASet(): Set<number>;
67
+ greyscale(): this;
68
+ reframe(xOffset: number, yOffset: number, width: number, height: number, fillRGBA?: number)
69
+ : this;
70
+ scale(factor: number): this;
71
+ scanAllCoords(handler: (x: number, y: number, bufferIndex: number) => void): void;
72
+ scanAllIndexes(handler: (bufferIndex: number) => void): void;
73
+ }
74
+
75
+ export class GifFrame extends BitmapImage implements GifFrameOptions {
76
+
77
+ static readonly DisposeToAnything: 0;
78
+ static readonly DisposeNothing: 1;
79
+ static readonly DisposeToBackgroundColor: 2;
80
+ static readonly DisposeToPrevious: 3;
81
+
82
+ xOffset: number;
83
+ yOffset: number;
84
+ disposalMethod: 0|1|2|3;
85
+ delayCentisecs: number;
86
+ interlaced: boolean;
87
+
88
+ constructor(bitmap: JimpBitmap, options?: GifFrameOptions);
89
+ constructor(bitmapImage: BitmapImage, options?: GifFrameOptions);
90
+ constructor(width: number, height: number, buffer: Buffer, options?: GifFrameOptions);
91
+ constructor(width: number, height: number, backgroundRGBA?: number, options?: GifFrameOptions);
92
+ constructor(frame: GifFrame);
93
+
94
+ getPalette(): GifPalette;
95
+ }
96
+
97
+ export interface GifCodecOptions {
98
+ transparentRGB?: number;
99
+ }
100
+
101
+ export class GifCodec implements GifEncoder, GifDecoder {
102
+
103
+ constructor(options?: GifCodecOptions);
104
+
105
+ encodeGif(frames: GifFrame[], spec: GifSpec): Promise<Gif>;
106
+ decodeGif(buffer: Buffer): Promise<Gif>;
107
+ }
108
+
109
+ export class GifError extends Error {
110
+
111
+ constructor(message: string);
112
+ }
113
+
114
+ export namespace GifUtil {
115
+
116
+ function cloneFrames(frames: GifFrame[]): GifFrame[];
117
+ function copyAsJimp(jimp: any, bitmapImageToCopy: BitmapImage): any;
118
+ function getColorInfo(frames: GifFrame[], maxGlobalIndex?: number): {
119
+ colors?: number[],
120
+ indexCount?: number,
121
+ usesTransparency: boolean,
122
+ palettes: GifPalette[]
123
+ }
124
+ function getMaxDimensions(frames: GifFrame[]): { maxWidth: number, maxHeight: number };
125
+ function quantizeDekker(imageOrImages: BitmapImage|BitmapImage[], maxColorIndexes: number,
126
+ dither?: Dither): void;
127
+ function quantizeSorokin(imageOrImages: BitmapImage|BitmapImage[], maxColorIndexes: number,
128
+ histogram?: string, dither?: Dither): void;
129
+ function quantizeWu(imageOrImages: BitmapImage|BitmapImage[], maxColorIndexes: number,
130
+ significantBits?: number, dither?: Dither): void;
131
+ function read(source: string|Buffer, decoder?: GifDecoder): Promise<Gif>;
132
+ function shareAsJimp(jimp: any, bitmapImageToCopy: BitmapImage): any;
133
+ function write(path: string, frames: GifFrame[], spec?: GifSpec, encoder?: GifEncoder):
134
+ Promise<Gif>;
135
+ }
136
+
137
+ export type DitherAlgorithm =
138
+ 'FloydSteinberg' |
139
+ 'FalseFloydSteinberg' |
140
+ 'Stucki' |
141
+ 'Atkinson' |
142
+ 'Jarvis' |
143
+ 'Burkes' |
144
+ 'Sierra' |
145
+ 'TwoSierra' |
146
+ 'SierraLite';
147
+
148
+ export type Dither = {
149
+ ditherAlgorithm: DitherAlgorithm,
150
+ minimumColorDistanceToDither?: number, // default = 0
151
+ serpentine?: boolean, // default = true
152
+ calculateErrorLikeGIMP?: boolean // default = false
153
+ };
node_modules/gifwrap/package.json ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name": "gifwrap",
3
+ "version": "0.10.1",
4
+ "description": "A Jimp-compatible library for working with GIFs",
5
+ "main": "src/index.js",
6
+ "scripts": {
7
+ "test": "mocha --timeout=6000 ./test/*.js",
8
+ "docs": "jsdoc2md --plugin dmd-clear --template templates/README.hbs src/index.js src/gif.js src/bitmapimage.js src/gifframe.js src/gifutil.js src/gifcodec.js > README.md"
9
+ },
10
+ "repository": {
11
+ "type": "git",
12
+ "url": "git+https://github.com/jtlapp/gifwrap.git"
13
+ },
14
+ "keywords": [
15
+ "image",
16
+ "image",
17
+ "processing",
18
+ "image",
19
+ "manipulation",
20
+ "gif",
21
+ "javascript"
22
+ ],
23
+ "author": "Joseph T. Lapp",
24
+ "license": "MIT",
25
+ "bugs": {
26
+ "url": "https://github.com/jtlapp/gifwrap/issues"
27
+ },
28
+ "homepage": "https://github.com/jtlapp/gifwrap#readme",
29
+ "dependencies": {
30
+ "image-q": "^4.0.0",
31
+ "omggif": "^1.0.10"
32
+ },
33
+ "devDependencies": {
34
+ "chai": "^4.2.0",
35
+ "dmd-clear": "^0.1.2",
36
+ "jimp": "^0.2.28",
37
+ "mocha": "^9.2.2"
38
+ }
39
+ }
node_modules/gifwrap/src/bitmapimage.js ADDED
@@ -0,0 +1,310 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 'use strict';
2
+
3
+ /** @class BitmapImage */
4
+
5
+ class BitmapImage {
6
+
7
+ /**
8
+ * BitmapImage is a class that hold an RGBA (red, green, blue, alpha) representation of an image. It's shape is borrowed from the Jimp package to make it easy to transfer GIF image frames into Jimp and Jimp images into GIF image frames. Each instance has a `bitmap` property having the following properties:
9
+ *
10
+ * Property | Description
11
+ * --- | ---
12
+ * bitmap.width | width of image in pixels
13
+ * bitmap.height | height of image in pixels
14
+ * bitmap.data | a Buffer whose every four bytes represents a pixel, each sequential byte of a pixel corresponding to the red, green, blue, and alpha values of the pixel
15
+ *
16
+ * Its constructor supports the following signatures:
17
+ *
18
+ * * new BitmapImage(bitmap: { width: number, height: number, data: Buffer })
19
+ * * new BitmapImage(bitmapImage: BitmapImage)
20
+ * * new BitmapImage(width: number, height: number, buffer: Buffer)
21
+ * * new BitmapImage(width: number, height: number, backgroundRGBA?: number)
22
+ *
23
+ * When a `BitmapImage` is provided, the constructed `BitmapImage` is a deep clone of the provided one, so that each image's pixel data can subsequently be modified without affecting each other.
24
+ *
25
+ * `backgroundRGBA` is an optional parameter representing a pixel as a single number. In hex, the number is as follows: 0xRRGGBBAA, where RR is the red byte, GG the green byte, BB, the blue byte, and AA the alpha value. An AA of 0x00 is considered transparent, and all non-zero AA values are treated as opaque.
26
+ */
27
+
28
+ constructor(...args) {
29
+ // don't confirm the number of args, because a subclass may have
30
+ // additional args and pass them all to the superclass
31
+ if (args.length === 0) {
32
+ throw new Error("constructor requires parameters");
33
+ }
34
+ const firstArg = args[0];
35
+ if (firstArg !== null && typeof firstArg === 'object') {
36
+ if (firstArg instanceof BitmapImage) {
37
+ // copy a provided BitmapImage
38
+ const sourceBitmap = firstArg.bitmap;
39
+ this.bitmap = {
40
+ width: sourceBitmap.width,
41
+ height: sourceBitmap.height,
42
+ data: new Buffer(sourceBitmap.width * sourceBitmap.height * 4)
43
+ };
44
+ sourceBitmap.data.copy(this.bitmap.data);
45
+ }
46
+ else if (firstArg.width && firstArg.height && firstArg.data) {
47
+ // share a provided bitmap
48
+ this.bitmap = firstArg;
49
+ }
50
+ else {
51
+ throw new Error("unrecognized constructor parameters");
52
+ }
53
+ }
54
+ else if (typeof firstArg === 'number' && typeof args[1] === 'number')
55
+ {
56
+ const width = firstArg;
57
+ const height = args[1];
58
+ const thirdArg = args[2];
59
+ this.bitmap = { width, height };
60
+
61
+ if (Buffer.isBuffer(thirdArg)) {
62
+ this.bitmap.data = thirdArg;
63
+ }
64
+ else {
65
+ this.bitmap.data = new Buffer(width * height * 4);
66
+ if (typeof thirdArg === 'number') {
67
+ this.fillRGBA(thirdArg);
68
+ }
69
+ }
70
+ }
71
+ else {
72
+ throw new Error("unrecognized constructor parameters");
73
+ }
74
+ }
75
+
76
+ /**
77
+ * Copy a square portion of this image into another image.
78
+ *
79
+ * @param {BitmapImage} toImage Image into which to copy the square
80
+ * @param {number} toX x-coord in toImage of upper-left corner of receiving square
81
+ * @param {number} toY y-coord in toImage of upper-left corner of receiving square
82
+ * @param {number} fromX x-coord in this image of upper-left corner of source square
83
+ * @param {number} fromY y-coord in this image of upper-left corner of source square
84
+ * @return {BitmapImage} The present image to allow for chaining.
85
+ */
86
+
87
+ blit(toImage, toX, toY, fromX, fromY, fromWidth, fromHeight) {
88
+ if (fromX + fromWidth > this.bitmap.width) {
89
+ throw new Error("copy exceeds width of source bitmap");
90
+ }
91
+ if (toX + fromWidth > toImage.bitmap.width) {
92
+ throw new Error("copy exceeds width of target bitmap");
93
+ }
94
+ if (fromY + fromHeight > this.bitmap.height) {
95
+ throw new Error("copy exceeds height of source bitmap");
96
+ }
97
+ if (toY + fromHeight > toImage.bitmap.height) {
98
+ throw new Erro("copy exceeds height of target bitmap");
99
+ }
100
+
101
+ const sourceBuf = this.bitmap.data;
102
+ const targetBuf = toImage.bitmap.data;
103
+ const sourceByteWidth = this.bitmap.width * 4;
104
+ const targetByteWidth = toImage.bitmap.width * 4;
105
+ const copyByteWidth = fromWidth * 4;
106
+ let si = fromY * sourceByteWidth + fromX * 4;
107
+ let ti = toY * targetByteWidth + toX * 4;
108
+
109
+ while (--fromHeight >= 0) {
110
+ sourceBuf.copy(targetBuf, ti, si, si + copyByteWidth);
111
+ si += sourceByteWidth;
112
+ ti += targetByteWidth;
113
+ }
114
+ return this;
115
+ }
116
+
117
+ /**
118
+ * Fills the image with a single color.
119
+ *
120
+ * @param {number} rgba Color with which to fill image, expressed as a singlenumber in the form 0xRRGGBBAA, where AA is 0x00 for transparent and any other value for opaque.
121
+ * @return {BitmapImage} The present image to allow for chaining.
122
+ */
123
+
124
+ fillRGBA(rgba) {
125
+ const buf = this.bitmap.data;
126
+ const bufByteWidth = this.bitmap.height * 4;
127
+
128
+ let bi = 0;
129
+ while (bi < bufByteWidth) {
130
+ buf.writeUInt32BE(rgba, bi);
131
+ bi += 4;
132
+ }
133
+ while (bi < buf.length) {
134
+ buf.copy(buf, bi, 0, bufByteWidth);
135
+ bi += bufByteWidth;
136
+ }
137
+ return this;
138
+ }
139
+
140
+ /**
141
+ * Gets the RGBA number of the pixel at the given coordinate in the form 0xRRGGBBAA, where AA is the alpha value, with alpha 0x00 encoding to transparency in GIFs.
142
+ *
143
+ * @param {number} x x-coord of pixel
144
+ * @param {number} y y-coord of pixel
145
+ * @return {number} RGBA of pixel in 0xRRGGBBAA form
146
+ */
147
+
148
+ getRGBA(x, y) {
149
+ const bi = (y * this.bitmap.width + x) * 4;
150
+ return this.bitmap.data.readUInt32BE(bi);
151
+ }
152
+
153
+ /**
154
+ * Gets a set of all RGBA colors found within the image.
155
+ *
156
+ * @return {Set} Set of all RGBA colors that the image contains.
157
+ */
158
+
159
+ getRGBASet() {
160
+ const rgbaSet = new Set();
161
+ const buf = this.bitmap.data;
162
+ for (let bi = 0; bi < buf.length; bi += 4) {
163
+ rgbaSet.add(buf.readUInt32BE(bi, true));
164
+ }
165
+ return rgbaSet;
166
+ }
167
+
168
+ /**
169
+ * Converts the image to greyscale using inferred Adobe metrics.
170
+ *
171
+ * @return {BitmapImage} The present image to allow for chaining.
172
+ */
173
+
174
+ greyscale() {
175
+ const buf = this.bitmap.data;
176
+ this.scan(0, 0, this.bitmap.width, this.bitmap.height, (x, y, idx) => {
177
+ const grey = Math.round(
178
+ 0.299 * buf[idx] +
179
+ 0.587 * buf[idx + 1] +
180
+ 0.114 * buf[idx + 2]
181
+ );
182
+ buf[idx] = grey;
183
+ buf[idx + 1] = grey;
184
+ buf[idx + 2] = grey;
185
+ });
186
+ return this;
187
+ }
188
+
189
+ /**
190
+ * Reframes the image as if placing a frame around the original image and replacing the original image with the newly framed image. When the new frame is strictly within the boundaries of the original image, this method crops the image. When any of the new boundaries exceed those of the original image, the `fillRGBA` must be provided to indicate the color with which to fill the extra space added to the image.
191
+ *
192
+ * @param {number} xOffset The x-coord offset of the upper-left pixel of the desired image relative to the present image.
193
+ * @param {number} yOffset The y-coord offset of the upper-left pixel of the desired image relative to the present image.
194
+ * @param {number} width The width of the new image after reframing
195
+ * @param {number} height The height of the new image after reframing
196
+ * @param {number} fillRGBA The color with which to fill space added to the image as a result of the reframing, in 0xRRGGBBAA format, where AA is 0x00 to indicate transparent and a non-zero value to indicate opaque. This parameter is only required when the reframing exceeds the original boundaries (i.e. does not simply perform a crop).
197
+ * @return {BitmapImage} The present image to allow for chaining.
198
+ */
199
+
200
+ reframe(xOffset, yOffset, width, height, fillRGBA) {
201
+ const cropX = (xOffset < 0 ? 0 : xOffset);
202
+ const cropY = (yOffset < 0 ? 0 : yOffset);
203
+ const cropWidth = (width + cropX > this.bitmap.width ?
204
+ this.bitmap.width - cropX : width);
205
+ const cropHeight = (height + cropY > this.bitmap.height ?
206
+ this.bitmap.height - cropY : height);
207
+ const newX = (xOffset < 0 ? -xOffset : 0);
208
+ const newY = (yOffset < 0 ? -yOffset : 0);
209
+
210
+ let image;
211
+ if (fillRGBA === undefined) {
212
+ if (cropX !== xOffset || cropY != yOffset ||
213
+ cropWidth !== width || cropHeight !== height)
214
+ {
215
+ throw new GifError(`fillRGBA required for this reframing`);
216
+ }
217
+ image = new BitmapImage(width, height);
218
+ }
219
+ else {
220
+ image = new BitmapImage(width, height, fillRGBA);
221
+ }
222
+ this.blit(image, newX, newY, cropX, cropY, cropWidth, cropHeight);
223
+ this.bitmap = image.bitmap;
224
+ return this;
225
+ }
226
+
227
+ /**
228
+ * Scales the image size up by an integer factor. Each pixel of the original image becomes a square of the same color in the new image having a size of `factor` x `factor` pixels.
229
+ *
230
+ * @param {number} factor The factor by which to scale up the image. Must be an integer >= 1.
231
+ * @return {BitmapImage} The present image to allow for chaining.
232
+ */
233
+
234
+ scale(factor) {
235
+ if (factor === 1) {
236
+ return;
237
+ }
238
+ if (!Number.isInteger(factor) || factor < 1) {
239
+ throw new Error("the scale must be an integer >= 1");
240
+ }
241
+ const sourceWidth = this.bitmap.width;
242
+ const sourceHeight = this.bitmap.height;
243
+ const destByteWidth = sourceWidth * factor * 4;
244
+ const sourceBuf = this.bitmap.data;
245
+ const destBuf = new Buffer(sourceHeight * destByteWidth * factor);
246
+ let sourceIndex = 0;
247
+ let priorDestRowIndex;
248
+ let destIndex = 0;
249
+ for (let y = 0; y < sourceHeight; ++y) {
250
+ priorDestRowIndex = destIndex;
251
+ for (let x = 0; x < sourceWidth; ++x) {
252
+ const color = sourceBuf.readUInt32BE(sourceIndex, true);
253
+ for (let cx = 0; cx < factor; ++cx) {
254
+ destBuf.writeUInt32BE(color, destIndex);
255
+ destIndex += 4;
256
+ }
257
+ sourceIndex += 4;
258
+ }
259
+ for (let cy = 1; cy < factor; ++cy) {
260
+ destBuf.copy(destBuf, destIndex, priorDestRowIndex, destIndex);
261
+ destIndex += destByteWidth;
262
+ priorDestRowIndex += destByteWidth;
263
+ }
264
+ }
265
+ this.bitmap = {
266
+ width: sourceWidth * factor,
267
+ height: sourceHeight * factor,
268
+ data: destBuf
269
+ };
270
+ return this;
271
+ }
272
+
273
+ /**
274
+ * Scans all coordinates of the image, handing each in turn to the provided handler function.
275
+ *
276
+ * @param {function} scanHandler A function(x: number, y: number, bi: number) to be called for each pixel of the image with that pixel's x-coord, y-coord, and index into the `data` buffer. The function accesses the pixel at this coordinate by accessing the `this.data` at index `bi`.
277
+ * @see scanAllIndexes
278
+ */
279
+
280
+ scanAllCoords(scanHandler) {
281
+ const width = this.bitmap.width;
282
+ const bufferLength = this.bitmap.data.length;
283
+ let x = 0;
284
+ let y = 0;
285
+
286
+ for (let bi = 0; bi < bufferLength; bi += 4) {
287
+ scanHandler(x, y, bi);
288
+ if (++x === width) {
289
+ x = 0;
290
+ ++y;
291
+ }
292
+ }
293
+ }
294
+
295
+ /**
296
+ * Scans all pixels of the image, handing the index of each in turn to the provided handler function. Runs a bit faster than `scanAllCoords()`, should the handler not need pixel coordinates.
297
+ *
298
+ * @param {function} scanHandler A function(bi: number) to be called for each pixel of the image with that pixel's index into the `data` buffer. The pixels is found at index 'bi' within `this.data`.
299
+ * @see scanAllCoords
300
+ */
301
+
302
+ scanAllIndexes(scanHandler) {
303
+ const bufferLength = this.bitmap.data.length;
304
+ for (let bi = 0; bi < bufferLength; bi += 4) {
305
+ scanHandler(bi);
306
+ }
307
+ }
308
+ }
309
+
310
+ module.exports = BitmapImage;
node_modules/gifwrap/src/gif.js ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 'use strict';
2
+
3
+ /** @class Gif */
4
+
5
+ class Gif {
6
+
7
+ // width - width of GIF in pixels
8
+ // height - height of GIF in pixels
9
+ // loops - 0 = unending; (n > 0) = iterate n times
10
+ // usesTransparency - whether any frames have transparent pixels
11
+ // colorScope - scope of color tables in GIF
12
+ // frames - array of frames
13
+ // buffer - GIF-formatted data
14
+
15
+ /**
16
+ * Gif is a class representing an encoded GIF. It is intended to be a read-only representation of a byte-encoded GIF. Only encoders and decoders should be creating instances of this class.
17
+ *
18
+ * Property | Description
19
+ * --- | ---
20
+ * width | width of the GIF at its widest
21
+ * height | height of the GIF at its highest
22
+ * loops | the number of times the GIF should loop before stopping; 0 => loop indefinitely
23
+ * usesTransparency | boolean indicating whether at least one frame contains at least one transparent pixel
24
+ * colorScope | the scope of the color tables as encoded within the GIF; either Gif.GlobalColorsOnly (== 1) or Gif.LocalColorsOnly (== 2).
25
+ * frames | a array of GifFrame instances, one for each frame of the GIF
26
+ * buffer | a Buffer holding the encoding's byte data
27
+ *
28
+ * Its constructor should only ever be called by the GIF encoder or decoder.
29
+ *
30
+ * @param {Buffer} buffer A Buffer containing the encoded bytes
31
+ * @param {GifFrame[]} frames Array of frames found in the encoding
32
+ * @param {object} spec Properties of the encoding as listed above
33
+ */
34
+
35
+ constructor(buffer, frames, spec) {
36
+ this.width = spec.width;
37
+ this.height = spec.height;
38
+ this.loops = spec.loops;
39
+ this.usesTransparency = spec.usesTransparency;
40
+ this.colorScope = spec.colorScope;
41
+ this.frames = frames;
42
+ this.buffer = buffer;
43
+ }
44
+ }
45
+
46
+ Gif.GlobalColorsPreferred = 0;
47
+ Gif.GlobalColorsOnly = 1;
48
+ Gif.LocalColorsOnly = 2;
49
+
50
+ /** @class GifError */
51
+
52
+ class GifError extends Error {
53
+
54
+ /**
55
+ * GifError is a class representing a GIF-related error
56
+ *
57
+ * @param {string|Error} messageOrError
58
+ */
59
+
60
+ constructor(messageOrError) {
61
+ super(messageOrError);
62
+ if (messageOrError instanceof Error) {
63
+ this.stack = 'Gif' + messageOrError.stack;
64
+ }
65
+ }
66
+ }
67
+
68
+ exports.Gif = Gif;
69
+ exports.GifError = GifError;
node_modules/gifwrap/src/gifcodec.js ADDED
@@ -0,0 +1,404 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 'use strict';
2
+
3
+ const Omggif = require('omggif');
4
+ const { Gif, GifError } = require('./gif');
5
+
6
+ // allow circular dependency with GifUtil
7
+ function GifUtil() {
8
+ const data = require('./gifutil');
9
+
10
+ GifUtil = function () {
11
+ return data;
12
+ };
13
+
14
+ return data;
15
+ }
16
+
17
+ const { GifFrame } = require('./gifframe');
18
+
19
+ const PER_GIF_OVERHEAD = 200; // these are guesses at upper limits
20
+ const PER_FRAME_OVERHEAD = 100;
21
+
22
+ // Note: I experimented with accepting a global color table when encoding and returning the global color table when decoding. Doing this properly greatly increased the complexity of the code and the amount of clock cycles required. The main issue is that each frame can specify any color of the global color table to be transparent within the frame, while this GIF library strives to hide GIF formatting details from its clients. E.g. it's possible to have 256 colors in the global color table and different transparencies in each frame, requiring clients to either provide per-frame transparency indexes, or for arcane reasons that won't be apparent to client developers, encode some GIFs with local color tables that previously decoded with global tables.
23
+
24
+ /** @class GifCodec */
25
+
26
+ class GifCodec
27
+ {
28
+ // _transparentRGBA - RGB given to transparent pixels (alpha=0) on decode; defaults to null indicating 0x000000, which is fastest
29
+
30
+ /**
31
+ * GifCodec is a class that both encodes and decodes GIFs. It implements both the `encode()` method expected of an encoder and the `decode()` method expected of a decoder, and it wraps the `omggif` GIF encoder/decoder package. GifCodec serves as this library's default encoder and decoder, but it's possible to wrap other GIF encoders and decoders for use by `gifwrap` as well. GifCodec will not encode GIFs with interlacing.
32
+ *
33
+ * Instances of this class are stateless and can be shared across multiple encodings and decodings.
34
+ *
35
+ * Its constructor takes one option argument:
36
+ *
37
+ * @param {object} options Optionally takes an objection whose only possible property is `transparentRGB`. Images are internally represented in RGBA format, where A is the alpha value of a pixel. When `transparentRGB` is provided, this RGB value (excluding alpha) is assigned to transparent pixels, which are also given alpha value 0x00. (All opaque pixels are given alpha value 0xFF). The RGB color of transparent pixels shouldn't matter for most applications. Defaults to 0x000000.
38
+ */
39
+
40
+ constructor(options = {}) {
41
+ this._transparentRGB = null; // 0x000000
42
+ if (typeof options.transparentRGB === 'number' &&
43
+ options.transparentRGB !== 0)
44
+ {
45
+ this._transparentRGBA = options.transparentRGB * 256;
46
+ }
47
+ this._testInitialBufferSize = 0; // assume no buffer scaling test
48
+ }
49
+
50
+ /**
51
+ * Decodes a GIF from a Buffer to yield an instance of Gif. Transparent pixels of the GIF are given alpha values of 0x00, and opaque pixels are given alpha values of 0xFF. The RGB values of transparent pixels default to 0x000000 but can be overridden by the constructor's `transparentRGB` option.
52
+ *
53
+ * @param {Buffer} buffer Bytes of an encoded GIF to decode.
54
+ * @return {Promise} A Promise that resolves to an instance of the Gif class, representing the encoded GIF.
55
+ * @throws {GifError} Error upon encountered an encoding-related problem with a GIF, so that the caller can distinguish between software errors and problems with GIFs.
56
+ */
57
+
58
+ decodeGif(buffer) {
59
+ try {
60
+ let reader;
61
+ try {
62
+ reader = new Omggif.GifReader(buffer);
63
+ }
64
+ catch (err) {
65
+ throw new GifError(err);
66
+ }
67
+ const frameCount = reader.numFrames();
68
+ const frames = [];
69
+ const spec = {
70
+ width: reader.width,
71
+ height: reader.height,
72
+ loops: reader.loopCount()
73
+ };
74
+
75
+ spec.usesTransparency = false;
76
+ for (let i = 0; i < frameCount; ++i) {
77
+ const frameInfo =
78
+ this._decodeFrame(reader, i, spec.usesTransparency);
79
+ frames.push(frameInfo.frame);
80
+ if (frameInfo.usesTransparency) {
81
+ spec.usesTransparency = true;
82
+ }
83
+ }
84
+ return Promise.resolve(new Gif(buffer, frames, spec));
85
+ }
86
+ catch (err) {
87
+ return Promise.reject(err);
88
+ }
89
+ }
90
+
91
+ /**
92
+ * Encodes a GIF from provided frames. Each pixel having an alpha value of 0x00 renders as transparent within the encoding, while all pixels of non-zero alpha value render as opaque.
93
+ *
94
+ * @param {GifFrame[]} frames Array of frames to encode
95
+ * @param {object} spec An optional object that may provide values for `loops` and `colorScope`, as defined for the Gif class. However, `colorSpace` may also take the value Gif.GlobalColorsPreferred (== 0) to indicate that the encoder should attempt to create only a global color table. `loop` defaults to 0, looping indefinitely. Set `loop` to null to disable looping, playing only once. `colorScope` defaults to Gif.GlobalColorsPreferred.
96
+ * @return {Promise} A Promise that resolves to an instance of the Gif class, representing the encoded GIF.
97
+ * @throws {GifError} Error upon encountered an encoding-related problem with a GIF, so that the caller can distinguish between software errors and problems with GIFs.
98
+ */
99
+
100
+ encodeGif(frames, spec = {}) {
101
+ try {
102
+ if (frames === null || frames.length === 0) {
103
+ throw new GifError("there are no frames");
104
+ }
105
+ const dims = GifUtil().getMaxDimensions(frames);
106
+
107
+ spec = Object.assign({}, spec); // don't munge caller's spec
108
+ spec.width = dims.maxWidth;
109
+ spec.height = dims.maxHeight;
110
+ if (spec.loops === undefined) {
111
+ spec.loops = 0;
112
+ }
113
+ spec.colorScope = spec.colorScope || Gif.GlobalColorsPreferred;
114
+
115
+ return Promise.resolve(this._encodeGif(frames, spec));
116
+ }
117
+ catch (err) {
118
+ return Promise.reject(err);
119
+ }
120
+ }
121
+
122
+ _decodeFrame(reader, frameIndex, alreadyUsedTransparency) {
123
+ let info, buffer;
124
+ try {
125
+ info = reader.frameInfo(frameIndex);
126
+ buffer = new Buffer(reader.width * reader.height * 4);
127
+ reader.decodeAndBlitFrameRGBA(frameIndex, buffer);
128
+ if (info.width !== reader.width || info.height !== reader.height) {
129
+ if (info.y) {
130
+ // skip unused rows
131
+ buffer = buffer.slice(info.y * reader.width * 4);
132
+ }
133
+ if (reader.width > info.width) {
134
+ // skip scanstride
135
+ for (let ii = 0; ii < info.height; ++ii) {
136
+ buffer.copy(buffer, ii * info.width * 4,
137
+ (info.x + ii * reader.width) * 4,
138
+ (info.x + ii * reader.width) * 4 + info.width * 4);
139
+ }
140
+ }
141
+ // trim buffer to size
142
+ buffer = buffer.slice(0, info.width * info.height * 4);
143
+ }
144
+ }
145
+ catch (err) {
146
+ throw new GifError(err);
147
+ }
148
+
149
+ let usesTransparency = false;
150
+ if (this._transparentRGBA === null) {
151
+ if (!alreadyUsedTransparency) {
152
+ for (let i = 3; i < buffer.length; i += 4) {
153
+ if (buffer[i] === 0) {
154
+ usesTransparency = true;
155
+ i = buffer.length;
156
+ }
157
+ }
158
+ }
159
+ }
160
+ else {
161
+ for (let i = 3; i < buffer.length; i += 4) {
162
+ if (buffer[i] === 0) {
163
+ buffer.writeUInt32BE(this._transparentRGBA, i - 3);
164
+ usesTransparency = true; // GIF might encode unused index
165
+ }
166
+ }
167
+ }
168
+
169
+ const frame = new GifFrame(info.width, info.height, buffer, {
170
+ xOffset: info.x,
171
+ yOffset: info.y,
172
+ disposalMethod: info.disposal,
173
+ interlaced: info.interlaced,
174
+ delayCentisecs: info.delay
175
+ });
176
+ return { frame, usesTransparency };
177
+ }
178
+
179
+ _encodeGif(frames, spec) {
180
+ let colorInfo;
181
+ if (spec.colorScope === Gif.LocalColorsOnly) {
182
+ colorInfo = GifUtil().getColorInfo(frames, 0);
183
+ }
184
+ else {
185
+ colorInfo = GifUtil().getColorInfo(frames, 256);
186
+ if (!colorInfo.colors) { // if global palette impossible
187
+ if (spec.colorScope === Gif.GlobalColorsOnly) {
188
+ throw new GifError(
189
+ "Too many color indexes for global color table");
190
+ }
191
+ spec.colorScope = Gif.LocalColorsOnly
192
+ }
193
+ }
194
+ spec.usesTransparency = colorInfo.usesTransparency;
195
+
196
+ const localPalettes = colorInfo.palettes;
197
+ if (spec.colorScope === Gif.LocalColorsOnly) {
198
+ const localSizeEst = 2000; //this._getSizeEstimateLocal(localPalettes, frames);
199
+ return _encodeLocal(frames, spec, localSizeEst, localPalettes);
200
+ }
201
+
202
+ const globalSizeEst = 2000; //this._getSizeEstimateGlobal(colorInfo, frames);
203
+ return _encodeGlobal(frames, spec, globalSizeEst, colorInfo);
204
+ }
205
+
206
+ _getSizeEstimateGlobal(globalPalette, frames) {
207
+ if (this._testInitialBufferSize > 0) {
208
+ return this._testInitialBufferSize;
209
+ }
210
+ let sizeEst = PER_GIF_OVERHEAD + 3*256 /* max palette size*/;
211
+ const pixelBitWidth = _getPixelBitWidth(globalPalette);
212
+ frames.forEach(frame => {
213
+ sizeEst += _getFrameSizeEst(frame, pixelBitWidth);
214
+ });
215
+ return sizeEst; // should be the upper limit
216
+ }
217
+
218
+ _getSizeEstimateLocal(palettes, frames) {
219
+ if (this._testInitialBufferSize > 0) {
220
+ return this._testInitialBufferSize;
221
+ }
222
+ let sizeEst = PER_GIF_OVERHEAD;
223
+ for (let i = 0; i < frames.length; ++i ) {
224
+ const palette = palettes[i];
225
+ const pixelBitWidth = _getPixelBitWidth(palette);
226
+ sizeEst += _getFrameSizeEst(frames[i], pixelBitWidth);
227
+ }
228
+ return sizeEst; // should be the upper limit
229
+ }
230
+ }
231
+ exports.GifCodec = GifCodec;
232
+
233
+ function _colorLookupLinear(colors, color) {
234
+ const index = colors.indexOf(color);
235
+ return (index === -1 ? null : index);
236
+ }
237
+
238
+ function _colorLookupBinary(colors, color) {
239
+ // adapted from https://stackoverflow.com/a/10264318/650894
240
+ var lo = 0, hi = colors.length - 1, mid;
241
+ while (lo <= hi) {
242
+ mid = Math.floor((lo + hi)/2);
243
+ if (colors[mid] > color)
244
+ hi = mid - 1;
245
+ else if (colors[mid] < color)
246
+ lo = mid + 1;
247
+ else
248
+ return mid;
249
+ }
250
+ return null;
251
+ }
252
+
253
+ function _encodeGlobal(frames, spec, bufferSizeEst, globalPalette) {
254
+ // would be inefficient for frames to lookup colors in extended palette
255
+ const extendedGlobalPalette = {
256
+ colors: globalPalette.colors.slice(),
257
+ usesTransparency: globalPalette.usesTransparency
258
+ };
259
+ _extendPaletteToPowerOf2(extendedGlobalPalette);
260
+ const options = {
261
+ palette: extendedGlobalPalette.colors,
262
+ loop: spec.loops
263
+ };
264
+ let buffer = new Buffer(bufferSizeEst);
265
+ let gifWriter;
266
+ try {
267
+ gifWriter = new Omggif.GifWriter(buffer, spec.width, spec.height,
268
+ options);
269
+ }
270
+ catch (err) {
271
+ throw new GifError(err);
272
+ }
273
+ for (let i = 0; i < frames.length; ++i) {
274
+ buffer = _writeFrame(gifWriter, i, frames[i], globalPalette, false);
275
+ }
276
+ return new Gif(buffer.slice(0, gifWriter.end()), frames, spec);
277
+ }
278
+
279
+ function _encodeLocal(frames, spec, bufferSizeEst, localPalettes) {
280
+ const options = {
281
+ loop: spec.loops
282
+ };
283
+ let buffer = new Buffer(bufferSizeEst);
284
+ let gifWriter;
285
+ try {
286
+ gifWriter = new Omggif.GifWriter(buffer, spec.width, spec.height,
287
+ options);
288
+ }
289
+ catch (err) {
290
+ throw new GifError(err);
291
+ }
292
+ for (let i = 0; i < frames.length; ++i) {
293
+ buffer = _writeFrame(gifWriter, i, frames[i], localPalettes[i], true);
294
+ }
295
+ return new Gif(buffer.slice(0, gifWriter.end()), frames, spec);
296
+ }
297
+
298
+ function _extendPaletteToPowerOf2(palette) {
299
+ const colors = palette.colors;
300
+ if (palette.usesTransparency) {
301
+ colors.push(0);
302
+ }
303
+ const colorCount = colors.length;
304
+ let powerOf2 = 2;
305
+ while (colorCount > powerOf2) {
306
+ powerOf2 <<= 1;
307
+ }
308
+ colors.length = powerOf2;
309
+ colors.fill(0, colorCount);
310
+ }
311
+
312
+ function _getFrameSizeEst(frame, pixelBitWidth) {
313
+ let byteLength = frame.bitmap.width * frame.bitmap.height;
314
+ byteLength = Math.ceil(byteLength * pixelBitWidth / 8);
315
+ byteLength += Math.ceil(byteLength / 255); // add block size bytes
316
+ // assume maximum palete size because it might get extended for power of 2
317
+ return (PER_FRAME_OVERHEAD + byteLength + 3 * 256 /* largest palette */);
318
+ }
319
+
320
+ function _getIndexedImage(frameIndex, frame, palette) {
321
+ const colors = palette.colors;
322
+ const colorToIndexFunc = (colors.length <= 8 ? // guess at the break-even
323
+ _colorLookupLinear : _colorLookupBinary);
324
+ const colorBuffer = frame.bitmap.data;
325
+ const indexBuffer = new Buffer(colorBuffer.length/4);
326
+ let transparentIndex = colors.length;
327
+ let i = 0, j = 0;
328
+
329
+ while (i < colorBuffer.length) {
330
+ if (colorBuffer[i + 3] !== 0) {
331
+ const color = (colorBuffer.readUInt32BE(i, true) >> 8) & 0xFFFFFF;
332
+ // caller guarantees that the color will be in the palette
333
+ indexBuffer[j] = colorToIndexFunc(colors, color);
334
+ }
335
+ else {
336
+ indexBuffer[j] = transparentIndex;
337
+ }
338
+ i += 4; // skip alpha
339
+ ++j;
340
+ }
341
+
342
+ if (palette.usesTransparency) {
343
+ if (transparentIndex === 256) {
344
+ throw new GifError(`Frame ${frameIndex} already has 256 colors` +
345
+ `and so can't use transparency`);
346
+ }
347
+ }
348
+ else {
349
+ transparentIndex = null;
350
+ }
351
+
352
+ return { buffer: indexBuffer, transparentIndex };
353
+ }
354
+
355
+ function _getPixelBitWidth(palette) {
356
+ let indexCount = palette.indexCount;
357
+ let pixelBitWidth = 0;
358
+ --indexCount; // start at maximum index
359
+ while (indexCount) {
360
+ ++pixelBitWidth;
361
+ indexCount >>= 1;
362
+ }
363
+ return (pixelBitWidth > 0 ? pixelBitWidth : 1);
364
+ }
365
+
366
+ function _writeFrame(gifWriter, frameIndex, frame, palette, isLocalPalette) {
367
+ if (frame.interlaced) {
368
+ throw new GifError("writing interlaced GIFs is not supported");
369
+ }
370
+ const frameInfo = _getIndexedImage(frameIndex, frame, palette);
371
+ const options = {
372
+ delay: frame.delayCentisecs,
373
+ disposal: frame.disposalMethod,
374
+ transparent: frameInfo.transparentIndex
375
+ };
376
+ if (isLocalPalette) {
377
+ _extendPaletteToPowerOf2(palette); // ok 'cause palette never used again
378
+ options.palette = palette.colors;
379
+ }
380
+ try {
381
+ let buffer = gifWriter.getOutputBuffer();
382
+ let startOfFrame = gifWriter.getOutputBufferPosition();
383
+ let endOfFrame;
384
+ let tryAgain = true;
385
+
386
+ while (tryAgain) {
387
+ endOfFrame = gifWriter.addFrame(frame.xOffset, frame.yOffset,
388
+ frame.bitmap.width, frame.bitmap.height, frameInfo.buffer, options);
389
+ tryAgain = false;
390
+ if (endOfFrame >= buffer.length - 1) {
391
+ const biggerBuffer = new Buffer(buffer.length * 1.5);
392
+ buffer.copy(biggerBuffer);
393
+ gifWriter.setOutputBuffer(biggerBuffer);
394
+ gifWriter.setOutputBufferPosition(startOfFrame);
395
+ buffer = biggerBuffer;
396
+ tryAgain = true;
397
+ }
398
+ }
399
+ return buffer;
400
+ }
401
+ catch (err) {
402
+ throw new GifError(err);
403
+ }
404
+ }
node_modules/gifwrap/src/gifframe.js ADDED
@@ -0,0 +1,114 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 'use strict';
2
+
3
+ const BitmapImage = require('./bitmapimage');
4
+ const { GifError } = require('./gif');
5
+
6
+ /** @class GifFrame */
7
+
8
+ class GifFrame extends BitmapImage {
9
+
10
+ // xOffset - x offset of bitmap on GIF (defaults to 0)
11
+ // yOffset - y offset of bitmap on GIF (defaults to 0)
12
+ // disposalMethod - pixel disposal method when handling partial images
13
+ // delayCentisecs - duration of frame in hundredths of a second
14
+ // interlaced - whether the image is interlaced (defaults to false)
15
+
16
+ /**
17
+ * GifFrame is a class representing an image frame of a GIF. GIFs contain one or more instances of GifFrame.
18
+ *
19
+ * Property | Description
20
+ * --- | ---
21
+ * xOffset | x-coord of position within GIF at which to render the image (defaults to 0)
22
+ * yOffset | y-coord of position within GIF at which to render the image (defaults to 0)
23
+ * disposalMethod | GIF disposal method; only relevant when the frames aren't all the same size (defaults to 2, disposing to background color)
24
+ * delayCentisecs | duration of the frame in hundreths of a second
25
+ * interlaced | boolean indicating whether the frame renders interlaced
26
+ *
27
+ * Its constructor supports the following signatures:
28
+ *
29
+ * * new GifFrame(bitmap: {width: number, height: number, data: Buffer}, options?)
30
+ * * new GifFrame(bitmapImage: BitmapImage, options?)
31
+ * * new GifFrame(width: number, height: number, buffer: Buffer, options?)
32
+ * * new GifFrame(width: number, height: number, backgroundRGBA?: number, options?)
33
+ * * new GifFrame(frame: GifFrame)
34
+ *
35
+ * See the base class BitmapImage for a discussion of all parameters but `options` and `frame`. `options` is an optional argument providing initial values for the above-listed GifFrame properties. Each property within option is itself optional.
36
+ *
37
+ * Provide a `frame` to the constructor to create a clone of the provided frame. The new frame includes a copy of the provided frame's pixel data so that each can subsequently be modified without affecting each other.
38
+ */
39
+
40
+ constructor(...args) {
41
+ super(...args);
42
+ if (args[0] instanceof GifFrame) {
43
+ // copy a provided GifFrame
44
+ const source = args[0];
45
+ this.xOffset = source.xOffset;
46
+ this.yOffset = source.yOffset;
47
+ this.disposalMethod = source.disposalMethod;
48
+ this.delayCentisecs = source.delayCentisecs;
49
+ this.interlaced = source.interlaced;
50
+ }
51
+ else {
52
+ const lastArg = args[args.length - 1];
53
+ let options = {};
54
+ if (typeof lastArg === 'object' && !(lastArg instanceof BitmapImage)) {
55
+ options = lastArg;
56
+ }
57
+ this.xOffset = options.xOffset || 0;
58
+ this.yOffset = options.yOffset || 0;
59
+ this.disposalMethod = (options.disposalMethod !== undefined ?
60
+ options.disposalMethod : GifFrame.DisposeToBackgroundColor);
61
+ this.delayCentisecs = options.delayCentisecs || 8;
62
+ this.interlaced = options.interlaced || false;
63
+ }
64
+ }
65
+
66
+ /**
67
+ * Get a summary of the colors found within the frame. The return value is an object of the following form:
68
+ *
69
+ * Property | Description
70
+ * --- | ---
71
+ * colors | An array of all the opaque colors found within the frame. Each color is given as an RGB number of the form 0xRRGGBB. The array is sorted by increasing number. Will be an empty array when the image is completely transparent.
72
+ * usesTransparency | boolean indicating whether there are any transparent pixels within the frame. A pixel is considered transparent if its alpha value is 0x00.
73
+ * indexCount | The number of color indexes required to represent this palette of colors. It is equal to the number of opaque colors plus one if the image includes transparency.
74
+ *
75
+ * @return {object} An object representing a color palette as described above.
76
+ */
77
+
78
+ getPalette() {
79
+ // returns with colors sorted low to high
80
+ const colorSet = new Set();
81
+ const buf = this.bitmap.data;
82
+ let i = 0;
83
+ let usesTransparency = false;
84
+ while (i < buf.length) {
85
+ if (buf[i + 3] === 0) {
86
+ usesTransparency = true;
87
+ }
88
+ else {
89
+ // can eliminate the bitshift by starting one byte prior
90
+ const color = (buf.readUInt32BE(i, true) >> 8) & 0xFFFFFF;
91
+ colorSet.add(color);
92
+ }
93
+ i += 4; // skip alpha
94
+ }
95
+ const colors = new Array(colorSet.size);
96
+ const iter = colorSet.values();
97
+ for (i = 0; i < colors.length; ++i) {
98
+ colors[i] = iter.next().value;
99
+ }
100
+ colors.sort((a, b) => (a - b));
101
+ let indexCount = colors.length;
102
+ if (usesTransparency) {
103
+ ++indexCount;
104
+ }
105
+ return { colors, usesTransparency, indexCount };
106
+ }
107
+ }
108
+
109
+ GifFrame.DisposeToAnything = 0;
110
+ GifFrame.DisposeNothing = 1;
111
+ GifFrame.DisposeToBackgroundColor = 2;
112
+ GifFrame.DisposeToPrevious = 3;
113
+
114
+ exports.GifFrame = GifFrame;
node_modules/gifwrap/src/gifutil.js ADDED
@@ -0,0 +1,373 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 'use strict';
2
+
3
+ /** @namespace GifUtil */
4
+
5
+ const fs = require('fs');
6
+ const ImageQ = require('image-q');
7
+
8
+ const BitmapImage = require('./bitmapimage');
9
+ const { GifFrame } = require('./gifframe');
10
+ const { GifError } = require('./gif');
11
+ const { GifCodec } = require('./gifcodec');
12
+
13
+ const INVALID_SUFFIXES = ['.jpg', '.jpeg', '.png', '.bmp'];
14
+
15
+ const defaultCodec = new GifCodec();
16
+
17
+ /**
18
+ * cloneFrames() clones provided frames. It's a utility method for cloning an entire array of frames at once.
19
+ *
20
+ * @function cloneFrames
21
+ * @memberof GifUtil
22
+ * @param {GifFrame[]} frames An array of GifFrame instances to clone
23
+ * @return {GifFrame[]} An array of GifFrame clones of the provided frames.
24
+ */
25
+
26
+ exports.cloneFrames = function (frames) {
27
+ let clones = [];
28
+ frames.forEach(frame => {
29
+
30
+ clones.push(new GifFrame(frame));
31
+ });
32
+ return clones;
33
+ }
34
+
35
+ /**
36
+ * getColorInfo() gets information about the colors used in the provided frames. The method is able to return an array of all colors found across all frames.
37
+ *
38
+ * `maxGlobalIndex` controls whether the computation short-circuits to avoid doing work that the caller doesn't need. The method only returns `colors` and `indexCount` for the colors across all frames when the number of indexes required to store the colors and transparency in a GIF (which is the value of `indexCount`) is less than or equal to `maxGlobalIndex`. Such short-circuiting is useful when the caller just needs to determine whether any frame includes transparency.
39
+ *
40
+ * @function getColorInfo
41
+ * @memberof GifUtil
42
+ * @param {GifFrame[]} frames Frames to examine for color and transparency.
43
+ * @param {number} maxGlobalIndex Maximum number of color indexes (including one for transparency) allowed among the returned compilation of colors. `colors` and `indexCount` are not returned if the number of color indexes required to accommodate all frames exceeds this number. Returns `colors` and `indexCount` by default.
44
+ * @returns {object} Object containing at least `palettes` and `usesTransparency`. `palettes` is an array of all the palettes returned by GifFrame#getPalette(). `usesTransparency` indicates whether at least one frame uses transparency. If `maxGlobalIndex` is not exceeded, the object also contains `colors`, an array of all colors (RGB) found across all palettes, sorted by increasing value, and `indexCount` indicating the number of indexes required to store the colors and the transparency in a GIF.
45
+ * @throws {GifError} When any frame requires more than 256 color indexes.
46
+ */
47
+
48
+ exports.getColorInfo = function (frames, maxGlobalIndex) {
49
+ let usesTransparency = false;
50
+ const palettes = [];
51
+ for (let i = 0; i < frames.length; ++i) {
52
+ let palette = frames[i].getPalette();
53
+ if (palette.usesTransparency) {
54
+ usesTransparency = true;
55
+ }
56
+ if (palette.indexCount > 256) {
57
+ throw new GifError(`Frame ${i} uses more than 256 color indexes`);
58
+ }
59
+ palettes.push(palette);
60
+ }
61
+ if (maxGlobalIndex === 0) {
62
+ return { usesTransparency, palettes };
63
+ }
64
+
65
+ const globalColorSet = new Set();
66
+ palettes.forEach(palette => {
67
+
68
+ palette.colors.forEach(color => {
69
+
70
+ globalColorSet.add(color);
71
+ });
72
+ });
73
+ let indexCount = globalColorSet.size;
74
+ if (usesTransparency) {
75
+ // odd that GIF requires a color table entry at transparent index
76
+ ++indexCount;
77
+ }
78
+ if (maxGlobalIndex && indexCount > maxGlobalIndex) {
79
+ return { usesTransparency, palettes };
80
+ }
81
+
82
+ const colors = new Array(globalColorSet.size);
83
+ const iter = globalColorSet.values();
84
+ for (let i = 0; i < colors.length; ++i) {
85
+ colors[i] = iter.next().value;
86
+ }
87
+ colors.sort((a, b) => (a - b));
88
+ return { colors, indexCount, usesTransparency, palettes };
89
+ };
90
+
91
+ /**
92
+ * copyAsJimp() returns a Jimp that contains a copy of the provided bitmap image (which may be either a BitmapImage or a GifFrame). Modifying the Jimp does not affect the provided bitmap image. This method serves as a macro for simplifying working with Jimp.
93
+ *
94
+ * @function copyAsJimp
95
+ * @memberof GifUtil
96
+ * @param {object} Reference to the Jimp package, keeping this library from being dependent on Jimp.
97
+ * @param {bitmapImageToCopy} Instance of BitmapImage (may be a GifUtil) with which to source the Jimp.
98
+ * @return {object} An new instance of Jimp containing a copy of the image in bitmapImageToCopy.
99
+ */
100
+
101
+ exports.copyAsJimp = function (jimp, bitmapImageToCopy) {
102
+ return exports.shareAsJimp(jimp, new BitmapImage(bitmapImageToCopy));
103
+ };
104
+
105
+ /**
106
+ * getMaxDimensions() returns the pixel width and height required to accommodate all of the provided frames, according to the offsets and dimensions of each frame.
107
+ *
108
+ * @function getMaxDimensions
109
+ * @memberof GifUtil
110
+ * @param {GifFrame[]} frames Frames to measure for their aggregate maximum dimensions.
111
+ * @return {object} An object of the form {maxWidth, maxHeight} indicating the maximum width and height required to accommodate all frames.
112
+ */
113
+
114
+ exports.getMaxDimensions = function (frames) {
115
+ let maxWidth = 0, maxHeight = 0;
116
+ frames.forEach(frame => {
117
+ const width = frame.xOffset + frame.bitmap.width;
118
+ if (width > maxWidth) {
119
+ maxWidth = width;
120
+ }
121
+ const height = frame.yOffset + frame.bitmap.height;
122
+ if (height > maxHeight) {
123
+ maxHeight = height;
124
+ }
125
+ });
126
+ return { maxWidth, maxHeight };
127
+ };
128
+
129
+ /**
130
+ * Quantizes colors so that there are at most a given number of color indexes (including transparency) across all provided images. Uses an algorithm by Anthony Dekker.
131
+ *
132
+ * The method treats different RGBA combinations as different colors, so if the frame has multiple alpha values or multiple RGB values for an alpha value, the caller may first want to normalize them by converting all transparent pixels to the same RGBA values.
133
+ *
134
+ * The method may increase the number of colors if there are fewer than the provided maximum.
135
+ *
136
+ * @function quantizeDekker
137
+ * @memberof GifUtil
138
+ * @param {BitmapImage|BitmapImage[]} imageOrImages Image or array of images (such as GifFrame instances) to be color-quantized. Quantizing across multiple images ensures color consistency from frame to frame.
139
+ * @param {number} maxColorIndexes The maximum number of color indexes that will exist in the palette after completing quantization. Defaults to 256.
140
+ * @param {object} dither (optional) An object configuring the dithering to apply. The properties are as followings, imported from the [`image-q` package](https://github.com/ibezkrovnyi/image-quantization) without explanation: { `ditherAlgorithm`: One of 'FloydSteinberg', 'FalseFloydSteinberg', 'Stucki', 'Atkinson', 'Jarvis', 'Burkes', 'Sierra', 'TwoSierra', 'SierraLite'; `minimumColorDistanceToDither`: (optional) A number defaulting to 0; `serpentine`: (optional) A boolean defaulting to true; `calculateErrorLikeGIMP`: (optional) A boolean defaulting to false. }
141
+ */
142
+
143
+ exports.quantizeDekker = function (imageOrImages, maxColorIndexes, dither) {
144
+ maxColorIndexes = maxColorIndexes || 256;
145
+ _quantize(imageOrImages, 'NeuQuantFloat', maxColorIndexes, 0, dither);
146
+ }
147
+
148
+ /**
149
+ * Quantizes colors so that there are at most a given number of color indexes (including transparency) across all provided images. Uses an algorithm by Leon Sorokin. This quantization method differs from the other two by likely never increasing the number of colors, should there be fewer than the provided maximum.
150
+ *
151
+ * The method treats different RGBA combinations as different colors, so if the frame has multiple alpha values or multiple RGB values for an alpha value, the caller may first want to normalize them by converting all transparent pixels to the same RGBA values.
152
+ *
153
+ * @function quantizeSorokin
154
+ * @memberof GifUtil
155
+ * @param {BitmapImage|BitmapImage[]} imageOrImages Image or array of images (such as GifFrame instances) to be color-quantized. Quantizing across multiple images ensures color consistency from frame to frame.
156
+ * @param {number} maxColorIndexes The maximum number of color indexes that will exist in the palette after completing quantization. Defaults to 256.
157
+ * @param {string} histogram (optional) Histogram method: 'top-pop' for global top-population, 'min-pop' for minimum-population threshhold within subregions. Defaults to 'min-pop'.
158
+ * @param {object} dither (optional) An object configuring the dithering to apply, as explained for `quantizeDekker()`.
159
+ */
160
+
161
+ exports.quantizeSorokin = function (imageOrImages, maxColorIndexes, histogram, dither) {
162
+ maxColorIndexes = maxColorIndexes || 256;
163
+ histogram = histogram || 'min-pop';
164
+ let histogramID;
165
+ switch (histogram) {
166
+ case 'min-pop':
167
+ histogramID = 2;
168
+ break;
169
+
170
+ case 'top-pop':
171
+ histogramID = 1;
172
+ break
173
+
174
+ default:
175
+ throw new Error(`Invalid quantizeSorokin histogram '${histogram}'`);
176
+ }
177
+ _quantize(imageOrImages, 'RGBQuant', maxColorIndexes, histogramID, dither);
178
+ }
179
+
180
+ /**
181
+ * Quantizes colors so that there are at most a given number of color indexes (including transparency) across all provided images. Uses an algorithm by Xiaolin Wu.
182
+ *
183
+ * The method treats different RGBA combinations as different colors, so if the frame has multiple alpha values or multiple RGB values for an alpha value, the caller may first want to normalize them by converting all transparent pixels to the same RGBA values.
184
+ *
185
+ * The method may increase the number of colors if there are fewer than the provided maximum.
186
+ *
187
+ * @function quantizeWu
188
+ * @memberof GifUtil
189
+ * @param {BitmapImage|BitmapImage[]} imageOrImages Image or array of images (such as GifFrame instances) to be color-quantized. Quantizing across multiple images ensures color consistency from frame to frame.
190
+ * @param {number} maxColorIndexes The maximum number of color indexes that will exist in the palette after completing quantization. Defaults to 256.
191
+ * @param {number} significantBits (optional) This is the number of significant high bits in each RGB color channel. Takes integer values from 1 through 8. Higher values correspond to higher quality. Defaults to 5.
192
+ * @param {object} dither (optional) An object configuring the dithering to apply, as explained for `quantizeDekker()`.
193
+ */
194
+
195
+ exports.quantizeWu = function (imageOrImages, maxColorIndexes, significantBits, dither) {
196
+ maxColorIndexes = maxColorIndexes || 256;
197
+ significantBits = significantBits || 5;
198
+ if (significantBits < 1 || significantBits > 8) {
199
+ throw new Error("Invalid quantization quality");
200
+ }
201
+ _quantize(imageOrImages, 'WuQuant', maxColorIndexes, significantBits, dither);
202
+ }
203
+
204
+ /**
205
+ * read() decodes an encoded GIF, whether provided as a filename or as a byte buffer.
206
+ *
207
+ * @function read
208
+ * @memberof GifUtil
209
+ * @param {string|Buffer} source Source to decode. When a string, it's the GIF filename to load and parse. When a Buffer, it's an encoded GIF to parse.
210
+ * @param {object} decoder An optional GIF decoder object implementing the `decode` method of class GifCodec. When provided, the method decodes the GIF using this decoder. When not provided, the method uses GifCodec.
211
+ * @return {Promise} A Promise that resolves to an instance of the Gif class, representing the decoded GIF.
212
+ */
213
+
214
+ exports.read = function (source, decoder) {
215
+ decoder = decoder || defaultCodec;
216
+ if (Buffer.isBuffer(source)) {
217
+ return decoder.decodeGif(source);
218
+ }
219
+ return _readBinary(source)
220
+ .then(buffer => {
221
+
222
+ return decoder.decodeGif(buffer);
223
+ });
224
+ };
225
+
226
+ /**
227
+ * shareAsJimp() returns a Jimp that shares a bitmap with the provided bitmap image (which may be either a BitmapImage or a GifFrame). Modifying the image in either the Jimp or the BitmapImage affects the other objects. This method serves as a macro for simplifying working with Jimp.
228
+ *
229
+ * @function shareAsJimp
230
+ * @memberof GifUtil
231
+ * @param {object} Reference to the Jimp package, keeping this library from being dependent on Jimp.
232
+ * @param {bitmapImageToShare} Instance of BitmapImage (may be a GifUtil) with which to source the Jimp.
233
+ * @return {object} An new instance of Jimp that shares the image in bitmapImageToShare.
234
+ */
235
+
236
+ exports.shareAsJimp = function (jimp, bitmapImageToShare) {
237
+ const jimpImage = new jimp(bitmapImageToShare.bitmap.width,
238
+ bitmapImageToShare.bitmap.height, 0);
239
+ jimpImage.bitmap.data = bitmapImageToShare.bitmap.data;
240
+ return jimpImage;
241
+ };
242
+
243
+ /**
244
+ * write() encodes a GIF and saves it as a file.
245
+ *
246
+ * @function write
247
+ * @memberof GifUtil
248
+ * @param {string} path Filename to write GIF out as. Will overwrite an existing file.
249
+ * @param {GifFrame[]} frames Array of frames to be written into GIF.
250
+ * @param {object} spec An optional object that may provide values for `loops` and `colorScope`, as defined for the Gif class. However, `colorSpace` may also take the value Gif.GlobalColorsPreferred (== 0) to indicate that the encoder should attempt to create only a global color table. `loop` defaults to 0, looping indefinitely, and `colorScope` defaults to Gif.GlobalColorsPreferred.
251
+ * @param {object} encoder An optional GIF encoder object implementing the `encode` method of class GifCodec. When provided, the method encodes the GIF using this encoder. When not provided, the method uses GifCodec.
252
+ * @return {Promise} A Promise that resolves to an instance of the Gif class, representing the encoded GIF.
253
+ */
254
+
255
+ exports.write = function (path, frames, spec, encoder) {
256
+ encoder = encoder || defaultCodec;
257
+ const matches = path.match(/\.[a-zA-Z]+$/); // prevent accidents
258
+ if (matches !== null &&
259
+ INVALID_SUFFIXES.includes(matches[0].toLowerCase()))
260
+ {
261
+ throw new Error(`GIF '${path}' has an unexpected suffix`);
262
+ }
263
+
264
+ return encoder.encodeGif(frames, spec)
265
+ .then(gif => {
266
+
267
+ return _writeBinary(path, gif.buffer)
268
+ .then(() => {
269
+
270
+ return gif;
271
+ });
272
+ });
273
+ };
274
+
275
+ function _quantize(imageOrImages, method, maxColorIndexes, modifier, dither) {
276
+ const images = Array.isArray(imageOrImages) ? imageOrImages : [imageOrImages];
277
+ const ditherAlgs = [
278
+ 'FloydSteinberg',
279
+ 'FalseFloydSteinberg',
280
+ 'Stucki',
281
+ 'Atkinson',
282
+ 'Jarvis',
283
+ 'Burkes',
284
+ 'Sierra',
285
+ 'TwoSierra',
286
+ 'SierraLite'
287
+ ];
288
+
289
+ if (dither) {
290
+ if (ditherAlgs.indexOf(dither.ditherAlgorithm) < 0) {
291
+ throw new Error(`Invalid ditherAlgorithm '${dither.ditherAlgorithm}'`);
292
+ }
293
+ if (dither.serpentine === undefined) {
294
+ dither.serpentine = true;
295
+ }
296
+ if (dither.minimumColorDistanceToDither === undefined) {
297
+ dither.minimumColorDistanceToDither = 0;
298
+ }
299
+ if (dither.calculateErrorLikeGIMP === undefined) {
300
+ dither.calculateErrorLikeGIMP = false;
301
+ }
302
+ }
303
+
304
+ const distCalculator = new ImageQ.distance.Euclidean();
305
+ const quantizer = new ImageQ.palette[method](distCalculator, maxColorIndexes, modifier);
306
+ let imageMaker;
307
+ if (dither) {
308
+ imageMaker = new ImageQ.image.ErrorDiffusionArray(
309
+ distCalculator,
310
+ ImageQ.image.ErrorDiffusionArrayKernel[dither.ditherAlgorithm],
311
+ dither.serpentine,
312
+ dither.minimumColorDistanceToDither,
313
+ dither.calculateErrorLikeGIMP
314
+ );
315
+ }
316
+ else {
317
+ imageMaker = new ImageQ.image.NearestColor(distCalculator);
318
+ }
319
+
320
+ const inputContainers = [];
321
+ images.forEach(image => {
322
+
323
+ const imageBuf = image.bitmap.data;
324
+ const inputBuf = new ArrayBuffer(imageBuf.length);
325
+ const inputArray = new Uint32Array(inputBuf);
326
+ for (let bi = 0, ai = 0; bi < imageBuf.length; bi += 4, ++ai) {
327
+ inputArray[ai] = imageBuf.readUInt32LE(bi, true);
328
+ }
329
+ const inputContainer = ImageQ.utils.PointContainer.fromUint32Array(
330
+ inputArray, image.bitmap.width, image.bitmap.height);
331
+ quantizer.sample(inputContainer);
332
+ inputContainers.push(inputContainer);
333
+ });
334
+
335
+ const limitedPalette = quantizer.quantizeSync();
336
+
337
+ for (let i = 0; i < images.length; ++i) {
338
+ const imageBuf = images[i].bitmap.data;
339
+ const outputContainer = imageMaker.quantizeSync(inputContainers[i], limitedPalette);
340
+ const outputArray = outputContainer.toUint32Array();
341
+ for (let bi = 0, ai = 0; bi < imageBuf.length; bi += 4, ++ai) {
342
+ imageBuf.writeUInt32LE(outputArray[ai], bi);
343
+ }
344
+ }
345
+ }
346
+
347
+ function _readBinary(path) {
348
+ // TBD: add support for URLs
349
+ return new Promise((resolve, reject) => {
350
+
351
+ fs.readFile(path, (err, buffer) => {
352
+
353
+ if (err) {
354
+ return reject(err);
355
+ }
356
+ return resolve(buffer);
357
+ });
358
+ });
359
+ }
360
+
361
+ function _writeBinary(path, buffer) {
362
+ // TBD: add support for URLs
363
+ return new Promise((resolve, reject) => {
364
+
365
+ fs.writeFile(path, buffer, err => {
366
+
367
+ if (err) {
368
+ return reject(err);
369
+ }
370
+ return resolve();
371
+ });
372
+ });
373
+ }
node_modules/gifwrap/src/index.js ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 'use strict';
2
+
3
+ const BitmapImage = require('./bitmapimage');
4
+ const { Gif, GifError } = require('./gif');
5
+ const { GifCodec } = require('./gifcodec');
6
+ const { GifFrame } = require('./gifframe');
7
+ const GifUtil = require('./gifutil');
8
+
9
+ module.exports = {
10
+ BitmapImage,
11
+ Gif,
12
+ GifCodec,
13
+ GifFrame,
14
+ GifUtil,
15
+ GifError
16
+ };
node_modules/gifwrap/src/omggif.d.ts ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ export type ByteArray = Uint8Array | Buffer;
3
+
4
+ export interface OmggifModule {
5
+ GifWriter: GifWriter;
6
+ GifReader: GifReader;
7
+ }
8
+
9
+ export interface GlobalOptions {
10
+ loop?: number; // 0 = unending loop; n > 0 = (n+1) iterations; null = once
11
+ palette?: number[]; // global palette RGB by color index
12
+ background?: number; // background index; most browsers may ignore this
13
+ }
14
+
15
+ export interface FrameOptions {
16
+ palette?: number[]; // RGB by color index
17
+ delay?: number; // duation in 100s of a second
18
+ disposal?: number; // what to do with background color (0-3)
19
+ transparent?: number; // transparency index
20
+ }
21
+
22
+ export interface GifWriter {
23
+ new (buffer: ByteArray, width: number, height: number, gopts?: GlobalOptions): GifWriter;
24
+ addFrame(x: number, y: number, width: number, height: number, indexedPixels: number[], opts?: FrameOptions): number; // returns size of buffer at end of frame
25
+ getOutputBuffer(): ByteArray;
26
+ setOutputBuffer(buffer: ByteArray): void;
27
+ getOutputBufferPosition(): number;
28
+ setOutputBufferPosition(position: number): void;
29
+ end(): number; // ends GIF and returns size of buffer
30
+ }
31
+
32
+ export interface GifReader {
33
+ width: number;
34
+ height: number;
35
+ new (buffer: ByteArray): GifReader;
36
+ numFrames(): number;
37
+ loopCount(): number;
38
+ frameInfo(frameNumber: number): FrameInfo;
39
+ decodeAndBlitFrameBGRA(frameNumber: number, pixels: number[]): void;
40
+ decodeAndBlitFrameRGBA(frameNumber: number, pixels: number[]): void;
41
+ }
42
+
43
+ export interface FrameInfo {
44
+ x: number;
45
+ y: number;
46
+ width: number;
47
+ height: number;
48
+ has_local_palette: boolean;
49
+ palette_offset: number;
50
+ data_offset: number;
51
+ data_length: number;
52
+ transparent_index: number;
53
+ interlaced: boolean;
54
+ delay: number; // 100ths of a second
55
+ disposal: number;
56
+ }
node_modules/gifwrap/templates/README.hbs ADDED
@@ -0,0 +1,267 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # gifwrap
2
+
3
+ A Jimp-compatible library for working with GIFs
4
+
5
+ ## Overview
6
+
7
+ `gifwrap` is a minimalist library for working with GIFs in Javascript, supporting both single- and multi-frame GIFs. It reads GIFs into an internal representation that's easy to work with and allows for making GIFs from scratch. The frame class is structured to make it easy to move images between [`Jimp`](https://github.com/oliver-moran/jimp) and `gifwrap` for more sophisticated image manipulation in `Jimp`, but the module has no dependency on `Jimp`.
8
+
9
+ The library uses Dean McNamee's [`omggif`](https://github.com/deanm/omggif) GIF encoder/decoder by default, but it employs an abstraction that allows using other encoders and decoders as well, once suitably wrapped.
10
+
11
+ At present, the module only works in Node.js. Includes Typescript typings.
12
+
13
+ ## Installation
14
+
15
+ ```
16
+ npm install gifwrap --save
17
+ ```
18
+
19
+ or
20
+
21
+ ```
22
+ yarn add gifwrap
23
+ ```
24
+
25
+ ## Usage
26
+
27
+ You can work with either GIF files or GIF encodings, and you can create GIFs from scratch.
28
+
29
+ The GifFrame class represents a single image frame, and the library largely represents a GIF as an array of GifFrame instances. For example, here is how you create a GIF from scratch:
30
+
31
+ ```js
32
+ const { GifFrame, GifUtil, GifCodec } = require('gifwrap');
33
+ const width = 200, height = 100;
34
+ const frames = [];
35
+
36
+ let frame = new GifFrame(width, height, { delayCentisecs: 10 });
37
+ // modify the pixels at frame.bitmap.data
38
+ frames.push(frame);
39
+ frame = new GifFrame(width, height, { delayCentisecs: 15 });
40
+ // modify the pixels at frame.bitmap.data
41
+ frames.push(frame);
42
+ // add more frames as desired...
43
+
44
+ // to write to a file...
45
+ GifUtil.write("my-creation.gif", frames, { loops: 3 }).then(gif => {
46
+ console.log("written");
47
+ });
48
+
49
+ // to get the byte encoding without writing to a file...
50
+ const codec = new GifCodec();
51
+ codec.encodeGif(frames, { loops: 3 }).then(gif => {
52
+ // byte encoding is now in gif.buffer
53
+ });
54
+
55
+ ```
56
+
57
+ Images are represented within a GifFrame exactly as they are in a `Jimp` image. In particular, each GifFrame instance has a `bitmap` property having the following structure:
58
+
59
+ * `frame.bitmap.width` - Width of image in pixels
60
+ * `frame.bitmap.height` - Height of image in pixels
61
+ * `frame.bitmap.data` - A Node.js Buffer that can be accessed like an array of bytes. Every 4 adjacent bytes represents the RGBA values of a single pixel. These 4 bytes correspond to red, green, blue, and alpha, in that order. Each pixel begins at an index that is a multiple of 4.
62
+
63
+ GIFs do not support partial transparency, so within `frame.bitmap.data`, pixels having alpha value 0x00 are treated as transparent and pixels of non-zero alpha value are treated as opaque. The encoder ignores the RGB values of transparent pixels.
64
+
65
+ `gifwrap` also provides utilities for reading GIF files and for parsing raw encodings:
66
+
67
+ ```js
68
+ const { GifUtil } = require('gifwrap');
69
+ GifUtil.read("fancy.gif").then(inputGif => {
70
+
71
+ inputGif.frames.forEach(frame => {
72
+
73
+ const buf = frame.bitmap.data;
74
+ frame.scanAllCoords((x, y, bi) => {
75
+
76
+ // Halve all grays on right half of image.
77
+
78
+ if (x > inputGif.width / 2) {
79
+ const r = buf[bi];
80
+ const g = buf[bi + 1];
81
+ const b = buf[bi + 2];
82
+ const a = buf[bi + 3];
83
+ if (r === g && r === b && a === 0xFF) {
84
+ buf[bi] /= 2;
85
+ buf[bi + 1] /= 2;
86
+ buf[bi + 2] /= 2;
87
+ }
88
+ }
89
+ });
90
+ });
91
+
92
+ // Pass inputGif to write() to preserve the original GIF's specs.
93
+ return GifUtil.write("modified.gif", inputGif.frames, inputGif).then(outputGif => {
94
+ console.log("modified");
95
+ });
96
+ });
97
+ ```
98
+
99
+ ```js
100
+ const { GifUtil, GifCodec } = require('gifwrap');
101
+ const codec = new GifCodec();
102
+ const byteEncodingBuffer = getByteEncodingForSomeGif();
103
+
104
+ codec.decodeGif(byteEncodingBuffer).then(sourceGif => {
105
+
106
+ const edgeLength = Math.min(sourceGif.width, sourceGif.height);
107
+ sourceGif.frames.forEach(frame => {
108
+
109
+ // Make each frame a centered square of size edgeLength x edgeLength.
110
+ // Note that frames may vary in size and that reframe() works even if
111
+ // the frame's image is smaller than the square. Should this happen,
112
+ // the space surrounding the original image will be transparent.
113
+
114
+ const xOffset = (frame.bitmap.width - edgeLength)/2;
115
+ const yOffset = (frame.bitmap.height - edgeLength)/2;
116
+ frame.reframe(xOffset, yOffset, edgeLength, edgeLength);
117
+ });
118
+
119
+ // The encoder determines GIF size from the frames, not the provided spec (sourceGif).
120
+ return GifUtil.write("modified.gif", sourceGif.frames, sourceGif).then(outputGif => {
121
+ console.log("modified");
122
+ });
123
+ });
124
+ ```
125
+
126
+ Notice that both encoding and decoding yields a GIF object. This is an instance of class Gif, and it provides information about the GIF, such as its size and how many times it loops. Notice also that you never call the Gif constructor to create a GIF. Instead, GIFs are created by providing a GifFrame array and a specification of GIF options. That specification is a subset of the properties of a Gif, so you can pass a previously-loaded Gif as a specification when writing or encoding. The encoder only uses the properties that can't be inferred from the frames -- namely, how many times the GIF loops and how to attempt to package the color tables within the encoding.
127
+
128
+ ## Leveraging Jimp
129
+
130
+ This module was originally written as a wrapper around Jimp images -- hence its name -- and then with frames as subclasses of Jimp images. Neither approach worked out well. The final approach requires just a tad of legwork to use `gifwrap` images within Jimp.
131
+
132
+ Both Jimp images and GifFrame instances share the `bitmap` property. By transferring this property back and forth between Jimp images and GifFrame instances, an image can be moved back and forth between the two libraries.
133
+
134
+ You can construct a GifFrame from a Jimp image as follows:
135
+
136
+ ```js
137
+ const { BitmapImage, GifFrame } = require('gifwrap');
138
+ const Jimp = require('jimp');
139
+ const j = new Jimp(200, 100, 0xFFFFFFFF);
140
+
141
+ // create a frame clone of a Jip bitmap
142
+ const fCopied = new GifFrame(new BitmapImage(j.bitmap));
143
+
144
+ // create a frame that shares a bitmap with Jimp (one way)
145
+ const fShared1 = new GifFrame(j.bitmap);
146
+
147
+ // create a frame that shares a bitmap with Jimp (another way)
148
+ const fShared2 = new GifFrame(1, 1, 0); // any GifFrame
149
+ fShared2.bitmap = j.bitmap;
150
+ ```
151
+
152
+ And you can construct a Jimp instance from a GifFrame image as follows:
153
+
154
+ ```js
155
+ const { BitmapImage, GifFrame } = require('gifwrap');
156
+ const Jimp = require('jimp');
157
+ const frame = new GifFrame(200, 100, 0xFFFFFFFF);
158
+
159
+ // create a Jimp containing a clone of the frame bitmap
160
+ jimpCopied = GifUtil.copyAsJimp(Jimp, frame);
161
+
162
+ // create a Jimp that shares a bitmap with the frame
163
+ jimpShared = GifUtil.shareAsJimp(Jimp, frame);
164
+ ```
165
+
166
+ ## Encoders and Decoders
167
+
168
+ `gifwrap` provides a default GIF encoder/decoder, but it is architected to be able to work with other encoders and decoders. The encoder and decoder may even be separate implementations. Encoders and decoders have varying capabilities, performance measures, and levels of reliability.
169
+
170
+ GifCodec is the default implementation, and it's both an encoder and a decoder. It's an adapter that wraps the [`omggif`](https://github.com/deanm/omggif) module. `omggif` appears to support a broad variety of GIFs, although it cannot produce an interlaced encoding (which there is little need for anyway). Although `omggif` doesn't include a test suite at present, `gifwrap`'s test suite happens to test it reasonably well by virtue of using `omggif` underneath.
171
+
172
+ An encoder need only implement GifCodec's [`encodeGif()`](#GifCodec+encodeGif) method, and a decoder need only implement its [`decodeGif()`](#GifCodec+decodeGif) method. See the descriptions of those methods for the requirement details. Although GifCodec is stateless, so that instances an be reused across multiple encodings and decodings, third party encoders and decoders need not be. However, applications that use the library with stateful encoders will need to be aware of the need to create new instances.
173
+
174
+ To use a third-party encoder or decoder with the GifUtil `write()` and `read()` functions, just pass an instance of the encoder or decoder as the last parameter to `write()` or `read()`, respectively. For example:
175
+
176
+ ```js
177
+ const { GifUtil } = require('gifwrap');
178
+ const SnazzyDecoder = require('gifwrap-snazzy-decoder');
179
+ const AwesomeEncoder = require('gifwrap-awesome-encoder');
180
+
181
+ GifUtil.read("fancy.gif", new SnazzyDecoder()).then(gif =>
182
+
183
+ /*...*/
184
+
185
+ return GifUtil.write("modified.gif", gif.frames, gif, new AwesomeEncoder()).then(newGif => {
186
+ console.log("modified");
187
+ });
188
+ });
189
+ ```
190
+
191
+ ## API Reference
192
+
193
+ The [Typescript typings](https://github.com/jtlapp/gifwrap/blob/master/index.d.ts) provide an exact specification of the API and also serve as a cheat sheet. The classes and namespaces follow:
194
+
195
+ * **gifwrap**
196
+
197
+ * [.**Gif**](#new_Gif_new)
198
+ * [.**BitmapImage**](#BitmapImage)
199
+ * [.**GifFrame**](#GifFrame)
200
+ * [.**GifUtil**](#GifUtil)
201
+ * [.**GifCodec**](#GifCodec)
202
+ * [.**GifError**](#new_GifError_new)
203
+
204
+ {{#class name="Gif"}}
205
+ {{>body~}}
206
+ {{>member-index~}}
207
+ {{/class}}
208
+ {{#class name="BitmapImage"}}
209
+ {{>body~}}
210
+ {{>member-index~}}
211
+ {{/class}}
212
+ {{#class name="GifFrame"}}
213
+ {{>body~}}
214
+ {{>member-index~}}
215
+ {{/class}}
216
+ {{#namespace name="GifUtil"}}
217
+ {{>body~}}
218
+ {{>member-index~}}
219
+ {{/namespace}}
220
+ {{#class name="GifCodec"}}
221
+ {{>body~}}
222
+ {{>member-index~}}
223
+ {{/class}}
224
+
225
+ {{#class name="Gif"}}
226
+ {{>members~}}
227
+ {{/class}}
228
+ {{#class name="BitmapImage"}}
229
+ {{>members~}}
230
+ {{/class}}
231
+ {{#class name="GifFrame"}}
232
+ {{>members~}}
233
+ {{/class}}
234
+ {{#namespace name="GifUtil"}}
235
+ {{>members~}}
236
+ {{/namespace}}
237
+ {{#class name="GifCodec"}}
238
+ {{>members~}}
239
+ {{/class}}
240
+ {{#class name="GifError"}}
241
+ {{>body~}}
242
+ {{>members~}}
243
+ {{/class}}
244
+
245
+ ## LICENSE
246
+
247
+ MIT License
248
+
249
+ Copyright © 2017 Joseph T. Lapp
250
+
251
+ Permission is hereby granted, free of charge, to any person obtaining a copy
252
+ of this software and associated documentation files (the "Software"), to deal
253
+ in the Software without restriction, including without limitation the rights
254
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
255
+ copies of the Software, and to permit persons to whom the Software is
256
+ furnished to do so, subject to the following conditions:
257
+
258
+ The above copyright notice and this permission notice shall be included in all
259
+ copies or substantial portions of the Software.
260
+
261
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
262
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
263
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
264
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
265
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
266
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
267
+ SOFTWARE.
node_modules/gifwrap/test/fixtures/count5x7.gif ADDED
node_modules/gifwrap/test/fixtures/countConstantDelay0.gif ADDED
node_modules/gifwrap/test/fixtures/countConstantDelay1.gif ADDED
node_modules/gifwrap/test/fixtures/countConstantDelay3.gif ADDED
node_modules/gifwrap/test/fixtures/countIncreasingDelay.gif ADDED
node_modules/gifwrap/test/fixtures/hairstreak.jpg ADDED
node_modules/gifwrap/test/fixtures/lenna.png ADDED
node_modules/gifwrap/test/fixtures/nburling-public.gif ADDED
node_modules/gifwrap/test/fixtures/pelagrina.jpg ADDED
node_modules/gifwrap/test/fixtures/penguins.png ADDED
node_modules/gifwrap/test/fixtures/quantized/hairstreak256_Dekker.png ADDED
node_modules/gifwrap/test/fixtures/quantized/hairstreak256_Sorokin.png ADDED
node_modules/gifwrap/test/fixtures/quantized/hairstreak256_Wu.png ADDED
node_modules/gifwrap/test/fixtures/quantized/hairstreak32_Dekker.png ADDED
node_modules/gifwrap/test/fixtures/quantized/hairstreak32_Sorokin.png ADDED
node_modules/gifwrap/test/fixtures/quantized/hairstreak32_Wu.png ADDED
node_modules/gifwrap/test/fixtures/quantized/rosewithtrans256_Dekker.png ADDED
node_modules/gifwrap/test/fixtures/quantized/rosewithtrans256_Sorokin.png ADDED
node_modules/gifwrap/test/fixtures/quantized/rosewithtrans256_Wu.png ADDED
node_modules/gifwrap/test/fixtures/quantized/rosewithtrans32_Dekker.png ADDED
node_modules/gifwrap/test/fixtures/quantized/rosewithtrans32_Sorokin.png ADDED
node_modules/gifwrap/test/fixtures/quantized/rosewithtrans32_Wu.png ADDED
node_modules/gifwrap/test/fixtures/quantized/sculptmap256_Dekker.png ADDED
node_modules/gifwrap/test/fixtures/quantized/sculptmap256_Dekker_FloydSteinberg.png ADDED
node_modules/gifwrap/test/fixtures/quantized/sculptmap256_Sorokin.png ADDED
node_modules/gifwrap/test/fixtures/quantized/sculptmap256_Sorokin_FloydSteinberg.png ADDED
node_modules/gifwrap/test/fixtures/quantized/sculptmap256_Wu.png ADDED
node_modules/gifwrap/test/fixtures/quantized/sculptmap256_Wu_FloydSteinberg.png ADDED
node_modules/gifwrap/test/fixtures/quantized/sculptmap32_Dekker.png ADDED
node_modules/gifwrap/test/fixtures/quantized/sculptmap32_Sorokin.png ADDED
node_modules/gifwrap/test/fixtures/quantized/sculptmap32_Wu.png ADDED