├── .nojekyll
├── .gitignore
├── screenshot.gif
├── .npmignore
├── .editorconfig
├── web_modules
├── _chunks
│ ├── _commonjsHelpers-rKnUJq5k.js
│ └── polyfills-CU6gNi7m.js
├── import-map.json
├── canvas-context.js
└── es-module-shims
│ └── wasm.js
├── LICENSE.md
├── CHANGELOG.md
├── package.json
├── index.html
├── index.js
└── README.md
/.nojekyll:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | node_modules
2 | .DS_Store
3 | /types
4 | /lib
5 |
--------------------------------------------------------------------------------
/screenshot.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/dmnsgn/raf-perf/HEAD/screenshot.gif
--------------------------------------------------------------------------------
/.npmignore:
--------------------------------------------------------------------------------
1 | /web_modules
2 | /examples
3 | /docs
4 | /coverage
5 | /test
6 | /.github
7 | screenshot.*
8 | index.html
9 | tsconfig.json
10 | .editorconfig
11 | .nojekyll
12 |
--------------------------------------------------------------------------------
/.editorconfig:
--------------------------------------------------------------------------------
1 | root = true
2 |
3 | [*]
4 | end_of_line = lf
5 | charset = utf-8
6 | indent_style = space
7 | indent_size = 2
8 | trim_trailing_whitespace = true
9 | insert_final_newline = true
10 |
--------------------------------------------------------------------------------
/web_modules/_chunks/_commonjsHelpers-rKnUJq5k.js:
--------------------------------------------------------------------------------
1 | var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
2 |
3 | export { commonjsGlobal as c };
4 |
--------------------------------------------------------------------------------
/web_modules/import-map.json:
--------------------------------------------------------------------------------
1 | {
2 | "imports": {
3 | "canvas-context": "./canvas-context.js",
4 | "es-module-shims": "./es-module-shims.js",
5 | "es-module-shims/debug": "./es-module-shims/debug.js",
6 | "es-module-shims/wasm": "./es-module-shims/wasm.js"
7 | }
8 | }
9 |
--------------------------------------------------------------------------------
/LICENSE.md:
--------------------------------------------------------------------------------
1 | Copyright (C) 2019 Damien Seguin
2 |
3 | Permission is hereby granted, free of charge, to any person obtaining a copy
4 | of this software and associated documentation files (the "Software"), to deal
5 | in the Software without restriction, including without limitation the rights
6 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7 | copies of the Software, and to permit persons to whom the Software is
8 | furnished to do so, subject to the following conditions:
9 |
10 | The above copyright notice and this permission notice shall be included in
11 | all copies or substantial portions of the Software.
12 |
13 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
19 | THE SOFTWARE.
20 |
--------------------------------------------------------------------------------
/CHANGELOG.md:
--------------------------------------------------------------------------------
1 | # Changelog
2 |
3 | All notable changes to this project will be documented in this file. See [commit-and-tag-version](https://github.com/absolute-version/commit-and-tag-version) for commit guidelines.
4 |
5 | ## [3.0.1](https://github.com/dmnsgn/raf-perf/compare/v3.0.0...v3.0.1) (2024-07-06)
6 |
7 |
8 |
9 | # [3.0.0](https://github.com/dmnsgn/raf-perf/compare/v2.1.0...v3.0.0) (2023-08-15)
10 |
11 |
12 | ### Features
13 |
14 | * removed "events" dependency ([a76c133](https://github.com/dmnsgn/raf-perf/commit/a76c133864d7797460161b32c8206f5b1119b0b3))
15 | * replace events dependency with a simple emit/on Set emitter ([b4197b3](https://github.com/dmnsgn/raf-perf/commit/b4197b3b90f1ddbda78a6f020f576b65310b7383))
16 |
17 |
18 | ### BREAKING CHANGES
19 |
20 | * RafPerf doesn't extends EventEmitter anymore
21 |
22 |
23 |
24 | # [2.1.0](https://github.com/dmnsgn/raf-perf/compare/v2.0.0...v2.1.0) (2021-09-10)
25 |
26 |
27 | ### Features
28 |
29 | * add exports field to package.json ([3390bf0](https://github.com/dmnsgn/raf-perf/commit/3390bf07f0839579961e7c399100bd305e15fa66))
30 |
31 |
32 |
33 | # [2.0.0](https://github.com/dmnsgn/raf-perf/compare/v1.2.0...v2.0.0) (2021-04-10)
34 |
35 |
36 | ### Code Refactoring
37 |
38 | * use ES modules ([09411d2](https://github.com/dmnsgn/raf-perf/commit/09411d29a1dee3e880b6029415a44d5a5f8fd1b4))
39 |
40 |
41 | ### BREAKING CHANGES
42 |
43 | * switch to type module
44 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "raf-perf",
3 | "version": "3.0.1",
4 | "description": "RAF loop with an adaptive fps and performance ratio calculated from either a sample count or a sample duration. Typically used when doing intensive graphics computation in canvas.",
5 | "keywords": [
6 | "raf",
7 | "fps",
8 | "adaptive",
9 | "throttle",
10 | "perf",
11 | "performance",
12 | "tick",
13 | "ticker",
14 | "loop",
15 | "requestanimationframe"
16 | ],
17 | "homepage": "https://github.com/dmnsgn/raf-perf",
18 | "bugs": "https://github.com/dmnsgn/raf-perf/issues",
19 | "repository": {
20 | "type": "git",
21 | "url": "git+https://github.com/dmnsgn/raf-perf.git"
22 | },
23 | "funding": [
24 | {
25 | "type": "individual",
26 | "url": "https://paypal.me/dmnsgn"
27 | },
28 | {
29 | "type": "individual",
30 | "url": "https://commerce.coinbase.com/checkout/56cbdf28-e323-48d8-9c98-7019e72c97f3"
31 | }
32 | ],
33 | "license": "MIT",
34 | "author": "Damien Seguin (https://github.com/dmnsgn)",
35 | "sideEffects": false,
36 | "type": "module",
37 | "exports": {
38 | ".": {
39 | "types": "./types/index.d.ts",
40 | "default": "./index.js"
41 | }
42 | },
43 | "main": "index.js",
44 | "types": "types/index.d.ts",
45 | "devDependencies": {
46 | "canvas-context": "^3.2.0",
47 | "es-module-shims": "^1.10.0"
48 | },
49 | "engines": {
50 | "node": ">=22.0.0",
51 | "npm": ">=10.5.1",
52 | "snowdev": ">=2.2.x"
53 | }
54 | }
55 |
--------------------------------------------------------------------------------
/web_modules/canvas-context.js:
--------------------------------------------------------------------------------
1 | /**
2 | * @module createCanvasContext
3 | */ const contextTypeList = [
4 | "2d",
5 | "webgl",
6 | "experimental-webgl",
7 | "webgl2",
8 | "webgl2-compute",
9 | "bitmaprenderer",
10 | "gpupresent",
11 | "webgpu"
12 | ];
13 | /**
14 | * Create a RenderingContext (2d, webgl, webgl2, bitmaprenderer, webgpu), optionally offscreen for possible use in a Worker.
15 | *
16 | * @alias module:createCanvasContext
17 | * @param {import("./types.js").ContextType} [contextType="2d"]
18 | * @param {import("./types.js").CanvasContextOptions} [options={}]
19 | * @returns {import("./types.js").CanvasContextReturnValue}
20 | */ function createCanvasContext(contextType, options) {
21 | if (contextType === void 0) contextType = "2d";
22 | if (options === void 0) options = {};
23 | // Get options and set defaults
24 | const { width, height, offscreen = false, worker = false, contextAttributes = {} } = {
25 | ...options
26 | };
27 | // Check contextType is valid
28 | if (!worker && !contextTypeList.includes(contextType)) {
29 | throw new TypeError(`Unknown contextType: "${contextType}"`);
30 | }
31 | // Return in Node or in a Worker unless a canvas is provided
32 | // See https://github.com/Automattic/node-canvas for an example
33 | if (typeof window === "undefined" && !options.canvas) {
34 | return null;
35 | }
36 | // Get offscreen canvas if requested and available
37 | const canvasEl = options.canvas || document.createElement("canvas");
38 | const canvas = (offscreen || worker) && "OffscreenCanvas" in window ? canvasEl.transferControlToOffscreen() : canvasEl;
39 | // Set canvas dimensions (default to 300 in browsers)
40 | if (Number.isInteger(width) && width >= 0) canvas.width = width;
41 | if (Number.isInteger(height) && height >= 0) canvas.height = height;
42 | if (worker) return {
43 | canvas
44 | };
45 | // Get the context with specified attributes and handle experimental-webgl
46 | let context;
47 | try {
48 | context = canvas.getContext(contextType, contextAttributes) || (contextType === "webgl" ? canvas.getContext("experimental-webgl", contextAttributes) : null);
49 | } catch (error) {
50 | context = null;
51 | }
52 | return {
53 | canvas,
54 | context
55 | };
56 | }
57 |
58 | export { createCanvasContext as default };
59 |
--------------------------------------------------------------------------------
/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 | raf-perf by Damien Seguin (https://github.com/dmnsgn)
8 |
36 |
37 |
38 |
39 | raf-perf
40 |
41 |
42 |
43 |
44 |
45 |
109 |
110 |
111 |
--------------------------------------------------------------------------------
/index.js:
--------------------------------------------------------------------------------
1 | /**
2 | * @typedef {object} Options
3 | * @property {number} [fps=60] Throttle fps.
4 | * @property {OptionsPerformances} [performances={ enabled: true, samplesCount: 200, sampleDuration: 4000 }] Performances metrics.
5 | */
6 |
7 | /**
8 | * @typedef {object} OptionsPerformances
9 | * @property {boolean} [enabled=true] Evaluate performances.
10 | * @property {number} [samplesCount=200] Number of samples to evaluate performances.
11 | * @property {number} [sampleDuration=4000] Duration of sample to evaluate performances.
12 | */
13 |
14 | class RafPerf {
15 | /**
16 | * @type {string}
17 | */
18 | static TickEvent = "tick";
19 | /**
20 | * @type {string}
21 | */
22 | static PerfEvent = "perf";
23 |
24 | static now() {
25 | return (performance || Date).now();
26 | }
27 |
28 | static fpsToMs(value) {
29 | return (1 / value) * 1000;
30 | }
31 |
32 | /**
33 | * Creates an instance of RafPerf.
34 | *
35 | * @param {Options} [options={}]
36 | * `samplesCount` and `sampleDuration` are used concurrently. Set `sampleDuration` to a _falsy_ value if you only want to sample performances from a number of frames.
37 | */
38 | constructor(options = {}) {
39 | this.options = Object.assign(
40 | {
41 | fps: 60,
42 | performances: {
43 | enabled: true,
44 | samplesCount: 200,
45 | // If everything runs smoothtly, samplesCount will be used over sampleDuration
46 | // 1000 ms / 60 fps * 200 samplesCount = 3333 ms
47 | sampleDuration: 4000,
48 | },
49 | },
50 | options,
51 | );
52 |
53 | this.events = {};
54 |
55 | this.reset();
56 |
57 | this.tick = this.tick.bind(this);
58 | this.onVisibilityChange = this.onVisibilityChange.bind(this);
59 | }
60 |
61 | reset() {
62 | this.isVisible = true;
63 | this.running = false;
64 | this.prevTime = null;
65 | this.startTime = null;
66 |
67 | this.frameDuration = RafPerf.fpsToMs(this.options.fps);
68 |
69 | this.performance = undefined;
70 | this.perfSamples = [];
71 |
72 | if (this.requestID) cancelAnimationFrame(this.requestID);
73 | }
74 |
75 | /**
76 | * Run the `requestAnimationFrame` loop and start checking performances if `options.performances.enabled` is `true`.
77 | */
78 | start() {
79 | // Check if loop is already running
80 | if (this.running) return;
81 |
82 | // Set running state and initial time
83 | this.running = true;
84 | this.prevTime = RafPerf.now();
85 | this.startTime = this.prevTime;
86 | this.perfStartTime = this.prevTime;
87 |
88 | // Add visibility listener
89 | document.addEventListener(
90 | "visibilitychange",
91 | this.onVisibilityChange,
92 | false,
93 | );
94 |
95 | // Start ticking
96 | this.requestID = requestAnimationFrame(this.tick);
97 | }
98 |
99 | /**
100 | * The frame loop callback.
101 | *
102 | * @fires RafPerf.PerfEvent
103 | * @fires RafPerf.TickEvent
104 | */
105 | tick() {
106 | // Ensure loop is running
107 | if (!this.running || !this.isVisible) return;
108 |
109 | const { performances } = this.options;
110 |
111 | // Compute delta time since previous time
112 | const time = RafPerf.now();
113 | const deltaTime = time - this.prevTime;
114 |
115 | // Compute delta since previous frame
116 | const frameDeltaTime = time - this.startTime;
117 |
118 | // Check elapsed time is more than desired frame duration
119 | if (deltaTime > this.frameDuration) {
120 | if (performances.enabled) {
121 | // Push delta time for average computation
122 | this.perfSamples.push(frameDeltaTime);
123 |
124 | // Check if enough time has passed to sample or number of samples collected is enough
125 | const perfNeedsUpdates =
126 | (performances.sampleDuration &&
127 | time - this.perfStartTime > performances.sampleDuration) ||
128 | this.perfSamples.length > performances.samplesCount;
129 |
130 | if (perfNeedsUpdates) {
131 | // Check average and update performance ratio
132 | const averageDeltaTime =
133 | this.perfSamples.reduce((time, sum) => time + sum) /
134 | this.perfSamples.length;
135 | this.performance = this.frameDuration / averageDeltaTime;
136 |
137 | /**
138 | * Event triggered when performance ratio (`this.frameDuration / averageDeltaTime`) is updated. Understand a ratio of the fps, for instance for a fps value of 24, `ratio < 0.5` means that the averaged `fps < 12` and you should probably do something about it.
139 | *
140 | * @event "perf"
141 | * @type {number} The performance ratio of frame duration against average delta time.
142 | */
143 | this.emit(RafPerf.PerfEvent, this.performance);
144 |
145 | // Reset performances variables
146 | this.perfSamples = [];
147 | this.perfStartTime = time;
148 | }
149 | }
150 |
151 | // Update prev and start time
152 | // Compensate for gap between delta time and x number of frames
153 | this.prevTime = time - (deltaTime % this.frameDuration);
154 | this.startTime = time;
155 |
156 | /**
157 | * Event triggered on tick, throttled by `options.fps`.
158 | *
159 | * @event "tick"
160 | * @type {number} The delta since previous frame.
161 | */
162 | this.emit(RafPerf.TickEvent, frameDeltaTime);
163 | }
164 |
165 | this.requestID = requestAnimationFrame(this.tick);
166 | }
167 |
168 | /**
169 | * Run `cancelAnimationFrame` if necessary and reset the engine.
170 | */
171 | stop() {
172 | document.removeEventListener(
173 | "visibilitychange",
174 | this.onVisibilityChange,
175 | false,
176 | );
177 |
178 | this.reset();
179 | }
180 |
181 | /**
182 | * Add "perf" and "tick" listeners.
183 | * @param {string} type
184 | * @param {Function} cb
185 | * @returns {Function} Call the return value to unsubscribe.
186 | */
187 | on(type, cb) {
188 | this.events[type] ||= new Set();
189 | this.events[type].add(cb);
190 | return () => this.events[type]?.delete(cb);
191 | }
192 |
193 | emit(type, ...args) {
194 | this.events[type]?.forEach((cb) => cb(...args));
195 | }
196 |
197 | onVisibilityChange() {
198 | this.isVisible = !document.hidden;
199 |
200 | if (this.isVisible) {
201 | this.reset();
202 | this.start();
203 | }
204 | }
205 | }
206 |
207 | export default RafPerf;
208 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # raf-perf
2 |
3 | [](https://www.npmjs.com/package/raf-perf)
4 | [](https://www.npmjs.com/package/raf-perf)
5 | [](https://bundlephobia.com/package/raf-perf)
6 | [](https://github.com/dmnsgn/raf-perf/blob/main/package.json)
7 | [](https://github.com/microsoft/TypeScript)
8 | [](https://conventionalcommits.org)
9 | [](https://github.com/prettier/prettier)
10 | [](https://github.com/eslint/eslint)
11 | [](https://github.com/dmnsgn/raf-perf/blob/main/LICENSE.md)
12 |
13 | RAF loop with an adaptive fps and performance ratio calculated from either a sample count or a sample duration. Typically used when doing intensive graphics computation in canvas.
14 |
15 | [](https://paypal.me/dmnsgn)
16 | [](https://commerce.coinbase.com/checkout/56cbdf28-e323-48d8-9c98-7019e72c97f3)
17 | [](https://twitter.com/dmnsgn)
18 |
19 | 
20 |
21 | ## Installation
22 |
23 | ```bash
24 | npm install raf-perf
25 | ```
26 |
27 | ## Usage
28 |
29 | ```js
30 | import RafPerf from "raf-perf";
31 | import createCanvasContext from "canvas-context";
32 |
33 | const { context, canvas } = createCanvasContext("2d", {
34 | width: window.innerWidth,
35 | height: window.innerHeight,
36 | offscreen: true,
37 | });
38 | document.body.appendChild(canvas);
39 |
40 | const engine = new RafPerf();
41 |
42 | const offTick = engine.on("tick", (dt) => {
43 | // Clear
44 | context.clearRect(0, 0, canvas.width, canvas.height);
45 |
46 | // Draw
47 | // ...
48 | });
49 |
50 | const offPerf = engine.on("perf", (ratio) => {
51 | if (!ratio) return;
52 |
53 | console.log(`Performance ratio: ${ratio}`);
54 |
55 | if (ratio < 0.9) {
56 | console.log("Too many draws");
57 | } else if (ratio >= 0.9 && rectCount < maxRectCount) {
58 | console.log("Draw more");
59 | }
60 | });
61 |
62 | engine.start();
63 |
64 | const destroy = () => {
65 | if (engine.isRunning) engine.stop();
66 | offTick();
67 | offPerf();
68 | };
69 | ```
70 |
71 | ## API
72 |
73 |
74 |
75 | ## Classes
76 |
77 |
78 | - RafPerf
79 |
80 |
81 |
82 | ## Events
83 |
84 |
85 | - "perf"
86 | Event triggered when performance ratio (this.frameDuration / averageDeltaTime) is updated. Understand a ratio of the fps, for instance for a fps value of 24, ratio < 0.5 means that the averaged fps < 12 and you should probably do something about it.
87 |
88 | - "tick"
89 | Event triggered on tick, throttled by options.fps.
90 |
91 |
92 |
93 | ## Typedefs
94 |
95 |
96 | - Options :
object
97 |
98 | - OptionsPerformances :
object
99 |
100 |
101 |
102 |
103 |
104 | ## RafPerf
105 |
106 | **Kind**: global class
107 |
108 | - [RafPerf](#RafPerf)
109 | - [new RafPerf([options])](#new_RafPerf_new)
110 | - [.TickEvent](#RafPerf+TickEvent) : string
111 | - [.PerfEvent](#RafPerf+PerfEvent) : string
112 | - [.start()](#RafPerf+start)
113 | - [.tick()](#RafPerf+tick)
114 | - [.stop()](#RafPerf+stop)
115 | - [.on(type, cb)](#RafPerf+on) ⇒ function
116 |
117 |
118 |
119 | ### new RafPerf([options])
120 |
121 | Creates an instance of RafPerf.
122 |
123 | | Param | Type | Default | Description |
124 | | --------- | -------------------------------- | --------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
125 | | [options] | [Options](#Options) | {} | `samplesCount` and `sampleDuration` are used concurrently. Set `sampleDuration` to a _falsy_ value if you only want to sample performances from a number of frames. |
126 |
127 |
128 |
129 | ### rafPerf.TickEvent : string
130 |
131 | **Kind**: instance property of [RafPerf](#RafPerf)
132 |
133 |
134 | ### rafPerf.PerfEvent : string
135 |
136 | **Kind**: instance property of [RafPerf](#RafPerf)
137 |
138 |
139 | ### rafPerf.start()
140 |
141 | Run the `requestAnimationFrame` loop and start checking performances if `options.performances.enabled` is `true`.
142 |
143 | **Kind**: instance method of [RafPerf](#RafPerf)
144 |
145 |
146 | ### rafPerf.tick()
147 |
148 | The frame loop callback.
149 |
150 | **Kind**: instance method of [RafPerf](#RafPerf)
151 | **Emits**: RafPerf.event:PerfEvent, RafPerf.event:TickEvent
152 |
153 |
154 | ### rafPerf.stop()
155 |
156 | Run `cancelAnimationFrame` if necessary and reset the engine.
157 |
158 | **Kind**: instance method of [RafPerf](#RafPerf)
159 |
160 |
161 | ### rafPerf.on(type, cb) ⇒ function
162 |
163 | Add "perf" and "tick" listeners.
164 |
165 | **Kind**: instance method of [RafPerf](#RafPerf)
166 | **Returns**: function - Call the return value to unsubscribe.
167 |
168 | | Param | Type |
169 | | ----- | --------------------- |
170 | | type | string |
171 | | cb | function |
172 |
173 |
174 |
175 | ## "perf"
176 |
177 | Event triggered when performance ratio (`this.frameDuration / averageDeltaTime`) is updated. Understand a ratio of the fps, for instance for a fps value of 24, `ratio < 0.5` means that the averaged `fps < 12` and you should probably do something about it.
178 |
179 | **Kind**: event emitted
180 |
181 |
182 | ## "tick"
183 |
184 | Event triggered on tick, throttled by `options.fps`.
185 |
186 | **Kind**: event emitted
187 |
188 |
189 | ## Options : object
190 |
191 | **Kind**: global typedef
192 | **Properties**
193 |
194 | | Name | Type | Default | Description |
195 | | -------------- | -------------------------------------------------------- | ----------------------------------------------------------------------- | --------------------- |
196 | | [fps] | number | 60 | Throttle fps. |
197 | | [performances] | [OptionsPerformances](#OptionsPerformances) | { enabled: true, samplesCount: 200, sampleDuration: 4000 } | Performances metrics. |
198 |
199 |
200 |
201 | ## OptionsPerformances : object
202 |
203 | **Kind**: global typedef
204 | **Properties**
205 |
206 | | Name | Type | Default | Description |
207 | | ---------------- | -------------------- | ----------------- | -------------------------------------------- |
208 | | [enabled] | boolean | true | Evaluate performances. |
209 | | [samplesCount] | number | 200 | Number of samples to evaluate performances. |
210 | | [sampleDuration] | number | 4000 | Duration of sample to evaluate performances. |
211 |
212 |
213 |
214 | ## License
215 |
216 | MIT. See [license file](https://github.com/dmnsgn/raf-perf/blob/main/LICENSE.md).
217 |
--------------------------------------------------------------------------------
/web_modules/_chunks/polyfills-CU6gNi7m.js:
--------------------------------------------------------------------------------
1 | var global$1 = (typeof global !== "undefined" ? global :
2 | typeof self !== "undefined" ? self :
3 | typeof window !== "undefined" ? window : {});
4 |
5 | var lookup = [];
6 | var revLookup = [];
7 | var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array;
8 | var inited = false;
9 | function init () {
10 | inited = true;
11 | var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
12 | for (var i = 0, len = code.length; i < len; ++i) {
13 | lookup[i] = code[i];
14 | revLookup[code.charCodeAt(i)] = i;
15 | }
16 |
17 | revLookup['-'.charCodeAt(0)] = 62;
18 | revLookup['_'.charCodeAt(0)] = 63;
19 | }
20 |
21 | function toByteArray (b64) {
22 | if (!inited) {
23 | init();
24 | }
25 | var i, j, l, tmp, placeHolders, arr;
26 | var len = b64.length;
27 |
28 | if (len % 4 > 0) {
29 | throw new Error('Invalid string. Length must be a multiple of 4')
30 | }
31 |
32 | // the number of equal signs (place holders)
33 | // if there are two placeholders, than the two characters before it
34 | // represent one byte
35 | // if there is only one, then the three characters before it represent 2 bytes
36 | // this is just a cheap hack to not do indexOf twice
37 | placeHolders = b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0;
38 |
39 | // base64 is 4/3 + up to two characters of the original data
40 | arr = new Arr(len * 3 / 4 - placeHolders);
41 |
42 | // if there are placeholders, only get up to the last complete 4 chars
43 | l = placeHolders > 0 ? len - 4 : len;
44 |
45 | var L = 0;
46 |
47 | for (i = 0, j = 0; i < l; i += 4, j += 3) {
48 | tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)];
49 | arr[L++] = (tmp >> 16) & 0xFF;
50 | arr[L++] = (tmp >> 8) & 0xFF;
51 | arr[L++] = tmp & 0xFF;
52 | }
53 |
54 | if (placeHolders === 2) {
55 | tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4);
56 | arr[L++] = tmp & 0xFF;
57 | } else if (placeHolders === 1) {
58 | tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2);
59 | arr[L++] = (tmp >> 8) & 0xFF;
60 | arr[L++] = tmp & 0xFF;
61 | }
62 |
63 | return arr
64 | }
65 |
66 | function tripletToBase64 (num) {
67 | return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F]
68 | }
69 |
70 | function encodeChunk (uint8, start, end) {
71 | var tmp;
72 | var output = [];
73 | for (var i = start; i < end; i += 3) {
74 | tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2]);
75 | output.push(tripletToBase64(tmp));
76 | }
77 | return output.join('')
78 | }
79 |
80 | function fromByteArray (uint8) {
81 | if (!inited) {
82 | init();
83 | }
84 | var tmp;
85 | var len = uint8.length;
86 | var extraBytes = len % 3; // if we have 1 byte left, pad 2 bytes
87 | var output = '';
88 | var parts = [];
89 | var maxChunkLength = 16383; // must be multiple of 3
90 |
91 | // go through the array every three bytes, we'll deal with trailing stuff later
92 | for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
93 | parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)));
94 | }
95 |
96 | // pad the end with zeros, but make sure to not forget the extra bytes
97 | if (extraBytes === 1) {
98 | tmp = uint8[len - 1];
99 | output += lookup[tmp >> 2];
100 | output += lookup[(tmp << 4) & 0x3F];
101 | output += '==';
102 | } else if (extraBytes === 2) {
103 | tmp = (uint8[len - 2] << 8) + (uint8[len - 1]);
104 | output += lookup[tmp >> 10];
105 | output += lookup[(tmp >> 4) & 0x3F];
106 | output += lookup[(tmp << 2) & 0x3F];
107 | output += '=';
108 | }
109 |
110 | parts.push(output);
111 |
112 | return parts.join('')
113 | }
114 |
115 | function read (buffer, offset, isLE, mLen, nBytes) {
116 | var e, m;
117 | var eLen = nBytes * 8 - mLen - 1;
118 | var eMax = (1 << eLen) - 1;
119 | var eBias = eMax >> 1;
120 | var nBits = -7;
121 | var i = isLE ? (nBytes - 1) : 0;
122 | var d = isLE ? -1 : 1;
123 | var s = buffer[offset + i];
124 |
125 | i += d;
126 |
127 | e = s & ((1 << (-nBits)) - 1);
128 | s >>= (-nBits);
129 | nBits += eLen;
130 | for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {}
131 |
132 | m = e & ((1 << (-nBits)) - 1);
133 | e >>= (-nBits);
134 | nBits += mLen;
135 | for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {}
136 |
137 | if (e === 0) {
138 | e = 1 - eBias;
139 | } else if (e === eMax) {
140 | return m ? NaN : ((s ? -1 : 1) * Infinity)
141 | } else {
142 | m = m + Math.pow(2, mLen);
143 | e = e - eBias;
144 | }
145 | return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
146 | }
147 |
148 | function write (buffer, value, offset, isLE, mLen, nBytes) {
149 | var e, m, c;
150 | var eLen = nBytes * 8 - mLen - 1;
151 | var eMax = (1 << eLen) - 1;
152 | var eBias = eMax >> 1;
153 | var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0);
154 | var i = isLE ? 0 : (nBytes - 1);
155 | var d = isLE ? 1 : -1;
156 | var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0;
157 |
158 | value = Math.abs(value);
159 |
160 | if (isNaN(value) || value === Infinity) {
161 | m = isNaN(value) ? 1 : 0;
162 | e = eMax;
163 | } else {
164 | e = Math.floor(Math.log(value) / Math.LN2);
165 | if (value * (c = Math.pow(2, -e)) < 1) {
166 | e--;
167 | c *= 2;
168 | }
169 | if (e + eBias >= 1) {
170 | value += rt / c;
171 | } else {
172 | value += rt * Math.pow(2, 1 - eBias);
173 | }
174 | if (value * c >= 2) {
175 | e++;
176 | c /= 2;
177 | }
178 |
179 | if (e + eBias >= eMax) {
180 | m = 0;
181 | e = eMax;
182 | } else if (e + eBias >= 1) {
183 | m = (value * c - 1) * Math.pow(2, mLen);
184 | e = e + eBias;
185 | } else {
186 | m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen);
187 | e = 0;
188 | }
189 | }
190 |
191 | for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
192 |
193 | e = (e << mLen) | m;
194 | eLen += mLen;
195 | for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
196 |
197 | buffer[offset + i - d] |= s * 128;
198 | }
199 |
200 | var toString = {}.toString;
201 |
202 | var isArray = Array.isArray || function (arr) {
203 | return toString.call(arr) == '[object Array]';
204 | };
205 |
206 | /*!
207 | * The buffer module from node.js, for the browser.
208 | *
209 | * @author Feross Aboukhadijeh
210 | * @license MIT
211 | */
212 | /* eslint-disable no-proto */
213 |
214 |
215 | var INSPECT_MAX_BYTES = 50;
216 |
217 | /**
218 | * If `Buffer.TYPED_ARRAY_SUPPORT`:
219 | * === true Use Uint8Array implementation (fastest)
220 | * === false Use Object implementation (most compatible, even IE6)
221 | *
222 | * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
223 | * Opera 11.6+, iOS 4.2+.
224 | *
225 | * Due to various browser bugs, sometimes the Object implementation will be used even
226 | * when the browser supports typed arrays.
227 | *
228 | * Note:
229 | *
230 | * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances,
231 | * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438.
232 | *
233 | * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function.
234 | *
235 | * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of
236 | * incorrect length in some situations.
237 |
238 | * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they
239 | * get the Object implementation, which is slower but behaves correctly.
240 | */
241 | Buffer.TYPED_ARRAY_SUPPORT = global$1.TYPED_ARRAY_SUPPORT !== undefined
242 | ? global$1.TYPED_ARRAY_SUPPORT
243 | : true;
244 |
245 | /*
246 | * Export kMaxLength after typed array support is determined.
247 | */
248 | kMaxLength();
249 |
250 | function kMaxLength () {
251 | return Buffer.TYPED_ARRAY_SUPPORT
252 | ? 0x7fffffff
253 | : 0x3fffffff
254 | }
255 |
256 | function createBuffer (that, length) {
257 | if (kMaxLength() < length) {
258 | throw new RangeError('Invalid typed array length')
259 | }
260 | if (Buffer.TYPED_ARRAY_SUPPORT) {
261 | // Return an augmented `Uint8Array` instance, for best performance
262 | that = new Uint8Array(length);
263 | that.__proto__ = Buffer.prototype;
264 | } else {
265 | // Fallback: Return an object instance of the Buffer class
266 | if (that === null) {
267 | that = new Buffer(length);
268 | }
269 | that.length = length;
270 | }
271 |
272 | return that
273 | }
274 |
275 | /**
276 | * The Buffer constructor returns instances of `Uint8Array` that have their
277 | * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
278 | * `Uint8Array`, so the returned instances will have all the node `Buffer` methods
279 | * and the `Uint8Array` methods. Square bracket notation works as expected -- it
280 | * returns a single octet.
281 | *
282 | * The `Uint8Array` prototype remains unmodified.
283 | */
284 |
285 | function Buffer (arg, encodingOrOffset, length) {
286 | if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) {
287 | return new Buffer(arg, encodingOrOffset, length)
288 | }
289 |
290 | // Common case.
291 | if (typeof arg === 'number') {
292 | if (typeof encodingOrOffset === 'string') {
293 | throw new Error(
294 | 'If encoding is specified then the first argument must be a string'
295 | )
296 | }
297 | return allocUnsafe(this, arg)
298 | }
299 | return from(this, arg, encodingOrOffset, length)
300 | }
301 |
302 | Buffer.poolSize = 8192; // not used by this implementation
303 |
304 | // TODO: Legacy, not needed anymore. Remove in next major version.
305 | Buffer._augment = function (arr) {
306 | arr.__proto__ = Buffer.prototype;
307 | return arr
308 | };
309 |
310 | function from (that, value, encodingOrOffset, length) {
311 | if (typeof value === 'number') {
312 | throw new TypeError('"value" argument must not be a number')
313 | }
314 |
315 | if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) {
316 | return fromArrayBuffer(that, value, encodingOrOffset, length)
317 | }
318 |
319 | if (typeof value === 'string') {
320 | return fromString(that, value, encodingOrOffset)
321 | }
322 |
323 | return fromObject(that, value)
324 | }
325 |
326 | /**
327 | * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
328 | * if value is a number.
329 | * Buffer.from(str[, encoding])
330 | * Buffer.from(array)
331 | * Buffer.from(buffer)
332 | * Buffer.from(arrayBuffer[, byteOffset[, length]])
333 | **/
334 | Buffer.from = function (value, encodingOrOffset, length) {
335 | return from(null, value, encodingOrOffset, length)
336 | };
337 |
338 | if (Buffer.TYPED_ARRAY_SUPPORT) {
339 | Buffer.prototype.__proto__ = Uint8Array.prototype;
340 | Buffer.__proto__ = Uint8Array;
341 | if (typeof Symbol !== 'undefined' && Symbol.species &&
342 | Buffer[Symbol.species] === Buffer) ;
343 | }
344 |
345 | function assertSize (size) {
346 | if (typeof size !== 'number') {
347 | throw new TypeError('"size" argument must be a number')
348 | } else if (size < 0) {
349 | throw new RangeError('"size" argument must not be negative')
350 | }
351 | }
352 |
353 | function alloc (that, size, fill, encoding) {
354 | assertSize(size);
355 | if (size <= 0) {
356 | return createBuffer(that, size)
357 | }
358 | if (fill !== undefined) {
359 | // Only pay attention to encoding if it's a string. This
360 | // prevents accidentally sending in a number that would
361 | // be interpretted as a start offset.
362 | return typeof encoding === 'string'
363 | ? createBuffer(that, size).fill(fill, encoding)
364 | : createBuffer(that, size).fill(fill)
365 | }
366 | return createBuffer(that, size)
367 | }
368 |
369 | /**
370 | * Creates a new filled Buffer instance.
371 | * alloc(size[, fill[, encoding]])
372 | **/
373 | Buffer.alloc = function (size, fill, encoding) {
374 | return alloc(null, size, fill, encoding)
375 | };
376 |
377 | function allocUnsafe (that, size) {
378 | assertSize(size);
379 | that = createBuffer(that, size < 0 ? 0 : checked(size) | 0);
380 | if (!Buffer.TYPED_ARRAY_SUPPORT) {
381 | for (var i = 0; i < size; ++i) {
382 | that[i] = 0;
383 | }
384 | }
385 | return that
386 | }
387 |
388 | /**
389 | * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
390 | * */
391 | Buffer.allocUnsafe = function (size) {
392 | return allocUnsafe(null, size)
393 | };
394 | /**
395 | * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
396 | */
397 | Buffer.allocUnsafeSlow = function (size) {
398 | return allocUnsafe(null, size)
399 | };
400 |
401 | function fromString (that, string, encoding) {
402 | if (typeof encoding !== 'string' || encoding === '') {
403 | encoding = 'utf8';
404 | }
405 |
406 | if (!Buffer.isEncoding(encoding)) {
407 | throw new TypeError('"encoding" must be a valid string encoding')
408 | }
409 |
410 | var length = byteLength(string, encoding) | 0;
411 | that = createBuffer(that, length);
412 |
413 | var actual = that.write(string, encoding);
414 |
415 | if (actual !== length) {
416 | // Writing a hex string, for example, that contains invalid characters will
417 | // cause everything after the first invalid character to be ignored. (e.g.
418 | // 'abxxcd' will be treated as 'ab')
419 | that = that.slice(0, actual);
420 | }
421 |
422 | return that
423 | }
424 |
425 | function fromArrayLike (that, array) {
426 | var length = array.length < 0 ? 0 : checked(array.length) | 0;
427 | that = createBuffer(that, length);
428 | for (var i = 0; i < length; i += 1) {
429 | that[i] = array[i] & 255;
430 | }
431 | return that
432 | }
433 |
434 | function fromArrayBuffer (that, array, byteOffset, length) {
435 | array.byteLength; // this throws if `array` is not a valid ArrayBuffer
436 |
437 | if (byteOffset < 0 || array.byteLength < byteOffset) {
438 | throw new RangeError('\'offset\' is out of bounds')
439 | }
440 |
441 | if (array.byteLength < byteOffset + (length || 0)) {
442 | throw new RangeError('\'length\' is out of bounds')
443 | }
444 |
445 | if (byteOffset === undefined && length === undefined) {
446 | array = new Uint8Array(array);
447 | } else if (length === undefined) {
448 | array = new Uint8Array(array, byteOffset);
449 | } else {
450 | array = new Uint8Array(array, byteOffset, length);
451 | }
452 |
453 | if (Buffer.TYPED_ARRAY_SUPPORT) {
454 | // Return an augmented `Uint8Array` instance, for best performance
455 | that = array;
456 | that.__proto__ = Buffer.prototype;
457 | } else {
458 | // Fallback: Return an object instance of the Buffer class
459 | that = fromArrayLike(that, array);
460 | }
461 | return that
462 | }
463 |
464 | function fromObject (that, obj) {
465 | if (internalIsBuffer(obj)) {
466 | var len = checked(obj.length) | 0;
467 | that = createBuffer(that, len);
468 |
469 | if (that.length === 0) {
470 | return that
471 | }
472 |
473 | obj.copy(that, 0, 0, len);
474 | return that
475 | }
476 |
477 | if (obj) {
478 | if ((typeof ArrayBuffer !== 'undefined' &&
479 | obj.buffer instanceof ArrayBuffer) || 'length' in obj) {
480 | if (typeof obj.length !== 'number' || isnan(obj.length)) {
481 | return createBuffer(that, 0)
482 | }
483 | return fromArrayLike(that, obj)
484 | }
485 |
486 | if (obj.type === 'Buffer' && isArray(obj.data)) {
487 | return fromArrayLike(that, obj.data)
488 | }
489 | }
490 |
491 | throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.')
492 | }
493 |
494 | function checked (length) {
495 | // Note: cannot use `length < kMaxLength()` here because that fails when
496 | // length is NaN (which is otherwise coerced to zero.)
497 | if (length >= kMaxLength()) {
498 | throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
499 | 'size: 0x' + kMaxLength().toString(16) + ' bytes')
500 | }
501 | return length | 0
502 | }
503 | Buffer.isBuffer = isBuffer;
504 | function internalIsBuffer (b) {
505 | return !!(b != null && b._isBuffer)
506 | }
507 |
508 | Buffer.compare = function compare (a, b) {
509 | if (!internalIsBuffer(a) || !internalIsBuffer(b)) {
510 | throw new TypeError('Arguments must be Buffers')
511 | }
512 |
513 | if (a === b) return 0
514 |
515 | var x = a.length;
516 | var y = b.length;
517 |
518 | for (var i = 0, len = Math.min(x, y); i < len; ++i) {
519 | if (a[i] !== b[i]) {
520 | x = a[i];
521 | y = b[i];
522 | break
523 | }
524 | }
525 |
526 | if (x < y) return -1
527 | if (y < x) return 1
528 | return 0
529 | };
530 |
531 | Buffer.isEncoding = function isEncoding (encoding) {
532 | switch (String(encoding).toLowerCase()) {
533 | case 'hex':
534 | case 'utf8':
535 | case 'utf-8':
536 | case 'ascii':
537 | case 'latin1':
538 | case 'binary':
539 | case 'base64':
540 | case 'ucs2':
541 | case 'ucs-2':
542 | case 'utf16le':
543 | case 'utf-16le':
544 | return true
545 | default:
546 | return false
547 | }
548 | };
549 |
550 | Buffer.concat = function concat (list, length) {
551 | if (!isArray(list)) {
552 | throw new TypeError('"list" argument must be an Array of Buffers')
553 | }
554 |
555 | if (list.length === 0) {
556 | return Buffer.alloc(0)
557 | }
558 |
559 | var i;
560 | if (length === undefined) {
561 | length = 0;
562 | for (i = 0; i < list.length; ++i) {
563 | length += list[i].length;
564 | }
565 | }
566 |
567 | var buffer = Buffer.allocUnsafe(length);
568 | var pos = 0;
569 | for (i = 0; i < list.length; ++i) {
570 | var buf = list[i];
571 | if (!internalIsBuffer(buf)) {
572 | throw new TypeError('"list" argument must be an Array of Buffers')
573 | }
574 | buf.copy(buffer, pos);
575 | pos += buf.length;
576 | }
577 | return buffer
578 | };
579 |
580 | function byteLength (string, encoding) {
581 | if (internalIsBuffer(string)) {
582 | return string.length
583 | }
584 | if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' &&
585 | (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) {
586 | return string.byteLength
587 | }
588 | if (typeof string !== 'string') {
589 | string = '' + string;
590 | }
591 |
592 | var len = string.length;
593 | if (len === 0) return 0
594 |
595 | // Use a for loop to avoid recursion
596 | var loweredCase = false;
597 | for (;;) {
598 | switch (encoding) {
599 | case 'ascii':
600 | case 'latin1':
601 | case 'binary':
602 | return len
603 | case 'utf8':
604 | case 'utf-8':
605 | case undefined:
606 | return utf8ToBytes(string).length
607 | case 'ucs2':
608 | case 'ucs-2':
609 | case 'utf16le':
610 | case 'utf-16le':
611 | return len * 2
612 | case 'hex':
613 | return len >>> 1
614 | case 'base64':
615 | return base64ToBytes(string).length
616 | default:
617 | if (loweredCase) return utf8ToBytes(string).length // assume utf8
618 | encoding = ('' + encoding).toLowerCase();
619 | loweredCase = true;
620 | }
621 | }
622 | }
623 | Buffer.byteLength = byteLength;
624 |
625 | function slowToString (encoding, start, end) {
626 | var loweredCase = false;
627 |
628 | // No need to verify that "this.length <= MAX_UINT32" since it's a read-only
629 | // property of a typed array.
630 |
631 | // This behaves neither like String nor Uint8Array in that we set start/end
632 | // to their upper/lower bounds if the value passed is out of range.
633 | // undefined is handled specially as per ECMA-262 6th Edition,
634 | // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
635 | if (start === undefined || start < 0) {
636 | start = 0;
637 | }
638 | // Return early if start > this.length. Done here to prevent potential uint32
639 | // coercion fail below.
640 | if (start > this.length) {
641 | return ''
642 | }
643 |
644 | if (end === undefined || end > this.length) {
645 | end = this.length;
646 | }
647 |
648 | if (end <= 0) {
649 | return ''
650 | }
651 |
652 | // Force coersion to uint32. This will also coerce falsey/NaN values to 0.
653 | end >>>= 0;
654 | start >>>= 0;
655 |
656 | if (end <= start) {
657 | return ''
658 | }
659 |
660 | if (!encoding) encoding = 'utf8';
661 |
662 | while (true) {
663 | switch (encoding) {
664 | case 'hex':
665 | return hexSlice(this, start, end)
666 |
667 | case 'utf8':
668 | case 'utf-8':
669 | return utf8Slice(this, start, end)
670 |
671 | case 'ascii':
672 | return asciiSlice(this, start, end)
673 |
674 | case 'latin1':
675 | case 'binary':
676 | return latin1Slice(this, start, end)
677 |
678 | case 'base64':
679 | return base64Slice(this, start, end)
680 |
681 | case 'ucs2':
682 | case 'ucs-2':
683 | case 'utf16le':
684 | case 'utf-16le':
685 | return utf16leSlice(this, start, end)
686 |
687 | default:
688 | if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
689 | encoding = (encoding + '').toLowerCase();
690 | loweredCase = true;
691 | }
692 | }
693 | }
694 |
695 | // The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect
696 | // Buffer instances.
697 | Buffer.prototype._isBuffer = true;
698 |
699 | function swap (b, n, m) {
700 | var i = b[n];
701 | b[n] = b[m];
702 | b[m] = i;
703 | }
704 |
705 | Buffer.prototype.swap16 = function swap16 () {
706 | var len = this.length;
707 | if (len % 2 !== 0) {
708 | throw new RangeError('Buffer size must be a multiple of 16-bits')
709 | }
710 | for (var i = 0; i < len; i += 2) {
711 | swap(this, i, i + 1);
712 | }
713 | return this
714 | };
715 |
716 | Buffer.prototype.swap32 = function swap32 () {
717 | var len = this.length;
718 | if (len % 4 !== 0) {
719 | throw new RangeError('Buffer size must be a multiple of 32-bits')
720 | }
721 | for (var i = 0; i < len; i += 4) {
722 | swap(this, i, i + 3);
723 | swap(this, i + 1, i + 2);
724 | }
725 | return this
726 | };
727 |
728 | Buffer.prototype.swap64 = function swap64 () {
729 | var len = this.length;
730 | if (len % 8 !== 0) {
731 | throw new RangeError('Buffer size must be a multiple of 64-bits')
732 | }
733 | for (var i = 0; i < len; i += 8) {
734 | swap(this, i, i + 7);
735 | swap(this, i + 1, i + 6);
736 | swap(this, i + 2, i + 5);
737 | swap(this, i + 3, i + 4);
738 | }
739 | return this
740 | };
741 |
742 | Buffer.prototype.toString = function toString () {
743 | var length = this.length | 0;
744 | if (length === 0) return ''
745 | if (arguments.length === 0) return utf8Slice(this, 0, length)
746 | return slowToString.apply(this, arguments)
747 | };
748 |
749 | Buffer.prototype.equals = function equals (b) {
750 | if (!internalIsBuffer(b)) throw new TypeError('Argument must be a Buffer')
751 | if (this === b) return true
752 | return Buffer.compare(this, b) === 0
753 | };
754 |
755 | Buffer.prototype.inspect = function inspect () {
756 | var str = '';
757 | var max = INSPECT_MAX_BYTES;
758 | if (this.length > 0) {
759 | str = this.toString('hex', 0, max).match(/.{2}/g).join(' ');
760 | if (this.length > max) str += ' ... ';
761 | }
762 | return ''
763 | };
764 |
765 | Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {
766 | if (!internalIsBuffer(target)) {
767 | throw new TypeError('Argument must be a Buffer')
768 | }
769 |
770 | if (start === undefined) {
771 | start = 0;
772 | }
773 | if (end === undefined) {
774 | end = target ? target.length : 0;
775 | }
776 | if (thisStart === undefined) {
777 | thisStart = 0;
778 | }
779 | if (thisEnd === undefined) {
780 | thisEnd = this.length;
781 | }
782 |
783 | if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
784 | throw new RangeError('out of range index')
785 | }
786 |
787 | if (thisStart >= thisEnd && start >= end) {
788 | return 0
789 | }
790 | if (thisStart >= thisEnd) {
791 | return -1
792 | }
793 | if (start >= end) {
794 | return 1
795 | }
796 |
797 | start >>>= 0;
798 | end >>>= 0;
799 | thisStart >>>= 0;
800 | thisEnd >>>= 0;
801 |
802 | if (this === target) return 0
803 |
804 | var x = thisEnd - thisStart;
805 | var y = end - start;
806 | var len = Math.min(x, y);
807 |
808 | var thisCopy = this.slice(thisStart, thisEnd);
809 | var targetCopy = target.slice(start, end);
810 |
811 | for (var i = 0; i < len; ++i) {
812 | if (thisCopy[i] !== targetCopy[i]) {
813 | x = thisCopy[i];
814 | y = targetCopy[i];
815 | break
816 | }
817 | }
818 |
819 | if (x < y) return -1
820 | if (y < x) return 1
821 | return 0
822 | };
823 |
824 | // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,
825 | // OR the last index of `val` in `buffer` at offset <= `byteOffset`.
826 | //
827 | // Arguments:
828 | // - buffer - a Buffer to search
829 | // - val - a string, Buffer, or number
830 | // - byteOffset - an index into `buffer`; will be clamped to an int32
831 | // - encoding - an optional encoding, relevant is val is a string
832 | // - dir - true for indexOf, false for lastIndexOf
833 | function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {
834 | // Empty buffer means no match
835 | if (buffer.length === 0) return -1
836 |
837 | // Normalize byteOffset
838 | if (typeof byteOffset === 'string') {
839 | encoding = byteOffset;
840 | byteOffset = 0;
841 | } else if (byteOffset > 0x7fffffff) {
842 | byteOffset = 0x7fffffff;
843 | } else if (byteOffset < -0x80000000) {
844 | byteOffset = -0x80000000;
845 | }
846 | byteOffset = +byteOffset; // Coerce to Number.
847 | if (isNaN(byteOffset)) {
848 | // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer
849 | byteOffset = dir ? 0 : (buffer.length - 1);
850 | }
851 |
852 | // Normalize byteOffset: negative offsets start from the end of the buffer
853 | if (byteOffset < 0) byteOffset = buffer.length + byteOffset;
854 | if (byteOffset >= buffer.length) {
855 | if (dir) return -1
856 | else byteOffset = buffer.length - 1;
857 | } else if (byteOffset < 0) {
858 | if (dir) byteOffset = 0;
859 | else return -1
860 | }
861 |
862 | // Normalize val
863 | if (typeof val === 'string') {
864 | val = Buffer.from(val, encoding);
865 | }
866 |
867 | // Finally, search either indexOf (if dir is true) or lastIndexOf
868 | if (internalIsBuffer(val)) {
869 | // Special case: looking for empty string/buffer always fails
870 | if (val.length === 0) {
871 | return -1
872 | }
873 | return arrayIndexOf(buffer, val, byteOffset, encoding, dir)
874 | } else if (typeof val === 'number') {
875 | val = val & 0xFF; // Search for a byte value [0-255]
876 | if (Buffer.TYPED_ARRAY_SUPPORT &&
877 | typeof Uint8Array.prototype.indexOf === 'function') {
878 | if (dir) {
879 | return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)
880 | } else {
881 | return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)
882 | }
883 | }
884 | return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir)
885 | }
886 |
887 | throw new TypeError('val must be string, number or Buffer')
888 | }
889 |
890 | function arrayIndexOf (arr, val, byteOffset, encoding, dir) {
891 | var indexSize = 1;
892 | var arrLength = arr.length;
893 | var valLength = val.length;
894 |
895 | if (encoding !== undefined) {
896 | encoding = String(encoding).toLowerCase();
897 | if (encoding === 'ucs2' || encoding === 'ucs-2' ||
898 | encoding === 'utf16le' || encoding === 'utf-16le') {
899 | if (arr.length < 2 || val.length < 2) {
900 | return -1
901 | }
902 | indexSize = 2;
903 | arrLength /= 2;
904 | valLength /= 2;
905 | byteOffset /= 2;
906 | }
907 | }
908 |
909 | function read (buf, i) {
910 | if (indexSize === 1) {
911 | return buf[i]
912 | } else {
913 | return buf.readUInt16BE(i * indexSize)
914 | }
915 | }
916 |
917 | var i;
918 | if (dir) {
919 | var foundIndex = -1;
920 | for (i = byteOffset; i < arrLength; i++) {
921 | if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
922 | if (foundIndex === -1) foundIndex = i;
923 | if (i - foundIndex + 1 === valLength) return foundIndex * indexSize
924 | } else {
925 | if (foundIndex !== -1) i -= i - foundIndex;
926 | foundIndex = -1;
927 | }
928 | }
929 | } else {
930 | if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength;
931 | for (i = byteOffset; i >= 0; i--) {
932 | var found = true;
933 | for (var j = 0; j < valLength; j++) {
934 | if (read(arr, i + j) !== read(val, j)) {
935 | found = false;
936 | break
937 | }
938 | }
939 | if (found) return i
940 | }
941 | }
942 |
943 | return -1
944 | }
945 |
946 | Buffer.prototype.includes = function includes (val, byteOffset, encoding) {
947 | return this.indexOf(val, byteOffset, encoding) !== -1
948 | };
949 |
950 | Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {
951 | return bidirectionalIndexOf(this, val, byteOffset, encoding, true)
952 | };
953 |
954 | Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {
955 | return bidirectionalIndexOf(this, val, byteOffset, encoding, false)
956 | };
957 |
958 | function hexWrite (buf, string, offset, length) {
959 | offset = Number(offset) || 0;
960 | var remaining = buf.length - offset;
961 | if (!length) {
962 | length = remaining;
963 | } else {
964 | length = Number(length);
965 | if (length > remaining) {
966 | length = remaining;
967 | }
968 | }
969 |
970 | // must be an even number of digits
971 | var strLen = string.length;
972 | if (strLen % 2 !== 0) throw new TypeError('Invalid hex string')
973 |
974 | if (length > strLen / 2) {
975 | length = strLen / 2;
976 | }
977 | for (var i = 0; i < length; ++i) {
978 | var parsed = parseInt(string.substr(i * 2, 2), 16);
979 | if (isNaN(parsed)) return i
980 | buf[offset + i] = parsed;
981 | }
982 | return i
983 | }
984 |
985 | function utf8Write (buf, string, offset, length) {
986 | return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
987 | }
988 |
989 | function asciiWrite (buf, string, offset, length) {
990 | return blitBuffer(asciiToBytes(string), buf, offset, length)
991 | }
992 |
993 | function latin1Write (buf, string, offset, length) {
994 | return asciiWrite(buf, string, offset, length)
995 | }
996 |
997 | function base64Write (buf, string, offset, length) {
998 | return blitBuffer(base64ToBytes(string), buf, offset, length)
999 | }
1000 |
1001 | function ucs2Write (buf, string, offset, length) {
1002 | return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
1003 | }
1004 |
1005 | Buffer.prototype.write = function write (string, offset, length, encoding) {
1006 | // Buffer#write(string)
1007 | if (offset === undefined) {
1008 | encoding = 'utf8';
1009 | length = this.length;
1010 | offset = 0;
1011 | // Buffer#write(string, encoding)
1012 | } else if (length === undefined && typeof offset === 'string') {
1013 | encoding = offset;
1014 | length = this.length;
1015 | offset = 0;
1016 | // Buffer#write(string, offset[, length][, encoding])
1017 | } else if (isFinite(offset)) {
1018 | offset = offset | 0;
1019 | if (isFinite(length)) {
1020 | length = length | 0;
1021 | if (encoding === undefined) encoding = 'utf8';
1022 | } else {
1023 | encoding = length;
1024 | length = undefined;
1025 | }
1026 | // legacy write(string, encoding, offset, length) - remove in v0.13
1027 | } else {
1028 | throw new Error(
1029 | 'Buffer.write(string, encoding, offset[, length]) is no longer supported'
1030 | )
1031 | }
1032 |
1033 | var remaining = this.length - offset;
1034 | if (length === undefined || length > remaining) length = remaining;
1035 |
1036 | if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
1037 | throw new RangeError('Attempt to write outside buffer bounds')
1038 | }
1039 |
1040 | if (!encoding) encoding = 'utf8';
1041 |
1042 | var loweredCase = false;
1043 | for (;;) {
1044 | switch (encoding) {
1045 | case 'hex':
1046 | return hexWrite(this, string, offset, length)
1047 |
1048 | case 'utf8':
1049 | case 'utf-8':
1050 | return utf8Write(this, string, offset, length)
1051 |
1052 | case 'ascii':
1053 | return asciiWrite(this, string, offset, length)
1054 |
1055 | case 'latin1':
1056 | case 'binary':
1057 | return latin1Write(this, string, offset, length)
1058 |
1059 | case 'base64':
1060 | // Warning: maxLength not taken into account in base64Write
1061 | return base64Write(this, string, offset, length)
1062 |
1063 | case 'ucs2':
1064 | case 'ucs-2':
1065 | case 'utf16le':
1066 | case 'utf-16le':
1067 | return ucs2Write(this, string, offset, length)
1068 |
1069 | default:
1070 | if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
1071 | encoding = ('' + encoding).toLowerCase();
1072 | loweredCase = true;
1073 | }
1074 | }
1075 | };
1076 |
1077 | Buffer.prototype.toJSON = function toJSON () {
1078 | return {
1079 | type: 'Buffer',
1080 | data: Array.prototype.slice.call(this._arr || this, 0)
1081 | }
1082 | };
1083 |
1084 | function base64Slice (buf, start, end) {
1085 | if (start === 0 && end === buf.length) {
1086 | return fromByteArray(buf)
1087 | } else {
1088 | return fromByteArray(buf.slice(start, end))
1089 | }
1090 | }
1091 |
1092 | function utf8Slice (buf, start, end) {
1093 | end = Math.min(buf.length, end);
1094 | var res = [];
1095 |
1096 | var i = start;
1097 | while (i < end) {
1098 | var firstByte = buf[i];
1099 | var codePoint = null;
1100 | var bytesPerSequence = (firstByte > 0xEF) ? 4
1101 | : (firstByte > 0xDF) ? 3
1102 | : (firstByte > 0xBF) ? 2
1103 | : 1;
1104 |
1105 | if (i + bytesPerSequence <= end) {
1106 | var secondByte, thirdByte, fourthByte, tempCodePoint;
1107 |
1108 | switch (bytesPerSequence) {
1109 | case 1:
1110 | if (firstByte < 0x80) {
1111 | codePoint = firstByte;
1112 | }
1113 | break
1114 | case 2:
1115 | secondByte = buf[i + 1];
1116 | if ((secondByte & 0xC0) === 0x80) {
1117 | tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F);
1118 | if (tempCodePoint > 0x7F) {
1119 | codePoint = tempCodePoint;
1120 | }
1121 | }
1122 | break
1123 | case 3:
1124 | secondByte = buf[i + 1];
1125 | thirdByte = buf[i + 2];
1126 | if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
1127 | tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F);
1128 | if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
1129 | codePoint = tempCodePoint;
1130 | }
1131 | }
1132 | break
1133 | case 4:
1134 | secondByte = buf[i + 1];
1135 | thirdByte = buf[i + 2];
1136 | fourthByte = buf[i + 3];
1137 | if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
1138 | tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F);
1139 | if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
1140 | codePoint = tempCodePoint;
1141 | }
1142 | }
1143 | }
1144 | }
1145 |
1146 | if (codePoint === null) {
1147 | // we did not generate a valid codePoint so insert a
1148 | // replacement char (U+FFFD) and advance only 1 byte
1149 | codePoint = 0xFFFD;
1150 | bytesPerSequence = 1;
1151 | } else if (codePoint > 0xFFFF) {
1152 | // encode to utf16 (surrogate pair dance)
1153 | codePoint -= 0x10000;
1154 | res.push(codePoint >>> 10 & 0x3FF | 0xD800);
1155 | codePoint = 0xDC00 | codePoint & 0x3FF;
1156 | }
1157 |
1158 | res.push(codePoint);
1159 | i += bytesPerSequence;
1160 | }
1161 |
1162 | return decodeCodePointsArray(res)
1163 | }
1164 |
1165 | // Based on http://stackoverflow.com/a/22747272/680742, the browser with
1166 | // the lowest limit is Chrome, with 0x10000 args.
1167 | // We go 1 magnitude less, for safety
1168 | var MAX_ARGUMENTS_LENGTH = 0x1000;
1169 |
1170 | function decodeCodePointsArray (codePoints) {
1171 | var len = codePoints.length;
1172 | if (len <= MAX_ARGUMENTS_LENGTH) {
1173 | return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
1174 | }
1175 |
1176 | // Decode in chunks to avoid "call stack size exceeded".
1177 | var res = '';
1178 | var i = 0;
1179 | while (i < len) {
1180 | res += String.fromCharCode.apply(
1181 | String,
1182 | codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
1183 | );
1184 | }
1185 | return res
1186 | }
1187 |
1188 | function asciiSlice (buf, start, end) {
1189 | var ret = '';
1190 | end = Math.min(buf.length, end);
1191 |
1192 | for (var i = start; i < end; ++i) {
1193 | ret += String.fromCharCode(buf[i] & 0x7F);
1194 | }
1195 | return ret
1196 | }
1197 |
1198 | function latin1Slice (buf, start, end) {
1199 | var ret = '';
1200 | end = Math.min(buf.length, end);
1201 |
1202 | for (var i = start; i < end; ++i) {
1203 | ret += String.fromCharCode(buf[i]);
1204 | }
1205 | return ret
1206 | }
1207 |
1208 | function hexSlice (buf, start, end) {
1209 | var len = buf.length;
1210 |
1211 | if (!start || start < 0) start = 0;
1212 | if (!end || end < 0 || end > len) end = len;
1213 |
1214 | var out = '';
1215 | for (var i = start; i < end; ++i) {
1216 | out += toHex(buf[i]);
1217 | }
1218 | return out
1219 | }
1220 |
1221 | function utf16leSlice (buf, start, end) {
1222 | var bytes = buf.slice(start, end);
1223 | var res = '';
1224 | for (var i = 0; i < bytes.length; i += 2) {
1225 | res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256);
1226 | }
1227 | return res
1228 | }
1229 |
1230 | Buffer.prototype.slice = function slice (start, end) {
1231 | var len = this.length;
1232 | start = ~~start;
1233 | end = end === undefined ? len : ~~end;
1234 |
1235 | if (start < 0) {
1236 | start += len;
1237 | if (start < 0) start = 0;
1238 | } else if (start > len) {
1239 | start = len;
1240 | }
1241 |
1242 | if (end < 0) {
1243 | end += len;
1244 | if (end < 0) end = 0;
1245 | } else if (end > len) {
1246 | end = len;
1247 | }
1248 |
1249 | if (end < start) end = start;
1250 |
1251 | var newBuf;
1252 | if (Buffer.TYPED_ARRAY_SUPPORT) {
1253 | newBuf = this.subarray(start, end);
1254 | newBuf.__proto__ = Buffer.prototype;
1255 | } else {
1256 | var sliceLen = end - start;
1257 | newBuf = new Buffer(sliceLen, undefined);
1258 | for (var i = 0; i < sliceLen; ++i) {
1259 | newBuf[i] = this[i + start];
1260 | }
1261 | }
1262 |
1263 | return newBuf
1264 | };
1265 |
1266 | /*
1267 | * Need to make sure that buffer isn't trying to write out of bounds.
1268 | */
1269 | function checkOffset (offset, ext, length) {
1270 | if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
1271 | if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
1272 | }
1273 |
1274 | Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
1275 | offset = offset | 0;
1276 | byteLength = byteLength | 0;
1277 | if (!noAssert) checkOffset(offset, byteLength, this.length);
1278 |
1279 | var val = this[offset];
1280 | var mul = 1;
1281 | var i = 0;
1282 | while (++i < byteLength && (mul *= 0x100)) {
1283 | val += this[offset + i] * mul;
1284 | }
1285 |
1286 | return val
1287 | };
1288 |
1289 | Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
1290 | offset = offset | 0;
1291 | byteLength = byteLength | 0;
1292 | if (!noAssert) {
1293 | checkOffset(offset, byteLength, this.length);
1294 | }
1295 |
1296 | var val = this[offset + --byteLength];
1297 | var mul = 1;
1298 | while (byteLength > 0 && (mul *= 0x100)) {
1299 | val += this[offset + --byteLength] * mul;
1300 | }
1301 |
1302 | return val
1303 | };
1304 |
1305 | Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
1306 | if (!noAssert) checkOffset(offset, 1, this.length);
1307 | return this[offset]
1308 | };
1309 |
1310 | Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
1311 | if (!noAssert) checkOffset(offset, 2, this.length);
1312 | return this[offset] | (this[offset + 1] << 8)
1313 | };
1314 |
1315 | Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
1316 | if (!noAssert) checkOffset(offset, 2, this.length);
1317 | return (this[offset] << 8) | this[offset + 1]
1318 | };
1319 |
1320 | Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
1321 | if (!noAssert) checkOffset(offset, 4, this.length);
1322 |
1323 | return ((this[offset]) |
1324 | (this[offset + 1] << 8) |
1325 | (this[offset + 2] << 16)) +
1326 | (this[offset + 3] * 0x1000000)
1327 | };
1328 |
1329 | Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
1330 | if (!noAssert) checkOffset(offset, 4, this.length);
1331 |
1332 | return (this[offset] * 0x1000000) +
1333 | ((this[offset + 1] << 16) |
1334 | (this[offset + 2] << 8) |
1335 | this[offset + 3])
1336 | };
1337 |
1338 | Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
1339 | offset = offset | 0;
1340 | byteLength = byteLength | 0;
1341 | if (!noAssert) checkOffset(offset, byteLength, this.length);
1342 |
1343 | var val = this[offset];
1344 | var mul = 1;
1345 | var i = 0;
1346 | while (++i < byteLength && (mul *= 0x100)) {
1347 | val += this[offset + i] * mul;
1348 | }
1349 | mul *= 0x80;
1350 |
1351 | if (val >= mul) val -= Math.pow(2, 8 * byteLength);
1352 |
1353 | return val
1354 | };
1355 |
1356 | Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
1357 | offset = offset | 0;
1358 | byteLength = byteLength | 0;
1359 | if (!noAssert) checkOffset(offset, byteLength, this.length);
1360 |
1361 | var i = byteLength;
1362 | var mul = 1;
1363 | var val = this[offset + --i];
1364 | while (i > 0 && (mul *= 0x100)) {
1365 | val += this[offset + --i] * mul;
1366 | }
1367 | mul *= 0x80;
1368 |
1369 | if (val >= mul) val -= Math.pow(2, 8 * byteLength);
1370 |
1371 | return val
1372 | };
1373 |
1374 | Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) {
1375 | if (!noAssert) checkOffset(offset, 1, this.length);
1376 | if (!(this[offset] & 0x80)) return (this[offset])
1377 | return ((0xff - this[offset] + 1) * -1)
1378 | };
1379 |
1380 | Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
1381 | if (!noAssert) checkOffset(offset, 2, this.length);
1382 | var val = this[offset] | (this[offset + 1] << 8);
1383 | return (val & 0x8000) ? val | 0xFFFF0000 : val
1384 | };
1385 |
1386 | Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
1387 | if (!noAssert) checkOffset(offset, 2, this.length);
1388 | var val = this[offset + 1] | (this[offset] << 8);
1389 | return (val & 0x8000) ? val | 0xFFFF0000 : val
1390 | };
1391 |
1392 | Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
1393 | if (!noAssert) checkOffset(offset, 4, this.length);
1394 |
1395 | return (this[offset]) |
1396 | (this[offset + 1] << 8) |
1397 | (this[offset + 2] << 16) |
1398 | (this[offset + 3] << 24)
1399 | };
1400 |
1401 | Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
1402 | if (!noAssert) checkOffset(offset, 4, this.length);
1403 |
1404 | return (this[offset] << 24) |
1405 | (this[offset + 1] << 16) |
1406 | (this[offset + 2] << 8) |
1407 | (this[offset + 3])
1408 | };
1409 |
1410 | Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
1411 | if (!noAssert) checkOffset(offset, 4, this.length);
1412 | return read(this, offset, true, 23, 4)
1413 | };
1414 |
1415 | Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
1416 | if (!noAssert) checkOffset(offset, 4, this.length);
1417 | return read(this, offset, false, 23, 4)
1418 | };
1419 |
1420 | Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
1421 | if (!noAssert) checkOffset(offset, 8, this.length);
1422 | return read(this, offset, true, 52, 8)
1423 | };
1424 |
1425 | Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
1426 | if (!noAssert) checkOffset(offset, 8, this.length);
1427 | return read(this, offset, false, 52, 8)
1428 | };
1429 |
1430 | function checkInt (buf, value, offset, ext, max, min) {
1431 | if (!internalIsBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance')
1432 | if (value > max || value < min) throw new RangeError('"value" argument is out of bounds')
1433 | if (offset + ext > buf.length) throw new RangeError('Index out of range')
1434 | }
1435 |
1436 | Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
1437 | value = +value;
1438 | offset = offset | 0;
1439 | byteLength = byteLength | 0;
1440 | if (!noAssert) {
1441 | var maxBytes = Math.pow(2, 8 * byteLength) - 1;
1442 | checkInt(this, value, offset, byteLength, maxBytes, 0);
1443 | }
1444 |
1445 | var mul = 1;
1446 | var i = 0;
1447 | this[offset] = value & 0xFF;
1448 | while (++i < byteLength && (mul *= 0x100)) {
1449 | this[offset + i] = (value / mul) & 0xFF;
1450 | }
1451 |
1452 | return offset + byteLength
1453 | };
1454 |
1455 | Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
1456 | value = +value;
1457 | offset = offset | 0;
1458 | byteLength = byteLength | 0;
1459 | if (!noAssert) {
1460 | var maxBytes = Math.pow(2, 8 * byteLength) - 1;
1461 | checkInt(this, value, offset, byteLength, maxBytes, 0);
1462 | }
1463 |
1464 | var i = byteLength - 1;
1465 | var mul = 1;
1466 | this[offset + i] = value & 0xFF;
1467 | while (--i >= 0 && (mul *= 0x100)) {
1468 | this[offset + i] = (value / mul) & 0xFF;
1469 | }
1470 |
1471 | return offset + byteLength
1472 | };
1473 |
1474 | Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
1475 | value = +value;
1476 | offset = offset | 0;
1477 | if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0);
1478 | if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value);
1479 | this[offset] = (value & 0xff);
1480 | return offset + 1
1481 | };
1482 |
1483 | function objectWriteUInt16 (buf, value, offset, littleEndian) {
1484 | if (value < 0) value = 0xffff + value + 1;
1485 | for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) {
1486 | buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>>
1487 | (littleEndian ? i : 1 - i) * 8;
1488 | }
1489 | }
1490 |
1491 | Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
1492 | value = +value;
1493 | offset = offset | 0;
1494 | if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0);
1495 | if (Buffer.TYPED_ARRAY_SUPPORT) {
1496 | this[offset] = (value & 0xff);
1497 | this[offset + 1] = (value >>> 8);
1498 | } else {
1499 | objectWriteUInt16(this, value, offset, true);
1500 | }
1501 | return offset + 2
1502 | };
1503 |
1504 | Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
1505 | value = +value;
1506 | offset = offset | 0;
1507 | if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0);
1508 | if (Buffer.TYPED_ARRAY_SUPPORT) {
1509 | this[offset] = (value >>> 8);
1510 | this[offset + 1] = (value & 0xff);
1511 | } else {
1512 | objectWriteUInt16(this, value, offset, false);
1513 | }
1514 | return offset + 2
1515 | };
1516 |
1517 | function objectWriteUInt32 (buf, value, offset, littleEndian) {
1518 | if (value < 0) value = 0xffffffff + value + 1;
1519 | for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) {
1520 | buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff;
1521 | }
1522 | }
1523 |
1524 | Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
1525 | value = +value;
1526 | offset = offset | 0;
1527 | if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0);
1528 | if (Buffer.TYPED_ARRAY_SUPPORT) {
1529 | this[offset + 3] = (value >>> 24);
1530 | this[offset + 2] = (value >>> 16);
1531 | this[offset + 1] = (value >>> 8);
1532 | this[offset] = (value & 0xff);
1533 | } else {
1534 | objectWriteUInt32(this, value, offset, true);
1535 | }
1536 | return offset + 4
1537 | };
1538 |
1539 | Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
1540 | value = +value;
1541 | offset = offset | 0;
1542 | if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0);
1543 | if (Buffer.TYPED_ARRAY_SUPPORT) {
1544 | this[offset] = (value >>> 24);
1545 | this[offset + 1] = (value >>> 16);
1546 | this[offset + 2] = (value >>> 8);
1547 | this[offset + 3] = (value & 0xff);
1548 | } else {
1549 | objectWriteUInt32(this, value, offset, false);
1550 | }
1551 | return offset + 4
1552 | };
1553 |
1554 | Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
1555 | value = +value;
1556 | offset = offset | 0;
1557 | if (!noAssert) {
1558 | var limit = Math.pow(2, 8 * byteLength - 1);
1559 |
1560 | checkInt(this, value, offset, byteLength, limit - 1, -limit);
1561 | }
1562 |
1563 | var i = 0;
1564 | var mul = 1;
1565 | var sub = 0;
1566 | this[offset] = value & 0xFF;
1567 | while (++i < byteLength && (mul *= 0x100)) {
1568 | if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
1569 | sub = 1;
1570 | }
1571 | this[offset + i] = ((value / mul) >> 0) - sub & 0xFF;
1572 | }
1573 |
1574 | return offset + byteLength
1575 | };
1576 |
1577 | Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
1578 | value = +value;
1579 | offset = offset | 0;
1580 | if (!noAssert) {
1581 | var limit = Math.pow(2, 8 * byteLength - 1);
1582 |
1583 | checkInt(this, value, offset, byteLength, limit - 1, -limit);
1584 | }
1585 |
1586 | var i = byteLength - 1;
1587 | var mul = 1;
1588 | var sub = 0;
1589 | this[offset + i] = value & 0xFF;
1590 | while (--i >= 0 && (mul *= 0x100)) {
1591 | if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
1592 | sub = 1;
1593 | }
1594 | this[offset + i] = ((value / mul) >> 0) - sub & 0xFF;
1595 | }
1596 |
1597 | return offset + byteLength
1598 | };
1599 |
1600 | Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
1601 | value = +value;
1602 | offset = offset | 0;
1603 | if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80);
1604 | if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value);
1605 | if (value < 0) value = 0xff + value + 1;
1606 | this[offset] = (value & 0xff);
1607 | return offset + 1
1608 | };
1609 |
1610 | Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
1611 | value = +value;
1612 | offset = offset | 0;
1613 | if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000);
1614 | if (Buffer.TYPED_ARRAY_SUPPORT) {
1615 | this[offset] = (value & 0xff);
1616 | this[offset + 1] = (value >>> 8);
1617 | } else {
1618 | objectWriteUInt16(this, value, offset, true);
1619 | }
1620 | return offset + 2
1621 | };
1622 |
1623 | Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
1624 | value = +value;
1625 | offset = offset | 0;
1626 | if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000);
1627 | if (Buffer.TYPED_ARRAY_SUPPORT) {
1628 | this[offset] = (value >>> 8);
1629 | this[offset + 1] = (value & 0xff);
1630 | } else {
1631 | objectWriteUInt16(this, value, offset, false);
1632 | }
1633 | return offset + 2
1634 | };
1635 |
1636 | Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
1637 | value = +value;
1638 | offset = offset | 0;
1639 | if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000);
1640 | if (Buffer.TYPED_ARRAY_SUPPORT) {
1641 | this[offset] = (value & 0xff);
1642 | this[offset + 1] = (value >>> 8);
1643 | this[offset + 2] = (value >>> 16);
1644 | this[offset + 3] = (value >>> 24);
1645 | } else {
1646 | objectWriteUInt32(this, value, offset, true);
1647 | }
1648 | return offset + 4
1649 | };
1650 |
1651 | Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
1652 | value = +value;
1653 | offset = offset | 0;
1654 | if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000);
1655 | if (value < 0) value = 0xffffffff + value + 1;
1656 | if (Buffer.TYPED_ARRAY_SUPPORT) {
1657 | this[offset] = (value >>> 24);
1658 | this[offset + 1] = (value >>> 16);
1659 | this[offset + 2] = (value >>> 8);
1660 | this[offset + 3] = (value & 0xff);
1661 | } else {
1662 | objectWriteUInt32(this, value, offset, false);
1663 | }
1664 | return offset + 4
1665 | };
1666 |
1667 | function checkIEEE754 (buf, value, offset, ext, max, min) {
1668 | if (offset + ext > buf.length) throw new RangeError('Index out of range')
1669 | if (offset < 0) throw new RangeError('Index out of range')
1670 | }
1671 |
1672 | function writeFloat (buf, value, offset, littleEndian, noAssert) {
1673 | if (!noAssert) {
1674 | checkIEEE754(buf, value, offset, 4);
1675 | }
1676 | write(buf, value, offset, littleEndian, 23, 4);
1677 | return offset + 4
1678 | }
1679 |
1680 | Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
1681 | return writeFloat(this, value, offset, true, noAssert)
1682 | };
1683 |
1684 | Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
1685 | return writeFloat(this, value, offset, false, noAssert)
1686 | };
1687 |
1688 | function writeDouble (buf, value, offset, littleEndian, noAssert) {
1689 | if (!noAssert) {
1690 | checkIEEE754(buf, value, offset, 8);
1691 | }
1692 | write(buf, value, offset, littleEndian, 52, 8);
1693 | return offset + 8
1694 | }
1695 |
1696 | Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
1697 | return writeDouble(this, value, offset, true, noAssert)
1698 | };
1699 |
1700 | Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
1701 | return writeDouble(this, value, offset, false, noAssert)
1702 | };
1703 |
1704 | // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
1705 | Buffer.prototype.copy = function copy (target, targetStart, start, end) {
1706 | if (!start) start = 0;
1707 | if (!end && end !== 0) end = this.length;
1708 | if (targetStart >= target.length) targetStart = target.length;
1709 | if (!targetStart) targetStart = 0;
1710 | if (end > 0 && end < start) end = start;
1711 |
1712 | // Copy 0 bytes; we're done
1713 | if (end === start) return 0
1714 | if (target.length === 0 || this.length === 0) return 0
1715 |
1716 | // Fatal error conditions
1717 | if (targetStart < 0) {
1718 | throw new RangeError('targetStart out of bounds')
1719 | }
1720 | if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds')
1721 | if (end < 0) throw new RangeError('sourceEnd out of bounds')
1722 |
1723 | // Are we oob?
1724 | if (end > this.length) end = this.length;
1725 | if (target.length - targetStart < end - start) {
1726 | end = target.length - targetStart + start;
1727 | }
1728 |
1729 | var len = end - start;
1730 | var i;
1731 |
1732 | if (this === target && start < targetStart && targetStart < end) {
1733 | // descending copy from end
1734 | for (i = len - 1; i >= 0; --i) {
1735 | target[i + targetStart] = this[i + start];
1736 | }
1737 | } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) {
1738 | // ascending copy from start
1739 | for (i = 0; i < len; ++i) {
1740 | target[i + targetStart] = this[i + start];
1741 | }
1742 | } else {
1743 | Uint8Array.prototype.set.call(
1744 | target,
1745 | this.subarray(start, start + len),
1746 | targetStart
1747 | );
1748 | }
1749 |
1750 | return len
1751 | };
1752 |
1753 | // Usage:
1754 | // buffer.fill(number[, offset[, end]])
1755 | // buffer.fill(buffer[, offset[, end]])
1756 | // buffer.fill(string[, offset[, end]][, encoding])
1757 | Buffer.prototype.fill = function fill (val, start, end, encoding) {
1758 | // Handle string cases:
1759 | if (typeof val === 'string') {
1760 | if (typeof start === 'string') {
1761 | encoding = start;
1762 | start = 0;
1763 | end = this.length;
1764 | } else if (typeof end === 'string') {
1765 | encoding = end;
1766 | end = this.length;
1767 | }
1768 | if (val.length === 1) {
1769 | var code = val.charCodeAt(0);
1770 | if (code < 256) {
1771 | val = code;
1772 | }
1773 | }
1774 | if (encoding !== undefined && typeof encoding !== 'string') {
1775 | throw new TypeError('encoding must be a string')
1776 | }
1777 | if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {
1778 | throw new TypeError('Unknown encoding: ' + encoding)
1779 | }
1780 | } else if (typeof val === 'number') {
1781 | val = val & 255;
1782 | }
1783 |
1784 | // Invalid ranges are not set to a default, so can range check early.
1785 | if (start < 0 || this.length < start || this.length < end) {
1786 | throw new RangeError('Out of range index')
1787 | }
1788 |
1789 | if (end <= start) {
1790 | return this
1791 | }
1792 |
1793 | start = start >>> 0;
1794 | end = end === undefined ? this.length : end >>> 0;
1795 |
1796 | if (!val) val = 0;
1797 |
1798 | var i;
1799 | if (typeof val === 'number') {
1800 | for (i = start; i < end; ++i) {
1801 | this[i] = val;
1802 | }
1803 | } else {
1804 | var bytes = internalIsBuffer(val)
1805 | ? val
1806 | : utf8ToBytes(new Buffer(val, encoding).toString());
1807 | var len = bytes.length;
1808 | for (i = 0; i < end - start; ++i) {
1809 | this[i + start] = bytes[i % len];
1810 | }
1811 | }
1812 |
1813 | return this
1814 | };
1815 |
1816 | // HELPER FUNCTIONS
1817 | // ================
1818 |
1819 | var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g;
1820 |
1821 | function base64clean (str) {
1822 | // Node strips out invalid characters like \n and \t from the string, base64-js does not
1823 | str = stringtrim(str).replace(INVALID_BASE64_RE, '');
1824 | // Node converts strings with length < 2 to ''
1825 | if (str.length < 2) return ''
1826 | // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
1827 | while (str.length % 4 !== 0) {
1828 | str = str + '=';
1829 | }
1830 | return str
1831 | }
1832 |
1833 | function stringtrim (str) {
1834 | if (str.trim) return str.trim()
1835 | return str.replace(/^\s+|\s+$/g, '')
1836 | }
1837 |
1838 | function toHex (n) {
1839 | if (n < 16) return '0' + n.toString(16)
1840 | return n.toString(16)
1841 | }
1842 |
1843 | function utf8ToBytes (string, units) {
1844 | units = units || Infinity;
1845 | var codePoint;
1846 | var length = string.length;
1847 | var leadSurrogate = null;
1848 | var bytes = [];
1849 |
1850 | for (var i = 0; i < length; ++i) {
1851 | codePoint = string.charCodeAt(i);
1852 |
1853 | // is surrogate component
1854 | if (codePoint > 0xD7FF && codePoint < 0xE000) {
1855 | // last char was a lead
1856 | if (!leadSurrogate) {
1857 | // no lead yet
1858 | if (codePoint > 0xDBFF) {
1859 | // unexpected trail
1860 | if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);
1861 | continue
1862 | } else if (i + 1 === length) {
1863 | // unpaired lead
1864 | if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);
1865 | continue
1866 | }
1867 |
1868 | // valid lead
1869 | leadSurrogate = codePoint;
1870 |
1871 | continue
1872 | }
1873 |
1874 | // 2 leads in a row
1875 | if (codePoint < 0xDC00) {
1876 | if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);
1877 | leadSurrogate = codePoint;
1878 | continue
1879 | }
1880 |
1881 | // valid surrogate pair
1882 | codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000;
1883 | } else if (leadSurrogate) {
1884 | // valid bmp char, but last char was a lead
1885 | if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);
1886 | }
1887 |
1888 | leadSurrogate = null;
1889 |
1890 | // encode utf8
1891 | if (codePoint < 0x80) {
1892 | if ((units -= 1) < 0) break
1893 | bytes.push(codePoint);
1894 | } else if (codePoint < 0x800) {
1895 | if ((units -= 2) < 0) break
1896 | bytes.push(
1897 | codePoint >> 0x6 | 0xC0,
1898 | codePoint & 0x3F | 0x80
1899 | );
1900 | } else if (codePoint < 0x10000) {
1901 | if ((units -= 3) < 0) break
1902 | bytes.push(
1903 | codePoint >> 0xC | 0xE0,
1904 | codePoint >> 0x6 & 0x3F | 0x80,
1905 | codePoint & 0x3F | 0x80
1906 | );
1907 | } else if (codePoint < 0x110000) {
1908 | if ((units -= 4) < 0) break
1909 | bytes.push(
1910 | codePoint >> 0x12 | 0xF0,
1911 | codePoint >> 0xC & 0x3F | 0x80,
1912 | codePoint >> 0x6 & 0x3F | 0x80,
1913 | codePoint & 0x3F | 0x80
1914 | );
1915 | } else {
1916 | throw new Error('Invalid code point')
1917 | }
1918 | }
1919 |
1920 | return bytes
1921 | }
1922 |
1923 | function asciiToBytes (str) {
1924 | var byteArray = [];
1925 | for (var i = 0; i < str.length; ++i) {
1926 | // Node's code seems to be doing this and not & 0x7F..
1927 | byteArray.push(str.charCodeAt(i) & 0xFF);
1928 | }
1929 | return byteArray
1930 | }
1931 |
1932 | function utf16leToBytes (str, units) {
1933 | var c, hi, lo;
1934 | var byteArray = [];
1935 | for (var i = 0; i < str.length; ++i) {
1936 | if ((units -= 2) < 0) break
1937 |
1938 | c = str.charCodeAt(i);
1939 | hi = c >> 8;
1940 | lo = c % 256;
1941 | byteArray.push(lo);
1942 | byteArray.push(hi);
1943 | }
1944 |
1945 | return byteArray
1946 | }
1947 |
1948 |
1949 | function base64ToBytes (str) {
1950 | return toByteArray(base64clean(str))
1951 | }
1952 |
1953 | function blitBuffer (src, dst, offset, length) {
1954 | for (var i = 0; i < length; ++i) {
1955 | if ((i + offset >= dst.length) || (i >= src.length)) break
1956 | dst[i + offset] = src[i];
1957 | }
1958 | return i
1959 | }
1960 |
1961 | function isnan (val) {
1962 | return val !== val // eslint-disable-line no-self-compare
1963 | }
1964 |
1965 |
1966 | // the following is from is-buffer, also by Feross Aboukhadijeh and with same lisence
1967 | // The _isBuffer check is for Safari 5-7 support, because it's missing
1968 | // Object.prototype.constructor. Remove this eventually
1969 | function isBuffer(obj) {
1970 | return obj != null && (!!obj._isBuffer || isFastBuffer(obj) || isSlowBuffer(obj))
1971 | }
1972 |
1973 | function isFastBuffer (obj) {
1974 | return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj)
1975 | }
1976 |
1977 | // For Node v0.10 support. Remove this eventually.
1978 | function isSlowBuffer (obj) {
1979 | return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isFastBuffer(obj.slice(0, 0))
1980 | }
1981 |
1982 | export { Buffer as B };
1983 |
--------------------------------------------------------------------------------
/web_modules/es-module-shims/wasm.js:
--------------------------------------------------------------------------------
1 | import { B as Buffer } from '../_chunks/polyfills-CU6gNi7m.js';
2 |
3 | /* ES Module Shims Wasm 1.10.0 */ (function() {
4 | const hasDocument = typeof document !== 'undefined';
5 | const noop = ()=>{};
6 | const optionsScript = hasDocument ? document.querySelector('script[type=esms-options]') : undefined;
7 | const esmsInitOptions = optionsScript ? JSON.parse(optionsScript.innerHTML) : {};
8 | Object.assign(esmsInitOptions, self.esmsInitOptions || {});
9 | let shimMode = hasDocument ? !!esmsInitOptions.shimMode : true;
10 | const importHook = globalHook(shimMode && esmsInitOptions.onimport);
11 | const resolveHook = globalHook(shimMode && esmsInitOptions.resolve);
12 | let fetchHook = esmsInitOptions.fetch ? globalHook(esmsInitOptions.fetch) : fetch;
13 | const metaHook = esmsInitOptions.meta ? globalHook(shimMode && esmsInitOptions.meta) : noop;
14 | const mapOverrides = esmsInitOptions.mapOverrides;
15 | let nonce = esmsInitOptions.nonce;
16 | if (!nonce && hasDocument) {
17 | const nonceElement = document.querySelector('script[nonce]');
18 | if (nonceElement) nonce = nonceElement.nonce || nonceElement.getAttribute('nonce');
19 | }
20 | const onerror = globalHook(esmsInitOptions.onerror || noop);
21 | const { revokeBlobURLs, noLoadEventRetriggers, globalLoadEventRetrigger, enforceIntegrity } = esmsInitOptions;
22 | function globalHook(name) {
23 | return typeof name === 'string' ? self[name] : name;
24 | }
25 | const enable = Array.isArray(esmsInitOptions.polyfillEnable) ? esmsInitOptions.polyfillEnable : [];
26 | const cssModulesEnabled = enable.includes('css-modules');
27 | const jsonModulesEnabled = enable.includes('json-modules');
28 | const wasmModulesEnabled = enable.includes('wasm-modules');
29 | const sourcePhaseEnabled = enable.includes('source-phase');
30 | const onpolyfill = esmsInitOptions.onpolyfill ? globalHook(esmsInitOptions.onpolyfill) : ()=>{
31 | console.log(`%c^^ Module error above is polyfilled and can be ignored ^^`, 'font-weight:900;color:#391');
32 | };
33 | const edge = !navigator.userAgentData && !!navigator.userAgent.match(/Edge\/\d+\.\d+/);
34 | const baseUrl = hasDocument ? document.baseURI : `${location.protocol}//${location.host}${location.pathname.includes('/') ? location.pathname.slice(0, location.pathname.lastIndexOf('/') + 1) : location.pathname}`;
35 | const createBlob = (source, type)=>{
36 | if (type === void 0) type = 'text/javascript';
37 | return URL.createObjectURL(new Blob([
38 | source
39 | ], {
40 | type
41 | }));
42 | };
43 | let { skip } = esmsInitOptions;
44 | if (Array.isArray(skip)) {
45 | const l = skip.map((s)=>new URL(s, baseUrl).href);
46 | skip = (s)=>l.some((i)=>i[i.length - 1] === '/' && s.startsWith(i) || s === i);
47 | } else if (typeof skip === 'string') {
48 | const r = new RegExp(skip);
49 | skip = (s)=>r.test(s);
50 | } else if (skip instanceof RegExp) {
51 | skip = (s)=>skip.test(s);
52 | }
53 | const dispatchError = (error)=>self.dispatchEvent(Object.assign(new Event('error'), {
54 | error
55 | }));
56 | const throwError = (err)=>{
57 | (self.reportError || dispatchError)(err), void onerror(err);
58 | };
59 | function fromParent(parent) {
60 | return parent ? ` imported from ${parent}` : '';
61 | }
62 | let importMapSrcOrLazy = false;
63 | function setImportMapSrcOrLazy() {
64 | importMapSrcOrLazy = true;
65 | }
66 | // shim mode is determined on initialization, no late shim mode
67 | if (!shimMode) {
68 | if (document.querySelectorAll('script[type=module-shim],script[type=importmap-shim],link[rel=modulepreload-shim]').length) {
69 | shimMode = true;
70 | } else {
71 | let seenScript = false;
72 | for (const script of document.querySelectorAll('script[type=module],script[type=importmap]')){
73 | if (!seenScript) {
74 | if (script.type === 'module' && !script.ep) seenScript = true;
75 | } else if (script.type === 'importmap' && seenScript) {
76 | importMapSrcOrLazy = true;
77 | break;
78 | }
79 | }
80 | }
81 | }
82 | const backslashRegEx = /\\/g;
83 | function asURL(url) {
84 | try {
85 | if (url.indexOf(':') !== -1) return new URL(url).href;
86 | } catch (_) {}
87 | }
88 | function resolveUrl(relUrl, parentUrl) {
89 | return resolveIfNotPlainOrUrl(relUrl, parentUrl) || asURL(relUrl) || resolveIfNotPlainOrUrl('./' + relUrl, parentUrl);
90 | }
91 | function resolveIfNotPlainOrUrl(relUrl, parentUrl) {
92 | const hIdx = parentUrl.indexOf('#'), qIdx = parentUrl.indexOf('?');
93 | if (hIdx + qIdx > -2) parentUrl = parentUrl.slice(0, hIdx === -1 ? qIdx : qIdx === -1 || qIdx > hIdx ? hIdx : qIdx);
94 | if (relUrl.indexOf('\\') !== -1) relUrl = relUrl.replace(backslashRegEx, '/');
95 | // protocol-relative
96 | if (relUrl[0] === '/' && relUrl[1] === '/') {
97 | return parentUrl.slice(0, parentUrl.indexOf(':') + 1) + relUrl;
98 | } else if (relUrl[0] === '.' && (relUrl[1] === '/' || relUrl[1] === '.' && (relUrl[2] === '/' || relUrl.length === 2 && (relUrl += '/')) || relUrl.length === 1 && (relUrl += '/')) || relUrl[0] === '/') {
99 | const parentProtocol = parentUrl.slice(0, parentUrl.indexOf(':') + 1);
100 | if (parentProtocol === 'blob:') {
101 | throw new TypeError(`Failed to resolve module specifier "${relUrl}". Invalid relative url or base scheme isn't hierarchical.`);
102 | }
103 | // Disabled, but these cases will give inconsistent results for deep backtracking
104 | //if (parentUrl[parentProtocol.length] !== '/')
105 | // throw new Error('Cannot resolve');
106 | // read pathname from parent URL
107 | // pathname taken to be part after leading "/"
108 | let pathname;
109 | if (parentUrl[parentProtocol.length + 1] === '/') {
110 | // resolving to a :// so we need to read out the auth and host
111 | if (parentProtocol !== 'file:') {
112 | pathname = parentUrl.slice(parentProtocol.length + 2);
113 | pathname = pathname.slice(pathname.indexOf('/') + 1);
114 | } else {
115 | pathname = parentUrl.slice(8);
116 | }
117 | } else {
118 | // resolving to :/ so pathname is the /... part
119 | pathname = parentUrl.slice(parentProtocol.length + (parentUrl[parentProtocol.length] === '/'));
120 | }
121 | if (relUrl[0] === '/') return parentUrl.slice(0, parentUrl.length - pathname.length - 1) + relUrl;
122 | // join together and split for removal of .. and . segments
123 | // looping the string instead of anything fancy for perf reasons
124 | // '../../../../../z' resolved to 'x/y' is just 'z'
125 | const segmented = pathname.slice(0, pathname.lastIndexOf('/') + 1) + relUrl;
126 | const output = [];
127 | let segmentIndex = -1;
128 | for(let i = 0; i < segmented.length; i++){
129 | // busy reading a segment - only terminate on '/'
130 | if (segmentIndex !== -1) {
131 | if (segmented[i] === '/') {
132 | output.push(segmented.slice(segmentIndex, i + 1));
133 | segmentIndex = -1;
134 | }
135 | continue;
136 | } else if (segmented[i] === '.') {
137 | // ../ segment
138 | if (segmented[i + 1] === '.' && (segmented[i + 2] === '/' || i + 2 === segmented.length)) {
139 | output.pop();
140 | i += 2;
141 | continue;
142 | } else if (segmented[i + 1] === '/' || i + 1 === segmented.length) {
143 | i += 1;
144 | continue;
145 | }
146 | }
147 | // it is the start of a new segment
148 | while(segmented[i] === '/')i++;
149 | segmentIndex = i;
150 | }
151 | // finish reading out the last segment
152 | if (segmentIndex !== -1) output.push(segmented.slice(segmentIndex));
153 | return parentUrl.slice(0, parentUrl.length - pathname.length) + output.join('');
154 | }
155 | }
156 | function resolveAndComposeImportMap(json, baseUrl, parentMap) {
157 | const outMap = {
158 | imports: Object.assign({}, parentMap.imports),
159 | scopes: Object.assign({}, parentMap.scopes),
160 | integrity: Object.assign({}, parentMap.integrity)
161 | };
162 | if (json.imports) resolveAndComposePackages(json.imports, outMap.imports, baseUrl, parentMap);
163 | if (json.scopes) for(let s in json.scopes){
164 | const resolvedScope = resolveUrl(s, baseUrl);
165 | resolveAndComposePackages(json.scopes[s], outMap.scopes[resolvedScope] || (outMap.scopes[resolvedScope] = {}), baseUrl, parentMap);
166 | }
167 | if (json.integrity) resolveAndComposeIntegrity(json.integrity, outMap.integrity, baseUrl);
168 | return outMap;
169 | }
170 | function getMatch(path, matchObj) {
171 | if (matchObj[path]) return path;
172 | let sepIndex = path.length;
173 | do {
174 | const segment = path.slice(0, sepIndex + 1);
175 | if (segment in matchObj) return segment;
176 | }while ((sepIndex = path.lastIndexOf('/', sepIndex - 1)) !== -1);
177 | }
178 | function applyPackages(id, packages) {
179 | const pkgName = getMatch(id, packages);
180 | if (pkgName) {
181 | const pkg = packages[pkgName];
182 | if (pkg === null) return;
183 | return pkg + id.slice(pkgName.length);
184 | }
185 | }
186 | function resolveImportMap(importMap, resolvedOrPlain, parentUrl) {
187 | let scopeUrl = parentUrl && getMatch(parentUrl, importMap.scopes);
188 | while(scopeUrl){
189 | const packageResolution = applyPackages(resolvedOrPlain, importMap.scopes[scopeUrl]);
190 | if (packageResolution) return packageResolution;
191 | scopeUrl = getMatch(scopeUrl.slice(0, scopeUrl.lastIndexOf('/')), importMap.scopes);
192 | }
193 | return applyPackages(resolvedOrPlain, importMap.imports) || resolvedOrPlain.indexOf(':') !== -1 && resolvedOrPlain;
194 | }
195 | function resolveAndComposePackages(packages, outPackages, baseUrl, parentMap) {
196 | for(let p in packages){
197 | const resolvedLhs = resolveIfNotPlainOrUrl(p, baseUrl) || p;
198 | if ((!shimMode || !mapOverrides) && outPackages[resolvedLhs] && outPackages[resolvedLhs] !== packages[resolvedLhs]) {
199 | throw Error(`Rejected map override "${resolvedLhs}" from ${outPackages[resolvedLhs]} to ${packages[resolvedLhs]}.`);
200 | }
201 | let target = packages[p];
202 | if (typeof target !== 'string') continue;
203 | const mapped = resolveImportMap(parentMap, resolveIfNotPlainOrUrl(target, baseUrl) || target, baseUrl);
204 | if (mapped) {
205 | outPackages[resolvedLhs] = mapped;
206 | continue;
207 | }
208 | console.warn(`Mapping "${p}" -> "${packages[p]}" does not resolve`);
209 | }
210 | }
211 | function resolveAndComposeIntegrity(integrity, outIntegrity, baseUrl) {
212 | for(let p in integrity){
213 | const resolvedLhs = resolveIfNotPlainOrUrl(p, baseUrl) || p;
214 | if ((!shimMode || !mapOverrides) && outIntegrity[resolvedLhs] && outIntegrity[resolvedLhs] !== integrity[resolvedLhs]) {
215 | throw Error(`Rejected map integrity override "${resolvedLhs}" from ${outIntegrity[resolvedLhs]} to ${integrity[resolvedLhs]}.`);
216 | }
217 | outIntegrity[resolvedLhs] = integrity[p];
218 | }
219 | }
220 | let dynamicImport = !hasDocument && (0, eval)('u=>import(u)');
221 | let supportsDynamicImport;
222 | const dynamicImportCheck = hasDocument && new Promise((resolve)=>{
223 | const s = Object.assign(document.createElement('script'), {
224 | src: createBlob('self._d=u=>import(u)'),
225 | ep: true
226 | });
227 | s.setAttribute('nonce', nonce);
228 | s.addEventListener('load', ()=>{
229 | if (!(supportsDynamicImport = !!(dynamicImport = self._d))) {
230 | let err;
231 | window.addEventListener('error', (_err)=>err = _err);
232 | dynamicImport = (url, opts)=>new Promise((resolve, reject)=>{
233 | const s = Object.assign(document.createElement('script'), {
234 | type: 'module',
235 | src: createBlob(`import*as m from'${url}';self._esmsi=m`)
236 | });
237 | err = undefined;
238 | s.ep = true;
239 | if (nonce) s.setAttribute('nonce', nonce);
240 | // Safari is unique in supporting module script error events
241 | s.addEventListener('error', cb);
242 | s.addEventListener('load', cb);
243 | function cb(_err) {
244 | document.head.removeChild(s);
245 | if (self._esmsi) {
246 | resolve(self._esmsi, baseUrl);
247 | self._esmsi = undefined;
248 | } else {
249 | reject(!(_err instanceof Event) && _err || err && err.error || new Error(`Error loading ${opts && opts.errUrl || url} (${s.src}).`));
250 | err = undefined;
251 | }
252 | }
253 | document.head.appendChild(s);
254 | });
255 | }
256 | document.head.removeChild(s);
257 | delete self._d;
258 | resolve();
259 | });
260 | document.head.appendChild(s);
261 | });
262 | // support browsers without dynamic import support (eg Firefox 6x)
263 | let supportsJsonAssertions = false;
264 | let supportsCssAssertions = false;
265 | const supports = hasDocument && HTMLScriptElement.supports;
266 | let supportsImportMaps = supports && supports.name === 'supports' && supports('importmap');
267 | let supportsImportMeta = supportsDynamicImport;
268 | let supportsWasmModules = false;
269 | let supportsSourcePhase = false;
270 | const wasmBytes = [
271 | 0,
272 | 97,
273 | 115,
274 | 109,
275 | 1,
276 | 0,
277 | 0,
278 | 0
279 | ];
280 | let featureDetectionPromise = Promise.resolve(dynamicImportCheck).then(()=>{
281 | if (!supportsDynamicImport) return;
282 | if (!hasDocument) return Promise.all([
283 | supportsImportMaps || dynamicImport(createBlob('import.meta')).then(()=>supportsImportMeta = true, noop),
284 | cssModulesEnabled && dynamicImport(createBlob(`import"${createBlob('', 'text/css')}"with{type:"css"}`)).then(()=>supportsCssAssertions = true, noop),
285 | jsonModulesEnabled && dynamicImport(createBlob(`import"${createBlob('{}', 'text/json')}"with{type:"json"}`)).then(()=>supportsJsonAssertions = true, noop),
286 | wasmModulesEnabled && dynamicImport(createBlob(`import"${createBlob(new Uint8Array(wasmBytes), 'application/wasm')}"`)).then(()=>supportsWasmModules = true, noop),
287 | wasmModulesEnabled && sourcePhaseEnabled && dynamicImport(createBlob(`import source x from"${createBlob(new Uint8Array(wasmBytes), 'application/wasm')}"`)).then(()=>supportsSourcePhase = true, noop)
288 | ]);
289 | return new Promise((resolve)=>{
290 | const iframe = document.createElement('iframe');
291 | iframe.style.display = 'none';
292 | iframe.setAttribute('nonce', nonce);
293 | function cb(param) {
294 | let { data } = param;
295 | const isFeatureDetectionMessage = Array.isArray(data) && data[0] === 'esms';
296 | if (!isFeatureDetectionMessage) return;
297 | [, supportsImportMaps, supportsImportMeta, supportsCssAssertions, supportsJsonAssertions, supportsWasmModules, supportsSourcePhase] = data;
298 | resolve();
299 | document.head.removeChild(iframe);
300 | window.removeEventListener('message', cb, false);
301 | }
302 | window.addEventListener('message', cb, false);
303 | const importMapTest = `