@hcaptcha/react-hcaptcha 1.17.3 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js DELETED
@@ -1,484 +0,0 @@
1
- "use strict";
2
-
3
- var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
4
- var _typeof3 = require("@babel/runtime/helpers/typeof");
5
- Object.defineProperty(exports, "__esModule", {
6
- value: true
7
- });
8
- exports["default"] = void 0;
9
- var _typeof2 = _interopRequireDefault(require("@babel/runtime/helpers/typeof"));
10
- var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"));
11
- var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass"));
12
- var _possibleConstructorReturn2 = _interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn"));
13
- var _getPrototypeOf2 = _interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf"));
14
- var _assertThisInitialized2 = _interopRequireDefault(require("@babel/runtime/helpers/assertThisInitialized"));
15
- var _inherits2 = _interopRequireDefault(require("@babel/runtime/helpers/inherits"));
16
- var React = _interopRequireWildcard(require("react"));
17
- var _loader = require("@hcaptcha/loader");
18
- var _utils = require("./utils.js");
19
- function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(e) { return e ? t : r; })(e); }
20
- function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != _typeof3(e) && "function" != typeof e) return { "default": e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && Object.prototype.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n["default"] = e, t && t.set(e, n), n; }
21
- function _callSuper(t, o, e) { return o = (0, _getPrototypeOf2["default"])(o), (0, _possibleConstructorReturn2["default"])(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], (0, _getPrototypeOf2["default"])(t).constructor) : o.apply(t, e)); }
22
- function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
23
- var HCaptcha = /*#__PURE__*/function (_React$Component) {
24
- (0, _inherits2["default"])(HCaptcha, _React$Component);
25
- function HCaptcha(props) {
26
- var _this;
27
- (0, _classCallCheck2["default"])(this, HCaptcha);
28
- _this = _callSuper(this, HCaptcha, [props]);
29
-
30
- /**
31
- * Internal reference to track hCaptcha API
32
- *
33
- * Required as window is relative to initialization in application
34
- * not where the script and iFrames have been loaded.
35
- */
36
- _this._hcaptcha = undefined;
37
-
38
- // API Methods
39
- _this.renderCaptcha = _this.renderCaptcha.bind((0, _assertThisInitialized2["default"])(_this));
40
- _this.resetCaptcha = _this.resetCaptcha.bind((0, _assertThisInitialized2["default"])(_this));
41
- _this.removeCaptcha = _this.removeCaptcha.bind((0, _assertThisInitialized2["default"])(_this));
42
- _this.isReady = _this.isReady.bind((0, _assertThisInitialized2["default"])(_this));
43
- _this._onReady = null;
44
-
45
- // Event Handlers
46
- _this.loadCaptcha = _this.loadCaptcha.bind((0, _assertThisInitialized2["default"])(_this));
47
- _this.handleOnLoad = _this.handleOnLoad.bind((0, _assertThisInitialized2["default"])(_this));
48
- _this.handleSubmit = _this.handleSubmit.bind((0, _assertThisInitialized2["default"])(_this));
49
- _this.handleExpire = _this.handleExpire.bind((0, _assertThisInitialized2["default"])(_this));
50
- _this.handleError = _this.handleError.bind((0, _assertThisInitialized2["default"])(_this));
51
- _this.handleOpen = _this.handleOpen.bind((0, _assertThisInitialized2["default"])(_this));
52
- _this.handleClose = _this.handleClose.bind((0, _assertThisInitialized2["default"])(_this));
53
- _this.handleChallengeExpired = _this.handleChallengeExpired.bind((0, _assertThisInitialized2["default"])(_this));
54
- _this.ref = /*#__PURE__*/React.createRef();
55
- _this.apiScriptRequested = false;
56
- _this.sentryHub = null;
57
- _this.captchaId = '';
58
-
59
- /**
60
- * Tracks the currently pending async execute() promise.
61
- * Stores { resolve, reject } so we can cancel on unmount/errors/etc.
62
- */
63
- _this._pendingExecute = null;
64
- _this.state = {
65
- isApiReady: false,
66
- isRemoved: false,
67
- elementId: props.id
68
- };
69
- return _this;
70
- }
71
- (0, _createClass2["default"])(HCaptcha, [{
72
- key: "componentDidMount",
73
- value: function componentDidMount() {
74
- var _this2 = this;
75
- // Once captcha is mounted intialize hCaptcha - hCaptcha
76
- var element = (0, _utils.getMountElement)(this.props.scriptLocation);
77
- var frame = (0, _utils.getFrame)(element);
78
- this._hcaptcha = frame.window.hcaptcha || undefined;
79
- var isApiReady = typeof this._hcaptcha !== 'undefined';
80
-
81
- /*
82
- * Check if hCaptcha has already been loaded,
83
- * If Yes, render the captcha
84
- * If No, create script tag and wait to render the captcha
85
- */
86
- if (isApiReady) {
87
- this.setState({
88
- isApiReady: true
89
- }, function () {
90
- _this2.renderCaptcha();
91
- });
92
- return;
93
- }
94
- this.loadCaptcha();
95
- }
96
- }, {
97
- key: "componentWillUnmount",
98
- value: function componentWillUnmount() {
99
- var hcaptcha = this._hcaptcha;
100
- var captchaId = this.captchaId;
101
- this._cancelPendingExecute('react-component-unmounted');
102
- if (!this.isReady()) {
103
- return;
104
- }
105
-
106
- // Reset any stored variables / timers when unmounting
107
- hcaptcha.reset(captchaId);
108
- hcaptcha.remove(captchaId);
109
- }
110
- }, {
111
- key: "shouldComponentUpdate",
112
- value: function shouldComponentUpdate(nextProps, nextState) {
113
- // Prevent component re-rendering when these internal state variables are updated
114
- if (this.state.isApiReady !== nextState.isApiReady || this.state.isRemoved !== nextState.isRemoved) {
115
- return false;
116
- }
117
- return true;
118
- }
119
- }, {
120
- key: "componentDidUpdate",
121
- value: function componentDidUpdate(prevProps) {
122
- var _this3 = this;
123
- // Prop Keys that could change
124
- var keys = ['sitekey', 'size', 'theme', 'tabindex', 'languageOverride', 'endpoint'];
125
- // See if any props changed during component update
126
- var match = keys.every(function (key) {
127
- return prevProps[key] === _this3.props[key];
128
- });
129
-
130
- // If they have changed, remove current captcha and render a new one
131
- if (!match) {
132
- this.removeCaptcha(function () {
133
- _this3.renderCaptcha();
134
- });
135
- }
136
- }
137
- }, {
138
- key: "loadCaptcha",
139
- value: function loadCaptcha() {
140
- if (this.apiScriptRequested) {
141
- return;
142
- }
143
- var _this$props = this.props,
144
- apihost = _this$props.apihost,
145
- assethost = _this$props.assethost,
146
- endpoint = _this$props.endpoint,
147
- host = _this$props.host,
148
- imghost = _this$props.imghost,
149
- hl = _this$props.languageOverride,
150
- reCaptchaCompat = _this$props.reCaptchaCompat,
151
- reportapi = _this$props.reportapi,
152
- sentry = _this$props.sentry,
153
- custom = _this$props.custom,
154
- loadAsync = _this$props.loadAsync,
155
- scriptLocation = _this$props.scriptLocation,
156
- scriptSource = _this$props.scriptSource,
157
- secureApi = _this$props.secureApi,
158
- _this$props$cleanup = _this$props.cleanup,
159
- cleanup = _this$props$cleanup === void 0 ? true : _this$props$cleanup,
160
- userJourneys = _this$props.userJourneys;
161
- var mountParams = {
162
- render: 'explicit',
163
- apihost: apihost,
164
- assethost: assethost,
165
- endpoint: endpoint,
166
- hl: hl,
167
- host: host,
168
- imghost: imghost,
169
- recaptchacompat: reCaptchaCompat === false ? 'off' : null,
170
- reportapi: reportapi,
171
- sentry: sentry,
172
- custom: custom,
173
- loadAsync: loadAsync,
174
- scriptLocation: scriptLocation,
175
- scriptSource: scriptSource,
176
- secureApi: secureApi,
177
- cleanup: cleanup,
178
- uj: userJourneys !== undefined ? userJourneys : false
179
- };
180
- (0, _loader.hCaptchaLoader)(mountParams).then(this.handleOnLoad, this.handleError)["catch"](this.handleError);
181
- this.apiScriptRequested = true;
182
- }
183
- }, {
184
- key: "renderCaptcha",
185
- value: function renderCaptcha(onRender) {
186
- var _this4 = this;
187
- var onReady = this.props.onReady;
188
- var isApiReady = this.state.isApiReady;
189
- var captchaId = this.captchaId;
190
-
191
- // Prevent calling hCaptcha render on two conditions:
192
- // • API is not ready
193
- // • Component has already been mounted
194
- if (!isApiReady || captchaId) return;
195
- var renderParams = Object.assign({
196
- "open-callback": this.handleOpen,
197
- "close-callback": this.handleClose,
198
- "error-callback": this.handleError,
199
- "chalexpired-callback": this.handleChallengeExpired,
200
- "expired-callback": this.handleExpire,
201
- "callback": this.handleSubmit
202
- }, this.props, {
203
- hl: this.props.hl || this.props.languageOverride,
204
- languageOverride: undefined
205
- });
206
- var hcaptcha = this._hcaptcha;
207
- //Render hCaptcha widget and provide necessary callbacks - hCaptcha
208
- var id = hcaptcha.render(this.ref.current, renderParams);
209
- this.captchaId = id;
210
- this.setState({
211
- isRemoved: false
212
- }, function () {
213
- onRender && onRender();
214
- onReady && onReady();
215
- _this4._onReady && _this4._onReady(id);
216
- });
217
- }
218
- }, {
219
- key: "resetCaptcha",
220
- value: function resetCaptcha() {
221
- var hcaptcha = this._hcaptcha;
222
- var captchaId = this.captchaId;
223
- if (!this.isReady()) {
224
- return;
225
- }
226
-
227
- // Reset captcha state, removes stored token and unticks checkbox
228
- hcaptcha.reset(captchaId);
229
- this._cancelPendingExecute('hcaptcha-reset');
230
- }
231
- }, {
232
- key: "removeCaptcha",
233
- value: function removeCaptcha(callback) {
234
- var _this5 = this;
235
- var hcaptcha = this._hcaptcha;
236
- var captchaId = this.captchaId;
237
- this._cancelPendingExecute('hcaptcha-removed');
238
- if (!this.isReady()) {
239
- return;
240
- }
241
- this.setState({
242
- isRemoved: true
243
- }, function () {
244
- _this5.captchaId = '';
245
- hcaptcha.remove(captchaId);
246
- callback && callback();
247
- });
248
- }
249
- }, {
250
- key: "handleOnLoad",
251
- value: function handleOnLoad() {
252
- var _this6 = this;
253
- this.setState({
254
- isApiReady: true
255
- }, function () {
256
- var element = (0, _utils.getMountElement)(_this6.props.scriptLocation);
257
- var frame = (0, _utils.getFrame)(element);
258
- _this6._hcaptcha = frame.window.hcaptcha;
259
-
260
- // render captcha and wait for captcha id
261
- _this6.renderCaptcha(function () {
262
- // trigger onLoad if it exists
263
-
264
- var onLoad = _this6.props.onLoad;
265
- if (onLoad) onLoad();
266
- });
267
- });
268
- }
269
- }, {
270
- key: "handleSubmit",
271
- value: function handleSubmit(event) {
272
- var onVerify = this.props.onVerify;
273
- var isRemoved = this.state.isRemoved;
274
- var hcaptcha = this._hcaptcha;
275
- var captchaId = this.captchaId;
276
- if (typeof hcaptcha === 'undefined' || isRemoved) return;
277
- var token = hcaptcha.getResponse(captchaId); //Get response token from hCaptcha widget
278
- var ekey = hcaptcha.getRespKey(captchaId); //Get current challenge session id from hCaptcha widget
279
- if (onVerify) onVerify(token, ekey); //Dispatch event to verify user response
280
- }
281
- }, {
282
- key: "handleExpire",
283
- value: function handleExpire() {
284
- var onExpire = this.props.onExpire;
285
- var hcaptcha = this._hcaptcha;
286
- var captchaId = this.captchaId;
287
- if (!this.isReady()) {
288
- return;
289
- }
290
- hcaptcha.reset(captchaId); // If hCaptcha runs into error, reset captcha - hCaptcha
291
-
292
- if (onExpire) onExpire();
293
- }
294
- }, {
295
- key: "handleError",
296
- value: function handleError(event) {
297
- var onError = this.props.onError;
298
- var hcaptcha = this._hcaptcha;
299
- var captchaId = this.captchaId;
300
- if (this.isReady()) {
301
- // If hCaptcha runs into error, reset captcha - hCaptcha
302
- hcaptcha.reset(captchaId);
303
- }
304
- if (onError) onError(event);
305
- }
306
- }, {
307
- key: "isReady",
308
- value: function isReady() {
309
- var _this$state = this.state,
310
- isApiReady = _this$state.isApiReady,
311
- isRemoved = _this$state.isRemoved;
312
- return isApiReady && !isRemoved;
313
- }
314
-
315
- /**
316
- * Cancel any pending async execute() promise
317
- * Called when the component unmounts, errors occur, resets, etc.
318
- */
319
- }, {
320
- key: "_cancelPendingExecute",
321
- value: function _cancelPendingExecute(reason) {
322
- if (!this._pendingExecute) {
323
- return;
324
- }
325
- var pending = this._pendingExecute;
326
- this._pendingExecute = null;
327
- var error = new Error(reason);
328
- pending.reject(error);
329
- }
330
- }, {
331
- key: "handleOpen",
332
- value: function handleOpen() {
333
- if (!this.isReady() || !this.props.onOpen) {
334
- return;
335
- }
336
- this.props.onOpen();
337
- }
338
- }, {
339
- key: "handleClose",
340
- value: function handleClose() {
341
- if (!this.isReady() || !this.props.onClose) {
342
- return;
343
- }
344
- this.props.onClose();
345
- }
346
- }, {
347
- key: "handleChallengeExpired",
348
- value: function handleChallengeExpired() {
349
- if (!this.isReady() || !this.props.onChalExpired) {
350
- return;
351
- }
352
- this.props.onChalExpired();
353
- }
354
- }, {
355
- key: "execute",
356
- value: function execute() {
357
- var _this7 = this;
358
- var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;
359
- opts = (0, _typeof2["default"])(opts) === 'object' ? opts : null;
360
- try {
361
- var hcaptcha = this._hcaptcha;
362
- var captchaId = this.captchaId;
363
-
364
- // Is an async execute and there's already 1 pending, cancel the old one.
365
- if (opts && opts.async && this._pendingExecute) {
366
- this._cancelPendingExecute('hcaptcha-execute-replaced');
367
- }
368
- if (!this.isReady()) {
369
- if (opts && opts.async) {
370
- return new Promise(function (resolve, reject) {
371
- _this7._pendingExecute = {
372
- resolve: resolve,
373
- reject: reject
374
- };
375
- _this7._onReady = function (id) {
376
- if (!_this7._pendingExecute) {
377
- return;
378
- }
379
- try {
380
- var _result = hcaptcha.execute(id, opts);
381
- if (_result && typeof _result.then === 'function') {
382
- _result.then(function (val) {
383
- _this7._pendingExecute = null;
384
- resolve(val);
385
- })["catch"](function (err) {
386
- _this7._pendingExecute = null;
387
- reject(err);
388
- });
389
- } else {
390
- _this7._pendingExecute = null;
391
- reject(new Error('hcaptcha-execute-no-promise'));
392
- }
393
- } catch (e) {
394
- _this7._pendingExecute = null;
395
- reject(e);
396
- }
397
- };
398
- });
399
- } else {
400
- // Non-async: don't return a promise.
401
- this._onReady = function (id) {
402
- hcaptcha.execute(id, opts);
403
- };
404
- return null;
405
- }
406
- }
407
-
408
- // hCaptcha is ready, execute directly.
409
- var result = hcaptcha.execute(captchaId, opts);
410
-
411
- // If it's async execute, track it.
412
- if (opts && opts.async && result && typeof result.then === 'function') {
413
- return new Promise(function (resolve, reject) {
414
- _this7._pendingExecute = {
415
- resolve: resolve,
416
- reject: reject
417
- };
418
- result.then(function (val) {
419
- _this7._pendingExecute = null;
420
- resolve(val);
421
- })["catch"](function (err) {
422
- _this7._pendingExecute = null;
423
- reject(err);
424
- });
425
- });
426
- }
427
- return result;
428
- } catch (error) {
429
- if (opts && opts.async) {
430
- return Promise.reject(error);
431
- }
432
- return null;
433
- }
434
- }
435
- }, {
436
- key: "close",
437
- value: function close() {
438
- var hcaptcha = this._hcaptcha;
439
- var captchaId = this.captchaId;
440
- this._cancelPendingExecute('hcaptcha-closed');
441
- if (!this.isReady()) {
442
- return;
443
- }
444
- return hcaptcha.close(captchaId);
445
- }
446
- }, {
447
- key: "setData",
448
- value: function setData(data) {
449
- var hcaptcha = this._hcaptcha;
450
- var captchaId = this.captchaId;
451
- if (!this.isReady()) {
452
- return;
453
- }
454
- if (data && (0, _typeof2["default"])(data) !== "object") {
455
- data = null;
456
- }
457
- hcaptcha.setData(captchaId, data);
458
- }
459
- }, {
460
- key: "getResponse",
461
- value: function getResponse() {
462
- var hcaptcha = this._hcaptcha;
463
- return hcaptcha.getResponse(this.captchaId);
464
- }
465
- }, {
466
- key: "getRespKey",
467
- value: function getRespKey() {
468
- var hcaptcha = this._hcaptcha;
469
- return hcaptcha.getRespKey(this.captchaId);
470
- }
471
- }, {
472
- key: "render",
473
- value: function render() {
474
- var elementId = this.state.elementId;
475
- return /*#__PURE__*/React.createElement("div", {
476
- ref: this.ref,
477
- id: elementId
478
- });
479
- }
480
- }]);
481
- return HCaptcha;
482
- }(React.Component);
483
- var _default = exports["default"] = HCaptcha;
484
- module.exports = exports.default;
package/dist/utils.js DELETED
@@ -1,18 +0,0 @@
1
- "use strict";
2
-
3
- Object.defineProperty(exports, "__esModule", {
4
- value: true
5
- });
6
- exports.getFrame = getFrame;
7
- exports.getMountElement = getMountElement;
8
- function getFrame(element) {
9
- var doc = element && element.ownerDocument || document;
10
- var win = doc.defaultView || doc.parentWindow || window;
11
- return {
12
- document: doc,
13
- window: win
14
- };
15
- }
16
- function getMountElement(element) {
17
- return element || document.head;
18
- }
@@ -1,3 +0,0 @@
1
- import { createContext } from "react";
2
-
3
- export const HCaptchaContext = createContext();
@@ -1,98 +0,0 @@
1
- import React, { useEffect, useRef, useState } from "react";
2
- import HCaptcha from "../index.js";
3
- import { HCaptchaContext } from "./Context";
4
-
5
- export const HCaptchaProvider = ({
6
- sitekey = null,
7
- size = "normal",
8
- theme = "light",
9
- rqdata = null,
10
- languageOverride = null,
11
- onVerify,
12
- onError,
13
- children,
14
- }) => {
15
- const hcaptchaRef = useRef(null);
16
-
17
- const [ready, setReady] = useState(false);
18
- const [token, setToken] = useState(null);
19
- const [error, setError] = useState(null);
20
-
21
- const handleReady = () => {
22
- setReady(true);
23
- };
24
-
25
- const handleError = (error) => {
26
- setError(error);
27
- onError && onError(error);
28
- };
29
-
30
- const handleExpire = () => {
31
- setToken(null);
32
- };
33
-
34
- const handleVerify = (token) => {
35
- setToken(token);
36
- onVerify && onVerify(token);
37
- };
38
-
39
- const executeInstance = async (config = {}) => {
40
- try {
41
- if (!ready) {
42
- throw new Error("hCaptcha not ready");
43
- }
44
-
45
- if (token) {
46
- resetInstance();
47
- }
48
-
49
- const { response } = await hcaptchaRef.current.execute({
50
- async: true,
51
- ...(config.rqdata ? { rqdata: config.rqdata } : {}),
52
- });
53
-
54
- setToken(response);
55
-
56
- return response;
57
- } catch (error) {
58
- setError(error);
59
- onError && onError(error);
60
- }
61
- };
62
-
63
- const resetInstance = () => {
64
- hcaptchaRef?.current?.resetCaptcha();
65
- };
66
-
67
- useEffect(() => {
68
- if (rqdata) {
69
- hcaptchaRef?.current?.setData(rqdata);
70
- }
71
- }, [rqdata]);
72
-
73
- return (
74
- <HCaptchaContext.Provider
75
- value={{
76
- sitekey,
77
- error,
78
- token,
79
- ready,
80
- executeInstance,
81
- resetInstance,
82
- }}
83
- >
84
- {children}
85
- <HCaptcha
86
- sitekey={sitekey}
87
- size={size}
88
- theme={theme}
89
- languageOverride={languageOverride}
90
- onReady={handleReady}
91
- onVerify={handleVerify}
92
- onExpire={handleExpire}
93
- onError={handleError}
94
- ref={hcaptchaRef}
95
- ></HCaptcha>
96
- </HCaptchaContext.Provider>
97
- );
98
- };
@@ -1,2 +0,0 @@
1
- export { useHCaptcha } from "./useHCaptcha.tsx";
2
- export { HCaptchaProvider } from "./Provider.jsx";
@@ -1,4 +0,0 @@
1
- import { useContext } from "react";
2
-
3
- import { HCaptchaContext } from "./Context.jsx";
4
- export const useHCaptcha = () => useContext(HCaptchaContext);