@teactjs/runtime 0.1.0-alpha.5 → 0.1.0-alpha.7

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.
Files changed (2) hide show
  1. package/dist/index.js +126 -3785
  2. package/package.json +4 -4
package/dist/index.js CHANGED
@@ -1,923 +1,15 @@
1
1
  // @bun
2
- var __create = Object.create;
3
- var __getProtoOf = Object.getPrototypeOf;
4
- var __defProp = Object.defineProperty;
5
- var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __hasOwnProp = Object.prototype.hasOwnProperty;
7
- var __toESM = (mod, isNodeMode, target) => {
8
- target = mod != null ? __create(__getProtoOf(mod)) : {};
9
- const to = isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target;
10
- for (let key of __getOwnPropNames(mod))
11
- if (!__hasOwnProp.call(to, key))
12
- __defProp(to, key, {
13
- get: () => mod[key],
14
- enumerable: true
15
- });
16
- return to;
17
- };
18
- var __commonJS = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports);
19
-
20
- // ../../node_modules/.bun/react@19.2.4/node_modules/react/cjs/react.development.js
21
- var require_react_development = __commonJS((exports, module) => {
22
- (function() {
23
- function defineDeprecationWarning(methodName, info) {
24
- Object.defineProperty(Component.prototype, methodName, {
25
- get: function() {
26
- console.warn("%s(...) is deprecated in plain JavaScript React classes. %s", info[0], info[1]);
27
- }
28
- });
29
- }
30
- function getIteratorFn(maybeIterable) {
31
- if (maybeIterable === null || typeof maybeIterable !== "object")
32
- return null;
33
- maybeIterable = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable["@@iterator"];
34
- return typeof maybeIterable === "function" ? maybeIterable : null;
35
- }
36
- function warnNoop(publicInstance, callerName) {
37
- publicInstance = (publicInstance = publicInstance.constructor) && (publicInstance.displayName || publicInstance.name) || "ReactClass";
38
- var warningKey = publicInstance + "." + callerName;
39
- didWarnStateUpdateForUnmountedComponent[warningKey] || (console.error("Can't call %s on a component that is not yet mounted. This is a no-op, but it might indicate a bug in your application. Instead, assign to `this.state` directly or define a `state = {};` class property with the desired state in the %s component.", callerName, publicInstance), didWarnStateUpdateForUnmountedComponent[warningKey] = true);
40
- }
41
- function Component(props, context, updater) {
42
- this.props = props;
43
- this.context = context;
44
- this.refs = emptyObject;
45
- this.updater = updater || ReactNoopUpdateQueue;
46
- }
47
- function ComponentDummy() {}
48
- function PureComponent(props, context, updater) {
49
- this.props = props;
50
- this.context = context;
51
- this.refs = emptyObject;
52
- this.updater = updater || ReactNoopUpdateQueue;
53
- }
54
- function noop() {}
55
- function testStringCoercion(value) {
56
- return "" + value;
57
- }
58
- function checkKeyStringCoercion(value) {
59
- try {
60
- testStringCoercion(value);
61
- var JSCompiler_inline_result = false;
62
- } catch (e) {
63
- JSCompiler_inline_result = true;
64
- }
65
- if (JSCompiler_inline_result) {
66
- JSCompiler_inline_result = console;
67
- var JSCompiler_temp_const = JSCompiler_inline_result.error;
68
- var JSCompiler_inline_result$jscomp$0 = typeof Symbol === "function" && Symbol.toStringTag && value[Symbol.toStringTag] || value.constructor.name || "Object";
69
- JSCompiler_temp_const.call(JSCompiler_inline_result, "The provided key is an unsupported type %s. This value must be coerced to a string before using it here.", JSCompiler_inline_result$jscomp$0);
70
- return testStringCoercion(value);
71
- }
72
- }
73
- function getComponentNameFromType(type) {
74
- if (type == null)
75
- return null;
76
- if (typeof type === "function")
77
- return type.$$typeof === REACT_CLIENT_REFERENCE ? null : type.displayName || type.name || null;
78
- if (typeof type === "string")
79
- return type;
80
- switch (type) {
81
- case REACT_FRAGMENT_TYPE:
82
- return "Fragment";
83
- case REACT_PROFILER_TYPE:
84
- return "Profiler";
85
- case REACT_STRICT_MODE_TYPE:
86
- return "StrictMode";
87
- case REACT_SUSPENSE_TYPE:
88
- return "Suspense";
89
- case REACT_SUSPENSE_LIST_TYPE:
90
- return "SuspenseList";
91
- case REACT_ACTIVITY_TYPE:
92
- return "Activity";
93
- }
94
- if (typeof type === "object")
95
- switch (typeof type.tag === "number" && console.error("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."), type.$$typeof) {
96
- case REACT_PORTAL_TYPE:
97
- return "Portal";
98
- case REACT_CONTEXT_TYPE:
99
- return type.displayName || "Context";
100
- case REACT_CONSUMER_TYPE:
101
- return (type._context.displayName || "Context") + ".Consumer";
102
- case REACT_FORWARD_REF_TYPE:
103
- var innerType = type.render;
104
- type = type.displayName;
105
- type || (type = innerType.displayName || innerType.name || "", type = type !== "" ? "ForwardRef(" + type + ")" : "ForwardRef");
106
- return type;
107
- case REACT_MEMO_TYPE:
108
- return innerType = type.displayName || null, innerType !== null ? innerType : getComponentNameFromType(type.type) || "Memo";
109
- case REACT_LAZY_TYPE:
110
- innerType = type._payload;
111
- type = type._init;
112
- try {
113
- return getComponentNameFromType(type(innerType));
114
- } catch (x) {}
115
- }
116
- return null;
117
- }
118
- function getTaskName(type) {
119
- if (type === REACT_FRAGMENT_TYPE)
120
- return "<>";
121
- if (typeof type === "object" && type !== null && type.$$typeof === REACT_LAZY_TYPE)
122
- return "<...>";
123
- try {
124
- var name = getComponentNameFromType(type);
125
- return name ? "<" + name + ">" : "<...>";
126
- } catch (x) {
127
- return "<...>";
128
- }
129
- }
130
- function getOwner() {
131
- var dispatcher = ReactSharedInternals.A;
132
- return dispatcher === null ? null : dispatcher.getOwner();
133
- }
134
- function UnknownOwner() {
135
- return Error("react-stack-top-frame");
136
- }
137
- function hasValidKey(config) {
138
- if (hasOwnProperty.call(config, "key")) {
139
- var getter = Object.getOwnPropertyDescriptor(config, "key").get;
140
- if (getter && getter.isReactWarning)
141
- return false;
142
- }
143
- return config.key !== undefined;
144
- }
145
- function defineKeyPropWarningGetter(props, displayName) {
146
- function warnAboutAccessingKey() {
147
- specialPropKeyWarningShown || (specialPropKeyWarningShown = true, console.error("%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://react.dev/link/special-props)", displayName));
148
- }
149
- warnAboutAccessingKey.isReactWarning = true;
150
- Object.defineProperty(props, "key", {
151
- get: warnAboutAccessingKey,
152
- configurable: true
153
- });
154
- }
155
- function elementRefGetterWithDeprecationWarning() {
156
- var componentName = getComponentNameFromType(this.type);
157
- didWarnAboutElementRef[componentName] || (didWarnAboutElementRef[componentName] = true, console.error("Accessing element.ref was removed in React 19. ref is now a regular prop. It will be removed from the JSX Element type in a future release."));
158
- componentName = this.props.ref;
159
- return componentName !== undefined ? componentName : null;
160
- }
161
- function ReactElement(type, key, props, owner, debugStack, debugTask) {
162
- var refProp = props.ref;
163
- type = {
164
- $$typeof: REACT_ELEMENT_TYPE,
165
- type,
166
- key,
167
- props,
168
- _owner: owner
169
- };
170
- (refProp !== undefined ? refProp : null) !== null ? Object.defineProperty(type, "ref", {
171
- enumerable: false,
172
- get: elementRefGetterWithDeprecationWarning
173
- }) : Object.defineProperty(type, "ref", { enumerable: false, value: null });
174
- type._store = {};
175
- Object.defineProperty(type._store, "validated", {
176
- configurable: false,
177
- enumerable: false,
178
- writable: true,
179
- value: 0
180
- });
181
- Object.defineProperty(type, "_debugInfo", {
182
- configurable: false,
183
- enumerable: false,
184
- writable: true,
185
- value: null
186
- });
187
- Object.defineProperty(type, "_debugStack", {
188
- configurable: false,
189
- enumerable: false,
190
- writable: true,
191
- value: debugStack
192
- });
193
- Object.defineProperty(type, "_debugTask", {
194
- configurable: false,
195
- enumerable: false,
196
- writable: true,
197
- value: debugTask
198
- });
199
- Object.freeze && (Object.freeze(type.props), Object.freeze(type));
200
- return type;
201
- }
202
- function cloneAndReplaceKey(oldElement, newKey) {
203
- newKey = ReactElement(oldElement.type, newKey, oldElement.props, oldElement._owner, oldElement._debugStack, oldElement._debugTask);
204
- oldElement._store && (newKey._store.validated = oldElement._store.validated);
205
- return newKey;
206
- }
207
- function validateChildKeys(node) {
208
- isValidElement(node) ? node._store && (node._store.validated = 1) : typeof node === "object" && node !== null && node.$$typeof === REACT_LAZY_TYPE && (node._payload.status === "fulfilled" ? isValidElement(node._payload.value) && node._payload.value._store && (node._payload.value._store.validated = 1) : node._store && (node._store.validated = 1));
209
- }
210
- function isValidElement(object) {
211
- return typeof object === "object" && object !== null && object.$$typeof === REACT_ELEMENT_TYPE;
212
- }
213
- function escape(key) {
214
- var escaperLookup = { "=": "=0", ":": "=2" };
215
- return "$" + key.replace(/[=:]/g, function(match) {
216
- return escaperLookup[match];
217
- });
218
- }
219
- function getElementKey(element, index) {
220
- return typeof element === "object" && element !== null && element.key != null ? (checkKeyStringCoercion(element.key), escape("" + element.key)) : index.toString(36);
221
- }
222
- function resolveThenable(thenable) {
223
- switch (thenable.status) {
224
- case "fulfilled":
225
- return thenable.value;
226
- case "rejected":
227
- throw thenable.reason;
228
- default:
229
- switch (typeof thenable.status === "string" ? thenable.then(noop, noop) : (thenable.status = "pending", thenable.then(function(fulfilledValue) {
230
- thenable.status === "pending" && (thenable.status = "fulfilled", thenable.value = fulfilledValue);
231
- }, function(error) {
232
- thenable.status === "pending" && (thenable.status = "rejected", thenable.reason = error);
233
- })), thenable.status) {
234
- case "fulfilled":
235
- return thenable.value;
236
- case "rejected":
237
- throw thenable.reason;
238
- }
239
- }
240
- throw thenable;
241
- }
242
- function mapIntoArray(children, array, escapedPrefix, nameSoFar, callback) {
243
- var type = typeof children;
244
- if (type === "undefined" || type === "boolean")
245
- children = null;
246
- var invokeCallback = false;
247
- if (children === null)
248
- invokeCallback = true;
249
- else
250
- switch (type) {
251
- case "bigint":
252
- case "string":
253
- case "number":
254
- invokeCallback = true;
255
- break;
256
- case "object":
257
- switch (children.$$typeof) {
258
- case REACT_ELEMENT_TYPE:
259
- case REACT_PORTAL_TYPE:
260
- invokeCallback = true;
261
- break;
262
- case REACT_LAZY_TYPE:
263
- return invokeCallback = children._init, mapIntoArray(invokeCallback(children._payload), array, escapedPrefix, nameSoFar, callback);
264
- }
265
- }
266
- if (invokeCallback) {
267
- invokeCallback = children;
268
- callback = callback(invokeCallback);
269
- var childKey = nameSoFar === "" ? "." + getElementKey(invokeCallback, 0) : nameSoFar;
270
- isArrayImpl(callback) ? (escapedPrefix = "", childKey != null && (escapedPrefix = childKey.replace(userProvidedKeyEscapeRegex, "$&/") + "/"), mapIntoArray(callback, array, escapedPrefix, "", function(c) {
271
- return c;
272
- })) : callback != null && (isValidElement(callback) && (callback.key != null && (invokeCallback && invokeCallback.key === callback.key || checkKeyStringCoercion(callback.key)), escapedPrefix = cloneAndReplaceKey(callback, escapedPrefix + (callback.key == null || invokeCallback && invokeCallback.key === callback.key ? "" : ("" + callback.key).replace(userProvidedKeyEscapeRegex, "$&/") + "/") + childKey), nameSoFar !== "" && invokeCallback != null && isValidElement(invokeCallback) && invokeCallback.key == null && invokeCallback._store && !invokeCallback._store.validated && (escapedPrefix._store.validated = 2), callback = escapedPrefix), array.push(callback));
273
- return 1;
274
- }
275
- invokeCallback = 0;
276
- childKey = nameSoFar === "" ? "." : nameSoFar + ":";
277
- if (isArrayImpl(children))
278
- for (var i = 0;i < children.length; i++)
279
- nameSoFar = children[i], type = childKey + getElementKey(nameSoFar, i), invokeCallback += mapIntoArray(nameSoFar, array, escapedPrefix, type, callback);
280
- else if (i = getIteratorFn(children), typeof i === "function")
281
- for (i === children.entries && (didWarnAboutMaps || console.warn("Using Maps as children is not supported. Use an array of keyed ReactElements instead."), didWarnAboutMaps = true), children = i.call(children), i = 0;!(nameSoFar = children.next()).done; )
282
- nameSoFar = nameSoFar.value, type = childKey + getElementKey(nameSoFar, i++), invokeCallback += mapIntoArray(nameSoFar, array, escapedPrefix, type, callback);
283
- else if (type === "object") {
284
- if (typeof children.then === "function")
285
- return mapIntoArray(resolveThenable(children), array, escapedPrefix, nameSoFar, callback);
286
- array = String(children);
287
- throw Error("Objects are not valid as a React child (found: " + (array === "[object Object]" ? "object with keys {" + Object.keys(children).join(", ") + "}" : array) + "). If you meant to render a collection of children, use an array instead.");
288
- }
289
- return invokeCallback;
290
- }
291
- function mapChildren(children, func, context) {
292
- if (children == null)
293
- return children;
294
- var result = [], count = 0;
295
- mapIntoArray(children, result, "", "", function(child) {
296
- return func.call(context, child, count++);
297
- });
298
- return result;
299
- }
300
- function lazyInitializer(payload) {
301
- if (payload._status === -1) {
302
- var ioInfo = payload._ioInfo;
303
- ioInfo != null && (ioInfo.start = ioInfo.end = performance.now());
304
- ioInfo = payload._result;
305
- var thenable = ioInfo();
306
- thenable.then(function(moduleObject) {
307
- if (payload._status === 0 || payload._status === -1) {
308
- payload._status = 1;
309
- payload._result = moduleObject;
310
- var _ioInfo = payload._ioInfo;
311
- _ioInfo != null && (_ioInfo.end = performance.now());
312
- thenable.status === undefined && (thenable.status = "fulfilled", thenable.value = moduleObject);
313
- }
314
- }, function(error) {
315
- if (payload._status === 0 || payload._status === -1) {
316
- payload._status = 2;
317
- payload._result = error;
318
- var _ioInfo2 = payload._ioInfo;
319
- _ioInfo2 != null && (_ioInfo2.end = performance.now());
320
- thenable.status === undefined && (thenable.status = "rejected", thenable.reason = error);
321
- }
322
- });
323
- ioInfo = payload._ioInfo;
324
- if (ioInfo != null) {
325
- ioInfo.value = thenable;
326
- var displayName = thenable.displayName;
327
- typeof displayName === "string" && (ioInfo.name = displayName);
328
- }
329
- payload._status === -1 && (payload._status = 0, payload._result = thenable);
330
- }
331
- if (payload._status === 1)
332
- return ioInfo = payload._result, ioInfo === undefined && console.error(`lazy: Expected the result of a dynamic import() call. Instead received: %s
333
-
334
- Your code should look like:
335
- const MyComponent = lazy(() => import('./MyComponent'))
336
-
337
- Did you accidentally put curly braces around the import?`, ioInfo), "default" in ioInfo || console.error(`lazy: Expected the result of a dynamic import() call. Instead received: %s
338
-
339
- Your code should look like:
340
- const MyComponent = lazy(() => import('./MyComponent'))`, ioInfo), ioInfo.default;
341
- throw payload._result;
342
- }
343
- function resolveDispatcher() {
344
- var dispatcher = ReactSharedInternals.H;
345
- dispatcher === null && console.error(`Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
346
- 1. You might have mismatching versions of React and the renderer (such as React DOM)
347
- 2. You might be breaking the Rules of Hooks
348
- 3. You might have more than one copy of React in the same app
349
- See https://react.dev/link/invalid-hook-call for tips about how to debug and fix this problem.`);
350
- return dispatcher;
351
- }
352
- function releaseAsyncTransition() {
353
- ReactSharedInternals.asyncTransitions--;
354
- }
355
- function enqueueTask(task) {
356
- if (enqueueTaskImpl === null)
357
- try {
358
- var requireString = ("require" + Math.random()).slice(0, 7);
359
- enqueueTaskImpl = (module && module[requireString]).call(module, "timers").setImmediate;
360
- } catch (_err) {
361
- enqueueTaskImpl = function(callback) {
362
- didWarnAboutMessageChannel === false && (didWarnAboutMessageChannel = true, typeof MessageChannel === "undefined" && console.error("This browser does not have a MessageChannel implementation, so enqueuing tasks via await act(async () => ...) will fail. Please file an issue at https://github.com/facebook/react/issues if you encounter this warning."));
363
- var channel = new MessageChannel;
364
- channel.port1.onmessage = callback;
365
- channel.port2.postMessage(undefined);
366
- };
367
- }
368
- return enqueueTaskImpl(task);
369
- }
370
- function aggregateErrors(errors) {
371
- return 1 < errors.length && typeof AggregateError === "function" ? new AggregateError(errors) : errors[0];
372
- }
373
- function popActScope(prevActQueue, prevActScopeDepth) {
374
- prevActScopeDepth !== actScopeDepth - 1 && console.error("You seem to have overlapping act() calls, this is not supported. Be sure to await previous act() calls before making a new one. ");
375
- actScopeDepth = prevActScopeDepth;
376
- }
377
- function recursivelyFlushAsyncActWork(returnValue, resolve, reject) {
378
- var queue = ReactSharedInternals.actQueue;
379
- if (queue !== null)
380
- if (queue.length !== 0)
381
- try {
382
- flushActQueue(queue);
383
- enqueueTask(function() {
384
- return recursivelyFlushAsyncActWork(returnValue, resolve, reject);
385
- });
386
- return;
387
- } catch (error) {
388
- ReactSharedInternals.thrownErrors.push(error);
389
- }
390
- else
391
- ReactSharedInternals.actQueue = null;
392
- 0 < ReactSharedInternals.thrownErrors.length ? (queue = aggregateErrors(ReactSharedInternals.thrownErrors), ReactSharedInternals.thrownErrors.length = 0, reject(queue)) : resolve(returnValue);
393
- }
394
- function flushActQueue(queue) {
395
- if (!isFlushing) {
396
- isFlushing = true;
397
- var i = 0;
398
- try {
399
- for (;i < queue.length; i++) {
400
- var callback = queue[i];
401
- do {
402
- ReactSharedInternals.didUsePromise = false;
403
- var continuation = callback(false);
404
- if (continuation !== null) {
405
- if (ReactSharedInternals.didUsePromise) {
406
- queue[i] = callback;
407
- queue.splice(0, i);
408
- return;
409
- }
410
- callback = continuation;
411
- } else
412
- break;
413
- } while (1);
414
- }
415
- queue.length = 0;
416
- } catch (error) {
417
- queue.splice(0, i + 1), ReactSharedInternals.thrownErrors.push(error);
418
- } finally {
419
- isFlushing = false;
420
- }
421
- }
422
- }
423
- typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== "undefined" && typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart === "function" && __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(Error());
424
- var REACT_ELEMENT_TYPE = Symbol.for("react.transitional.element"), REACT_PORTAL_TYPE = Symbol.for("react.portal"), REACT_FRAGMENT_TYPE = Symbol.for("react.fragment"), REACT_STRICT_MODE_TYPE = Symbol.for("react.strict_mode"), REACT_PROFILER_TYPE = Symbol.for("react.profiler"), REACT_CONSUMER_TYPE = Symbol.for("react.consumer"), REACT_CONTEXT_TYPE = Symbol.for("react.context"), REACT_FORWARD_REF_TYPE = Symbol.for("react.forward_ref"), REACT_SUSPENSE_TYPE = Symbol.for("react.suspense"), REACT_SUSPENSE_LIST_TYPE = Symbol.for("react.suspense_list"), REACT_MEMO_TYPE = Symbol.for("react.memo"), REACT_LAZY_TYPE = Symbol.for("react.lazy"), REACT_ACTIVITY_TYPE = Symbol.for("react.activity"), MAYBE_ITERATOR_SYMBOL = Symbol.iterator, didWarnStateUpdateForUnmountedComponent = {}, ReactNoopUpdateQueue = {
425
- isMounted: function() {
426
- return false;
427
- },
428
- enqueueForceUpdate: function(publicInstance) {
429
- warnNoop(publicInstance, "forceUpdate");
430
- },
431
- enqueueReplaceState: function(publicInstance) {
432
- warnNoop(publicInstance, "replaceState");
433
- },
434
- enqueueSetState: function(publicInstance) {
435
- warnNoop(publicInstance, "setState");
436
- }
437
- }, assign = Object.assign, emptyObject = {};
438
- Object.freeze(emptyObject);
439
- Component.prototype.isReactComponent = {};
440
- Component.prototype.setState = function(partialState, callback) {
441
- if (typeof partialState !== "object" && typeof partialState !== "function" && partialState != null)
442
- throw Error("takes an object of state variables to update or a function which returns an object of state variables.");
443
- this.updater.enqueueSetState(this, partialState, callback, "setState");
444
- };
445
- Component.prototype.forceUpdate = function(callback) {
446
- this.updater.enqueueForceUpdate(this, callback, "forceUpdate");
447
- };
448
- var deprecatedAPIs = {
449
- isMounted: [
450
- "isMounted",
451
- "Instead, make sure to clean up subscriptions and pending requests in componentWillUnmount to prevent memory leaks."
452
- ],
453
- replaceState: [
454
- "replaceState",
455
- "Refactor your code to use setState instead (see https://github.com/facebook/react/issues/3236)."
456
- ]
457
- };
458
- for (fnName in deprecatedAPIs)
459
- deprecatedAPIs.hasOwnProperty(fnName) && defineDeprecationWarning(fnName, deprecatedAPIs[fnName]);
460
- ComponentDummy.prototype = Component.prototype;
461
- deprecatedAPIs = PureComponent.prototype = new ComponentDummy;
462
- deprecatedAPIs.constructor = PureComponent;
463
- assign(deprecatedAPIs, Component.prototype);
464
- deprecatedAPIs.isPureReactComponent = true;
465
- var isArrayImpl = Array.isArray, REACT_CLIENT_REFERENCE = Symbol.for("react.client.reference"), ReactSharedInternals = {
466
- H: null,
467
- A: null,
468
- T: null,
469
- S: null,
470
- actQueue: null,
471
- asyncTransitions: 0,
472
- isBatchingLegacy: false,
473
- didScheduleLegacyUpdate: false,
474
- didUsePromise: false,
475
- thrownErrors: [],
476
- getCurrentStack: null,
477
- recentlyCreatedOwnerStacks: 0
478
- }, hasOwnProperty = Object.prototype.hasOwnProperty, createTask = console.createTask ? console.createTask : function() {
479
- return null;
480
- };
481
- deprecatedAPIs = {
482
- react_stack_bottom_frame: function(callStackForError) {
483
- return callStackForError();
484
- }
485
- };
486
- var specialPropKeyWarningShown, didWarnAboutOldJSXRuntime;
487
- var didWarnAboutElementRef = {};
488
- var unknownOwnerDebugStack = deprecatedAPIs.react_stack_bottom_frame.bind(deprecatedAPIs, UnknownOwner)();
489
- var unknownOwnerDebugTask = createTask(getTaskName(UnknownOwner));
490
- var didWarnAboutMaps = false, userProvidedKeyEscapeRegex = /\/+/g, reportGlobalError = typeof reportError === "function" ? reportError : function(error) {
491
- if (typeof window === "object" && typeof window.ErrorEvent === "function") {
492
- var event = new window.ErrorEvent("error", {
493
- bubbles: true,
494
- cancelable: true,
495
- message: typeof error === "object" && error !== null && typeof error.message === "string" ? String(error.message) : String(error),
496
- error
497
- });
498
- if (!window.dispatchEvent(event))
499
- return;
500
- } else if (typeof process === "object" && typeof process.emit === "function") {
501
- process.emit("uncaughtException", error);
502
- return;
503
- }
504
- console.error(error);
505
- }, didWarnAboutMessageChannel = false, enqueueTaskImpl = null, actScopeDepth = 0, didWarnNoAwaitAct = false, isFlushing = false, queueSeveralMicrotasks = typeof queueMicrotask === "function" ? function(callback) {
506
- queueMicrotask(function() {
507
- return queueMicrotask(callback);
508
- });
509
- } : enqueueTask;
510
- deprecatedAPIs = Object.freeze({
511
- __proto__: null,
512
- c: function(size) {
513
- return resolveDispatcher().useMemoCache(size);
514
- }
515
- });
516
- var fnName = {
517
- map: mapChildren,
518
- forEach: function(children, forEachFunc, forEachContext) {
519
- mapChildren(children, function() {
520
- forEachFunc.apply(this, arguments);
521
- }, forEachContext);
522
- },
523
- count: function(children) {
524
- var n = 0;
525
- mapChildren(children, function() {
526
- n++;
527
- });
528
- return n;
529
- },
530
- toArray: function(children) {
531
- return mapChildren(children, function(child) {
532
- return child;
533
- }) || [];
534
- },
535
- only: function(children) {
536
- if (!isValidElement(children))
537
- throw Error("React.Children.only expected to receive a single React element child.");
538
- return children;
539
- }
540
- };
541
- exports.Activity = REACT_ACTIVITY_TYPE;
542
- exports.Children = fnName;
543
- exports.Component = Component;
544
- exports.Fragment = REACT_FRAGMENT_TYPE;
545
- exports.Profiler = REACT_PROFILER_TYPE;
546
- exports.PureComponent = PureComponent;
547
- exports.StrictMode = REACT_STRICT_MODE_TYPE;
548
- exports.Suspense = REACT_SUSPENSE_TYPE;
549
- exports.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE = ReactSharedInternals;
550
- exports.__COMPILER_RUNTIME = deprecatedAPIs;
551
- exports.act = function(callback) {
552
- var prevActQueue = ReactSharedInternals.actQueue, prevActScopeDepth = actScopeDepth;
553
- actScopeDepth++;
554
- var queue = ReactSharedInternals.actQueue = prevActQueue !== null ? prevActQueue : [], didAwaitActCall = false;
555
- try {
556
- var result = callback();
557
- } catch (error) {
558
- ReactSharedInternals.thrownErrors.push(error);
559
- }
560
- if (0 < ReactSharedInternals.thrownErrors.length)
561
- throw popActScope(prevActQueue, prevActScopeDepth), callback = aggregateErrors(ReactSharedInternals.thrownErrors), ReactSharedInternals.thrownErrors.length = 0, callback;
562
- if (result !== null && typeof result === "object" && typeof result.then === "function") {
563
- var thenable = result;
564
- queueSeveralMicrotasks(function() {
565
- didAwaitActCall || didWarnNoAwaitAct || (didWarnNoAwaitAct = true, console.error("You called act(async () => ...) without await. This could lead to unexpected testing behaviour, interleaving multiple act calls and mixing their scopes. You should - await act(async () => ...);"));
566
- });
567
- return {
568
- then: function(resolve, reject) {
569
- didAwaitActCall = true;
570
- thenable.then(function(returnValue) {
571
- popActScope(prevActQueue, prevActScopeDepth);
572
- if (prevActScopeDepth === 0) {
573
- try {
574
- flushActQueue(queue), enqueueTask(function() {
575
- return recursivelyFlushAsyncActWork(returnValue, resolve, reject);
576
- });
577
- } catch (error$0) {
578
- ReactSharedInternals.thrownErrors.push(error$0);
579
- }
580
- if (0 < ReactSharedInternals.thrownErrors.length) {
581
- var _thrownError = aggregateErrors(ReactSharedInternals.thrownErrors);
582
- ReactSharedInternals.thrownErrors.length = 0;
583
- reject(_thrownError);
584
- }
585
- } else
586
- resolve(returnValue);
587
- }, function(error) {
588
- popActScope(prevActQueue, prevActScopeDepth);
589
- 0 < ReactSharedInternals.thrownErrors.length ? (error = aggregateErrors(ReactSharedInternals.thrownErrors), ReactSharedInternals.thrownErrors.length = 0, reject(error)) : reject(error);
590
- });
591
- }
592
- };
593
- }
594
- var returnValue$jscomp$0 = result;
595
- popActScope(prevActQueue, prevActScopeDepth);
596
- prevActScopeDepth === 0 && (flushActQueue(queue), queue.length !== 0 && queueSeveralMicrotasks(function() {
597
- didAwaitActCall || didWarnNoAwaitAct || (didWarnNoAwaitAct = true, console.error("A component suspended inside an `act` scope, but the `act` call was not awaited. When testing React components that depend on asynchronous data, you must await the result:\n\nawait act(() => ...)"));
598
- }), ReactSharedInternals.actQueue = null);
599
- if (0 < ReactSharedInternals.thrownErrors.length)
600
- throw callback = aggregateErrors(ReactSharedInternals.thrownErrors), ReactSharedInternals.thrownErrors.length = 0, callback;
601
- return {
602
- then: function(resolve, reject) {
603
- didAwaitActCall = true;
604
- prevActScopeDepth === 0 ? (ReactSharedInternals.actQueue = queue, enqueueTask(function() {
605
- return recursivelyFlushAsyncActWork(returnValue$jscomp$0, resolve, reject);
606
- })) : resolve(returnValue$jscomp$0);
607
- }
608
- };
609
- };
610
- exports.cache = function(fn) {
611
- return function() {
612
- return fn.apply(null, arguments);
613
- };
614
- };
615
- exports.cacheSignal = function() {
616
- return null;
617
- };
618
- exports.captureOwnerStack = function() {
619
- var getCurrentStack = ReactSharedInternals.getCurrentStack;
620
- return getCurrentStack === null ? null : getCurrentStack();
621
- };
622
- exports.cloneElement = function(element, config, children) {
623
- if (element === null || element === undefined)
624
- throw Error("The argument must be a React element, but you passed " + element + ".");
625
- var props = assign({}, element.props), key = element.key, owner = element._owner;
626
- if (config != null) {
627
- var JSCompiler_inline_result;
628
- a: {
629
- if (hasOwnProperty.call(config, "ref") && (JSCompiler_inline_result = Object.getOwnPropertyDescriptor(config, "ref").get) && JSCompiler_inline_result.isReactWarning) {
630
- JSCompiler_inline_result = false;
631
- break a;
632
- }
633
- JSCompiler_inline_result = config.ref !== undefined;
634
- }
635
- JSCompiler_inline_result && (owner = getOwner());
636
- hasValidKey(config) && (checkKeyStringCoercion(config.key), key = "" + config.key);
637
- for (propName in config)
638
- !hasOwnProperty.call(config, propName) || propName === "key" || propName === "__self" || propName === "__source" || propName === "ref" && config.ref === undefined || (props[propName] = config[propName]);
639
- }
640
- var propName = arguments.length - 2;
641
- if (propName === 1)
642
- props.children = children;
643
- else if (1 < propName) {
644
- JSCompiler_inline_result = Array(propName);
645
- for (var i = 0;i < propName; i++)
646
- JSCompiler_inline_result[i] = arguments[i + 2];
647
- props.children = JSCompiler_inline_result;
648
- }
649
- props = ReactElement(element.type, key, props, owner, element._debugStack, element._debugTask);
650
- for (key = 2;key < arguments.length; key++)
651
- validateChildKeys(arguments[key]);
652
- return props;
653
- };
654
- exports.createContext = function(defaultValue) {
655
- defaultValue = {
656
- $$typeof: REACT_CONTEXT_TYPE,
657
- _currentValue: defaultValue,
658
- _currentValue2: defaultValue,
659
- _threadCount: 0,
660
- Provider: null,
661
- Consumer: null
662
- };
663
- defaultValue.Provider = defaultValue;
664
- defaultValue.Consumer = {
665
- $$typeof: REACT_CONSUMER_TYPE,
666
- _context: defaultValue
667
- };
668
- defaultValue._currentRenderer = null;
669
- defaultValue._currentRenderer2 = null;
670
- return defaultValue;
671
- };
672
- exports.createElement = function(type, config, children) {
673
- for (var i = 2;i < arguments.length; i++)
674
- validateChildKeys(arguments[i]);
675
- i = {};
676
- var key = null;
677
- if (config != null)
678
- for (propName in didWarnAboutOldJSXRuntime || !("__self" in config) || "key" in config || (didWarnAboutOldJSXRuntime = true, console.warn("Your app (or one of its dependencies) is using an outdated JSX transform. Update to the modern JSX transform for faster performance: https://react.dev/link/new-jsx-transform")), hasValidKey(config) && (checkKeyStringCoercion(config.key), key = "" + config.key), config)
679
- hasOwnProperty.call(config, propName) && propName !== "key" && propName !== "__self" && propName !== "__source" && (i[propName] = config[propName]);
680
- var childrenLength = arguments.length - 2;
681
- if (childrenLength === 1)
682
- i.children = children;
683
- else if (1 < childrenLength) {
684
- for (var childArray = Array(childrenLength), _i = 0;_i < childrenLength; _i++)
685
- childArray[_i] = arguments[_i + 2];
686
- Object.freeze && Object.freeze(childArray);
687
- i.children = childArray;
688
- }
689
- if (type && type.defaultProps)
690
- for (propName in childrenLength = type.defaultProps, childrenLength)
691
- i[propName] === undefined && (i[propName] = childrenLength[propName]);
692
- key && defineKeyPropWarningGetter(i, typeof type === "function" ? type.displayName || type.name || "Unknown" : type);
693
- var propName = 1e4 > ReactSharedInternals.recentlyCreatedOwnerStacks++;
694
- return ReactElement(type, key, i, getOwner(), propName ? Error("react-stack-top-frame") : unknownOwnerDebugStack, propName ? createTask(getTaskName(type)) : unknownOwnerDebugTask);
695
- };
696
- exports.createRef = function() {
697
- var refObject = { current: null };
698
- Object.seal(refObject);
699
- return refObject;
700
- };
701
- exports.forwardRef = function(render) {
702
- render != null && render.$$typeof === REACT_MEMO_TYPE ? console.error("forwardRef requires a render function but received a `memo` component. Instead of forwardRef(memo(...)), use memo(forwardRef(...)).") : typeof render !== "function" ? console.error("forwardRef requires a render function but was given %s.", render === null ? "null" : typeof render) : render.length !== 0 && render.length !== 2 && console.error("forwardRef render functions accept exactly two parameters: props and ref. %s", render.length === 1 ? "Did you forget to use the ref parameter?" : "Any additional parameter will be undefined.");
703
- render != null && render.defaultProps != null && console.error("forwardRef render functions do not support defaultProps. Did you accidentally pass a React component?");
704
- var elementType = { $$typeof: REACT_FORWARD_REF_TYPE, render }, ownName;
705
- Object.defineProperty(elementType, "displayName", {
706
- enumerable: false,
707
- configurable: true,
708
- get: function() {
709
- return ownName;
710
- },
711
- set: function(name) {
712
- ownName = name;
713
- render.name || render.displayName || (Object.defineProperty(render, "name", { value: name }), render.displayName = name);
714
- }
715
- });
716
- return elementType;
717
- };
718
- exports.isValidElement = isValidElement;
719
- exports.lazy = function(ctor) {
720
- ctor = { _status: -1, _result: ctor };
721
- var lazyType = {
722
- $$typeof: REACT_LAZY_TYPE,
723
- _payload: ctor,
724
- _init: lazyInitializer
725
- }, ioInfo = {
726
- name: "lazy",
727
- start: -1,
728
- end: -1,
729
- value: null,
730
- owner: null,
731
- debugStack: Error("react-stack-top-frame"),
732
- debugTask: console.createTask ? console.createTask("lazy()") : null
733
- };
734
- ctor._ioInfo = ioInfo;
735
- lazyType._debugInfo = [{ awaited: ioInfo }];
736
- return lazyType;
737
- };
738
- exports.memo = function(type, compare) {
739
- type == null && console.error("memo: The first argument must be a component. Instead received: %s", type === null ? "null" : typeof type);
740
- compare = {
741
- $$typeof: REACT_MEMO_TYPE,
742
- type,
743
- compare: compare === undefined ? null : compare
744
- };
745
- var ownName;
746
- Object.defineProperty(compare, "displayName", {
747
- enumerable: false,
748
- configurable: true,
749
- get: function() {
750
- return ownName;
751
- },
752
- set: function(name) {
753
- ownName = name;
754
- type.name || type.displayName || (Object.defineProperty(type, "name", { value: name }), type.displayName = name);
755
- }
756
- });
757
- return compare;
758
- };
759
- exports.startTransition = function(scope) {
760
- var prevTransition = ReactSharedInternals.T, currentTransition = {};
761
- currentTransition._updatedFibers = new Set;
762
- ReactSharedInternals.T = currentTransition;
763
- try {
764
- var returnValue = scope(), onStartTransitionFinish = ReactSharedInternals.S;
765
- onStartTransitionFinish !== null && onStartTransitionFinish(currentTransition, returnValue);
766
- typeof returnValue === "object" && returnValue !== null && typeof returnValue.then === "function" && (ReactSharedInternals.asyncTransitions++, returnValue.then(releaseAsyncTransition, releaseAsyncTransition), returnValue.then(noop, reportGlobalError));
767
- } catch (error) {
768
- reportGlobalError(error);
769
- } finally {
770
- prevTransition === null && currentTransition._updatedFibers && (scope = currentTransition._updatedFibers.size, currentTransition._updatedFibers.clear(), 10 < scope && console.warn("Detected a large number of updates inside startTransition. If this is due to a subscription please re-write it to use React provided hooks. Otherwise concurrent mode guarantees are off the table.")), prevTransition !== null && currentTransition.types !== null && (prevTransition.types !== null && prevTransition.types !== currentTransition.types && console.error("We expected inner Transitions to have transferred the outer types set and that you cannot add to the outer Transition while inside the inner.This is a bug in React."), prevTransition.types = currentTransition.types), ReactSharedInternals.T = prevTransition;
771
- }
772
- };
773
- exports.unstable_useCacheRefresh = function() {
774
- return resolveDispatcher().useCacheRefresh();
775
- };
776
- exports.use = function(usable) {
777
- return resolveDispatcher().use(usable);
778
- };
779
- exports.useActionState = function(action, initialState, permalink) {
780
- return resolveDispatcher().useActionState(action, initialState, permalink);
781
- };
782
- exports.useCallback = function(callback, deps) {
783
- return resolveDispatcher().useCallback(callback, deps);
784
- };
785
- exports.useContext = function(Context) {
786
- var dispatcher = resolveDispatcher();
787
- Context.$$typeof === REACT_CONSUMER_TYPE && console.error("Calling useContext(Context.Consumer) is not supported and will cause bugs. Did you mean to call useContext(Context) instead?");
788
- return dispatcher.useContext(Context);
789
- };
790
- exports.useDebugValue = function(value, formatterFn) {
791
- return resolveDispatcher().useDebugValue(value, formatterFn);
792
- };
793
- exports.useDeferredValue = function(value, initialValue) {
794
- return resolveDispatcher().useDeferredValue(value, initialValue);
795
- };
796
- exports.useEffect = function(create, deps) {
797
- create == null && console.warn("React Hook useEffect requires an effect callback. Did you forget to pass a callback to the hook?");
798
- return resolveDispatcher().useEffect(create, deps);
799
- };
800
- exports.useEffectEvent = function(callback) {
801
- return resolveDispatcher().useEffectEvent(callback);
802
- };
803
- exports.useId = function() {
804
- return resolveDispatcher().useId();
805
- };
806
- exports.useImperativeHandle = function(ref, create, deps) {
807
- return resolveDispatcher().useImperativeHandle(ref, create, deps);
808
- };
809
- exports.useInsertionEffect = function(create, deps) {
810
- create == null && console.warn("React Hook useInsertionEffect requires an effect callback. Did you forget to pass a callback to the hook?");
811
- return resolveDispatcher().useInsertionEffect(create, deps);
812
- };
813
- exports.useLayoutEffect = function(create, deps) {
814
- create == null && console.warn("React Hook useLayoutEffect requires an effect callback. Did you forget to pass a callback to the hook?");
815
- return resolveDispatcher().useLayoutEffect(create, deps);
816
- };
817
- exports.useMemo = function(create, deps) {
818
- return resolveDispatcher().useMemo(create, deps);
819
- };
820
- exports.useOptimistic = function(passthrough, reducer) {
821
- return resolveDispatcher().useOptimistic(passthrough, reducer);
822
- };
823
- exports.useReducer = function(reducer, initialArg, init) {
824
- return resolveDispatcher().useReducer(reducer, initialArg, init);
825
- };
826
- exports.useRef = function(initialValue) {
827
- return resolveDispatcher().useRef(initialValue);
828
- };
829
- exports.useState = function(initialState) {
830
- return resolveDispatcher().useState(initialState);
831
- };
832
- exports.useSyncExternalStore = function(subscribe, getSnapshot, getServerSnapshot) {
833
- return resolveDispatcher().useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);
834
- };
835
- exports.useTransition = function() {
836
- return resolveDispatcher().useTransition();
837
- };
838
- exports.version = "19.2.4";
839
- typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== "undefined" && typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop === "function" && __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(Error());
840
- })();
841
- });
842
-
843
- // ../../node_modules/.bun/react@19.2.4/node_modules/react/index.js
844
- var require_react = __commonJS((exports, module) => {
845
- var react_development = __toESM(require_react_development());
846
- if (false) {} else {
847
- module.exports = react_development;
848
- }
849
- });
850
-
851
- // ../../node_modules/.bun/use-sync-external-store@1.6.0+b1ab299f0a400331/node_modules/use-sync-external-store/cjs/use-sync-external-store-shim.development.js
852
- var require_use_sync_external_store_shim_development = __commonJS((exports) => {
853
- var React6 = __toESM(require_react());
854
- (function() {
855
- function is(x, y) {
856
- return x === y && (x !== 0 || 1 / x === 1 / y) || x !== x && y !== y;
857
- }
858
- function useSyncExternalStore$2(subscribe, getSnapshot) {
859
- didWarnOld18Alpha || React6.startTransition === undefined || (didWarnOld18Alpha = true, console.error("You are using an outdated, pre-release alpha of React 18 that does not support useSyncExternalStore. The use-sync-external-store shim will not work correctly. Upgrade to a newer pre-release."));
860
- var value = getSnapshot();
861
- if (!didWarnUncachedGetSnapshot) {
862
- var cachedValue = getSnapshot();
863
- objectIs(value, cachedValue) || (console.error("The result of getSnapshot should be cached to avoid an infinite loop"), didWarnUncachedGetSnapshot = true);
864
- }
865
- cachedValue = useState5({
866
- inst: { value, getSnapshot }
867
- });
868
- var inst = cachedValue[0].inst, forceUpdate = cachedValue[1];
869
- useLayoutEffect2(function() {
870
- inst.value = value;
871
- inst.getSnapshot = getSnapshot;
872
- checkIfSnapshotChanged(inst) && forceUpdate({ inst });
873
- }, [subscribe, value, getSnapshot]);
874
- useEffect3(function() {
875
- checkIfSnapshotChanged(inst) && forceUpdate({ inst });
876
- return subscribe(function() {
877
- checkIfSnapshotChanged(inst) && forceUpdate({ inst });
878
- });
879
- }, [subscribe]);
880
- useDebugValue2(value);
881
- return value;
882
- }
883
- function checkIfSnapshotChanged(inst) {
884
- var latestGetSnapshot = inst.getSnapshot;
885
- inst = inst.value;
886
- try {
887
- var nextValue = latestGetSnapshot();
888
- return !objectIs(inst, nextValue);
889
- } catch (error) {
890
- return true;
891
- }
892
- }
893
- function useSyncExternalStore$1(subscribe, getSnapshot) {
894
- return getSnapshot();
895
- }
896
- typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== "undefined" && typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart === "function" && __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(Error());
897
- var objectIs = typeof Object.is === "function" ? Object.is : is, useState5 = React6.useState, useEffect3 = React6.useEffect, useLayoutEffect2 = React6.useLayoutEffect, useDebugValue2 = React6.useDebugValue, didWarnOld18Alpha = false, didWarnUncachedGetSnapshot = false, shim = typeof window === "undefined" || typeof window.document === "undefined" || typeof window.document.createElement === "undefined" ? useSyncExternalStore$1 : useSyncExternalStore$2;
898
- exports.useSyncExternalStore = React6.useSyncExternalStore !== undefined ? React6.useSyncExternalStore : shim;
899
- typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== "undefined" && typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop === "function" && __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(Error());
900
- })();
901
- });
902
-
903
- // ../../node_modules/.bun/use-sync-external-store@1.6.0+b1ab299f0a400331/node_modules/use-sync-external-store/shim/index.js
904
- var require_shim = __commonJS((exports, module) => {
905
- if (false) {} else {
906
- module.exports = require_use_sync_external_store_shim_development();
907
- }
908
- });
909
-
910
2
  // src/bot.ts
911
- var import_react3 = __toESM(require_react(), 1);
3
+ import React3, { Suspense } from "react";
912
4
  import { createRoot } from "@teactjs/renderer";
913
5
  import { serializeOutput } from "@teactjs/telegram";
914
6
  import { CallbackRegistryCtx, ErrorBoundary, SuspenseFallback } from "@teactjs/react";
915
7
 
916
8
  // src/context.ts
917
- var import_react = __toESM(require_react(), 1);
918
- var RuntimeContext = import_react.default.createContext(null);
9
+ import React, { useContext } from "react";
10
+ var RuntimeContext = React.createContext(null);
919
11
  function useRuntime() {
920
- const ctx = import_react.useContext(RuntimeContext);
12
+ const ctx = useContext(RuntimeContext);
921
13
  if (!ctx)
922
14
  throw new Error("Teact hooks must be used inside a bot component");
923
15
  return ctx;
@@ -1021,18 +113,18 @@ function commandMiddleware(commands) {
1021
113
  }
1022
114
 
1023
115
  // src/router.ts
1024
- var import_react2 = __toESM(require_react(), 1);
116
+ import React2, { useState, useContext as useContext2, useCallback, createContext } from "react";
1025
117
  var GUARD_REPLY_SYMBOL = Symbol.for("teact.guardReply");
1026
118
  function createGuardReply(text, options) {
1027
119
  return { __type: GUARD_REPLY_SYMBOL, text, buttons: options?.buttons };
1028
120
  }
1029
- var RouterCtx = import_react2.createContext(null);
1030
- var CommitModeCtx = import_react2.createContext({ current: "replace" });
121
+ var RouterCtx = createContext(null);
122
+ var CommitModeCtx = createContext({ current: "replace" });
1031
123
  function redirect(path) {
1032
124
  return path;
1033
125
  }
1034
126
  function DefaultNotFound() {
1035
- return import_react2.default.createElement("tg-message", { text: `\uD83D\uDD0D Page not found
127
+ return React2.createElement("tg-message", { text: `\uD83D\uDD0D Page not found
1036
128
 
1037
129
  The page you're looking for doesn't exist.
1038
130
  Use /start to go back to the menu.` });
@@ -1128,55 +220,55 @@ function RouterProvider({
1128
220
  config,
1129
221
  initialPath
1130
222
  }) {
1131
- const commitMode = import_react2.useContext(CommitModeCtx);
1132
- const runtime = import_react2.useContext(RuntimeContext);
1133
- const [nav, setNav] = import_react2.useState({ path: initialPath, tick: 0 });
1134
- const navigate = import_react2.useCallback((path, opts) => {
223
+ const commitMode = useContext2(CommitModeCtx);
224
+ const runtime = useContext2(RuntimeContext);
225
+ const [nav, setNav] = useState({ path: initialPath, tick: 0 });
226
+ const navigate = useCallback((path, opts) => {
1135
227
  commitMode.current = opts?.mode ?? "replace";
1136
228
  setNav((prev) => ({ path, tick: prev.tick + 1 }));
1137
229
  }, [commitMode]);
1138
230
  const resolved = resolveRoute(config, nav.path, runtime?.session ?? {});
1139
231
  const providerValue = { path: nav.path, params: {}, navigate };
1140
232
  if (!resolved) {
1141
- return import_react2.default.createElement(RouterCtx.Provider, { value: providerValue }, import_react2.default.createElement(config.notFound));
233
+ return React2.createElement(RouterCtx.Provider, { value: providerValue }, React2.createElement(config.notFound));
1142
234
  }
1143
235
  if ("guardComponent" in resolved) {
1144
- return import_react2.default.createElement(RouterCtx.Provider, { value: providerValue }, import_react2.default.createElement(resolved.guardComponent));
236
+ return React2.createElement(RouterCtx.Provider, { value: providerValue }, React2.createElement(resolved.guardComponent));
1145
237
  }
1146
238
  if ("guardElement" in resolved) {
1147
- return import_react2.default.createElement(RouterCtx.Provider, { value: providerValue }, resolved.guardElement);
239
+ return React2.createElement(RouterCtx.Provider, { value: providerValue }, resolved.guardElement);
1148
240
  }
1149
241
  if ("guardReply" in resolved) {
1150
242
  const { text, buttons } = resolved.guardReply;
1151
243
  const children = [];
1152
244
  if (buttons?.length) {
1153
- const rows = buttons.map((row, ri) => import_react2.default.createElement("tg-button-row", { key: ri }, ...row.map((btn, bi) => import_react2.default.createElement("tg-button", {
245
+ const rows = buttons.map((row, ri) => React2.createElement("tg-button-row", { key: ri }, ...row.map((btn, bi) => React2.createElement("tg-button", {
1154
246
  key: bi,
1155
247
  text: btn.text,
1156
248
  url: btn.url,
1157
249
  callbackData: btn.route ? `__route:${btn.route}` : undefined
1158
250
  }))));
1159
- children.push(import_react2.default.createElement("tg-keyboard", { key: "kbd" }, ...rows));
251
+ children.push(React2.createElement("tg-keyboard", { key: "kbd" }, ...rows));
1160
252
  }
1161
- const msg = import_react2.default.createElement("tg-message", { text }, ...children);
1162
- return import_react2.default.createElement(RouterCtx.Provider, { value: providerValue }, msg);
253
+ const msg = React2.createElement("tg-message", { text }, ...children);
254
+ return React2.createElement(RouterCtx.Provider, { value: providerValue }, msg);
1163
255
  }
1164
- return import_react2.default.createElement(RouterCtx.Provider, { value: { path: resolved.path, params: resolved.params, navigate } }, import_react2.default.createElement(resolved.route.component));
256
+ return React2.createElement(RouterCtx.Provider, { value: { path: resolved.path, params: resolved.params, navigate } }, React2.createElement(resolved.route.component));
1165
257
  }
1166
258
  function useNavigate() {
1167
- const ctx = import_react2.useContext(RouterCtx);
259
+ const ctx = useContext2(RouterCtx);
1168
260
  if (!ctx)
1169
261
  throw new Error("useNavigate must be used inside a Router");
1170
262
  return ctx.navigate;
1171
263
  }
1172
264
  function useParams() {
1173
- const ctx = import_react2.useContext(RouterCtx);
265
+ const ctx = useContext2(RouterCtx);
1174
266
  if (!ctx)
1175
267
  throw new Error("useParams must be used inside a Router");
1176
268
  return ctx.params;
1177
269
  }
1178
270
  function useRoute() {
1179
- const ctx = import_react2.useContext(RouterCtx);
271
+ const ctx = useContext2(RouterCtx);
1180
272
  if (!ctx)
1181
273
  throw new Error("useRoute must be used inside a Router");
1182
274
  return { path: ctx.path, params: ctx.params };
@@ -1459,22 +551,22 @@ function createBot(options) {
1459
551
  let rootElement;
1460
552
  if (options.router) {
1461
553
  const initialPath = commandInfo?.initialRoute ?? options.router.defaultRoute;
1462
- rootElement = import_react3.default.createElement(RouterProvider, { config: options.router, initialPath });
554
+ rootElement = React3.createElement(RouterProvider, { config: options.router, initialPath });
1463
555
  } else {
1464
- rootElement = import_react3.default.createElement(options.component, {});
556
+ rootElement = React3.createElement(options.component, {});
1465
557
  }
1466
558
  for (const plugin of plugins) {
1467
559
  if (plugin.Provider) {
1468
- rootElement = import_react3.default.createElement(plugin.Provider, null, rootElement);
560
+ rootElement = React3.createElement(plugin.Provider, null, rootElement);
1469
561
  }
1470
562
  }
1471
563
  if (options.providers) {
1472
- rootElement = import_react3.default.createElement(options.providers, null, rootElement);
564
+ rootElement = React3.createElement(options.providers, null, rootElement);
1473
565
  }
1474
- const wrappedElement = import_react3.default.createElement(ErrorBoundary, {
566
+ const wrappedElement = React3.createElement(ErrorBoundary, {
1475
567
  onError: (err) => console.error(`[teact] Render error in chat ${chatState.chatId}:`, err)
1476
- }, import_react3.default.createElement(import_react3.Suspense, { fallback: import_react3.default.createElement(SuspenseFallback, null) }, rootElement));
1477
- const element = import_react3.default.createElement(CallbackRegistryCtx.Provider, { value: { handlers: chatState.handlers } }, import_react3.default.createElement(RuntimeContext.Provider, { value: runtimeValue }, import_react3.default.createElement(CommitModeCtx.Provider, { value: chatState.commitMode }, wrappedElement)));
568
+ }, React3.createElement(Suspense, { fallback: React3.createElement(SuspenseFallback, null) }, rootElement));
569
+ const element = React3.createElement(CallbackRegistryCtx.Provider, { value: { handlers: chatState.handlers } }, React3.createElement(RuntimeContext.Provider, { value: runtimeValue }, React3.createElement(CommitModeCtx.Provider, { value: chatState.commitMode }, wrappedElement)));
1478
570
  debugLog("rendering", { chatId: botCtx.chatId, hasRouter: !!options.router, plugins: plugins.length });
1479
571
  chatState.root.render(element);
1480
572
  }
@@ -1569,7 +661,7 @@ function createBot(options) {
1569
661
  return botInstance;
1570
662
  }
1571
663
  // src/conversation.ts
1572
- var import_react5 = __toESM(require_react(), 1);
664
+ import React4, { useState as useState2, useContext as useContext3, useId, useMemo, useCallback as useCallback2 } from "react";
1573
665
  import { CallbackRegistryCtx as CallbackRegistryCtx2 } from "@teactjs/react";
1574
666
  function runValidation(validator, value) {
1575
667
  if (typeof validator === "function")
@@ -1592,19 +684,19 @@ function useConversation(config) {
1592
684
  const stepsMode = config ? isStepsConfig(config) : false;
1593
685
  const steps = stepsMode ? config : undefined;
1594
686
  const opts = stepsMode ? undefined : config;
1595
- const [answers, setAnswers] = import_react5.useState({});
1596
- const [activeKey, setActiveKey] = import_react5.useState(null);
1597
- const [waitMode, setWaitMode] = import_react5.useState("text");
1598
- const [processedMsgId, setProcessedMsgId] = import_react5.useState("");
1599
- const [lastError, setLastError] = import_react5.useState(null);
687
+ const [answers, setAnswers] = useState2({});
688
+ const [activeKey, setActiveKey] = useState2(null);
689
+ const [waitMode, setWaitMode] = useState2("text");
690
+ const [processedMsgId, setProcessedMsgId] = useState2("");
691
+ const [lastError, setLastError] = useState2(null);
1600
692
  const bot = useBot();
1601
- const registry = import_react5.useContext(CallbackRegistryCtx2);
1602
- const hookId = import_react5.useId();
693
+ const registry = useContext3(CallbackRegistryCtx2);
694
+ const hookId = useId();
1603
695
  const text = bot.text;
1604
696
  const callbackData = bot.callbackData;
1605
697
  const msgId = bot.messageId ?? "";
1606
- const stepKeys = import_react5.useMemo(() => steps ? Object.keys(steps) : [], [steps]);
1607
- const validateFn = import_react5.useMemo(() => {
698
+ const stepKeys = useMemo(() => steps ? Object.keys(steps) : [], [steps]);
699
+ const validateFn = useMemo(() => {
1608
700
  if (steps) {
1609
701
  return (key, value) => {
1610
702
  const def = steps[key];
@@ -1633,7 +725,7 @@ function useConversation(config) {
1633
725
  setProcessedMsgId(msgId);
1634
726
  }
1635
727
  }
1636
- const setFn = import_react5.useCallback((key, value) => {
728
+ const setFn = useCallback2((key, value) => {
1637
729
  setAnswers((prev) => ({ ...prev, [key]: value }));
1638
730
  setActiveKey((prev) => prev === key ? null : prev);
1639
731
  setLastError(null);
@@ -1657,11 +749,11 @@ function useConversation(config) {
1657
749
  const optValue = typeof opt === "string" ? opt : opt.value;
1658
750
  const cbId = `__ask:${hookId}:${key}:${ri}:${ci}`;
1659
751
  registry?.handlers.set(cbId, () => setFn(key, optValue));
1660
- return import_react5.default.createElement("tg-button", { key: `${ri}:${ci}`, text: optText, callbackData: cbId });
752
+ return React4.createElement("tg-button", { key: `${ri}:${ci}`, text: optText, callbackData: cbId });
1661
753
  });
1662
- return import_react5.default.createElement("tg-button-row", { key: String(ri) }, ...buttons);
754
+ return React4.createElement("tg-button-row", { key: String(ri) }, ...buttons);
1663
755
  });
1664
- return import_react5.default.createElement("tg-message", { text: questionText }, import_react5.default.createElement("tg-keyboard", {}, ...rows));
756
+ return React4.createElement("tg-message", { text: questionText }, React4.createElement("tg-keyboard", {}, ...rows));
1665
757
  }
1666
758
  const currentKey = stepKeys.find((k) => !(k in answers)) ?? null;
1667
759
  function renderStep() {
@@ -1673,7 +765,7 @@ function useConversation(config) {
1673
765
 
1674
766
  ${def.prompt}` : def.prompt;
1675
767
  activateText(currentKey);
1676
- return import_react5.default.createElement("tg-message", { text: promptText });
768
+ return React4.createElement("tg-message", { text: promptText });
1677
769
  }
1678
770
  if ("ask" in def) {
1679
771
  const askText = lastError ? `\u26A0\uFE0F ${lastError}
@@ -1728,7 +820,7 @@ ${def.ask}` : def.ask;
1728
820
  clear: clearStep,
1729
821
  prompt(key, questionText) {
1730
822
  activateText(key);
1731
- return import_react5.default.createElement("tg-message", { text: questionText });
823
+ return React4.createElement("tg-message", { text: questionText });
1732
824
  },
1733
825
  ask: buildAsk,
1734
826
  waitFor(key) {
@@ -1761,9 +853,9 @@ function useForm(schema) {
1761
853
  return runValidation(field.validate, value);
1762
854
  }
1763
855
  });
1764
- const registry = import_react5.useContext(CallbackRegistryCtx2);
1765
- const formId = import_react5.useId();
1766
- const keys = import_react5.useMemo(() => Object.keys(schema), []);
856
+ const registry = useContext3(CallbackRegistryCtx2);
857
+ const formId = useId();
858
+ const keys = useMemo(() => Object.keys(schema), []);
1767
859
  const currentKey = keys.find((k) => !conv.has(k));
1768
860
  const complete = !currentKey;
1769
861
  function renderStep() {
@@ -1779,11 +871,11 @@ ${basePrompt}` : basePrompt;
1779
871
  const buttons = row.map((opt, ci) => {
1780
872
  const cbId = `__form:${formId}:${ri}:${ci}`;
1781
873
  registry?.handlers.set(cbId, () => conv.set(currentKey, opt));
1782
- return import_react5.default.createElement("tg-button", { key: `${ri}:${ci}`, text: opt, callbackData: cbId });
874
+ return React4.createElement("tg-button", { key: `${ri}:${ci}`, text: opt, callbackData: cbId });
1783
875
  });
1784
- return import_react5.default.createElement("tg-button-row", { key: String(ri) }, ...buttons);
876
+ return React4.createElement("tg-button-row", { key: String(ri) }, ...buttons);
1785
877
  });
1786
- return import_react5.default.createElement("tg-message", { text: promptText }, import_react5.default.createElement("tg-keyboard", {}, ...rows));
878
+ return React4.createElement("tg-message", { text: promptText }, React4.createElement("tg-keyboard", {}, ...rows));
1787
879
  }
1788
880
  return conv.prompt(currentKey, promptText);
1789
881
  }
@@ -1823,16 +915,16 @@ ${basePrompt}` : basePrompt;
1823
915
  reset: () => conv.reset()
1824
916
  };
1825
917
  }
1826
- var ConvCtx = import_react5.default.createContext(null);
1827
- var FormCtxInternal = import_react5.default.createContext(null);
918
+ var ConvCtx = React4.createContext(null);
919
+ var FormCtxInternal = React4.createContext(null);
1828
920
  function useConversationContext() {
1829
- const ctx = import_react5.default.useContext(ConvCtx);
921
+ const ctx = React4.useContext(ConvCtx);
1830
922
  if (!ctx)
1831
923
  throw new Error("useConversationContext must be used inside <Conversation>");
1832
924
  return ctx;
1833
925
  }
1834
926
  function useFormContext() {
1835
- const ctx = import_react5.default.useContext(FormCtxInternal);
927
+ const ctx = React4.useContext(FormCtxInternal);
1836
928
  if (!ctx)
1837
929
  throw new Error("useFormContext must be used inside <Form>");
1838
930
  return ctx;
@@ -1856,13 +948,13 @@ function FormCompleteChild(_) {
1856
948
  return null;
1857
949
  }
1858
950
  function ConversationRoot({ children, value }) {
1859
- const configRef = import_react5.default.useRef(undefined);
1860
- const built = import_react5.default.useRef(false);
951
+ const configRef = React4.useRef(undefined);
952
+ const built = React4.useRef(false);
1861
953
  if (!built.current) {
1862
954
  built.current = true;
1863
955
  const config = {};
1864
- import_react5.default.Children.forEach(children, (child) => {
1865
- if (!import_react5.default.isValidElement(child))
956
+ React4.Children.forEach(children, (child) => {
957
+ if (!React4.isValidElement(child))
1866
958
  return;
1867
959
  if (child.type === ConversationPrompt) {
1868
960
  const p = child.props;
@@ -1878,8 +970,8 @@ function ConversationRoot({ children, value }) {
1878
970
  configRef.current = Object.keys(config).length > 0 ? config : undefined;
1879
971
  }
1880
972
  if (configRef.current) {
1881
- import_react5.default.Children.forEach(children, (child) => {
1882
- if (import_react5.default.isValidElement(child) && child.type === ConversationStepChild) {
973
+ React4.Children.forEach(children, (child) => {
974
+ if (React4.isValidElement(child) && child.type === ConversationStepChild) {
1883
975
  const p = child.props;
1884
976
  const def = configRef.current[p.name];
1885
977
  if (def && "render" in def)
@@ -1890,17 +982,17 @@ function ConversationRoot({ children, value }) {
1890
982
  const internalConv = useConversation(configRef.current);
1891
983
  const conv = value ?? internalConv;
1892
984
  let completeContent = null;
1893
- import_react5.default.Children.forEach(children, (child) => {
1894
- if (import_react5.default.isValidElement(child) && child.type === ConversationComplete) {
985
+ React4.Children.forEach(children, (child) => {
986
+ if (React4.isValidElement(child) && child.type === ConversationComplete) {
1895
987
  completeContent = child.props.children;
1896
988
  }
1897
989
  });
1898
990
  const el = conv.render(() => {
1899
991
  if (typeof completeContent === "function")
1900
992
  return completeContent(conv);
1901
- return completeContent ?? import_react5.default.createElement("tg-message", { text: "\u2713" });
993
+ return completeContent ?? React4.createElement("tg-message", { text: "\u2713" });
1902
994
  });
1903
- return import_react5.default.createElement(ConvCtx.Provider, { value: conv }, el);
995
+ return React4.createElement(ConvCtx.Provider, { value: conv }, el);
1904
996
  }
1905
997
  var Conversation = Object.assign(ConversationRoot, {
1906
998
  Prompt: ConversationPrompt,
@@ -1909,13 +1001,13 @@ var Conversation = Object.assign(ConversationRoot, {
1909
1001
  Complete: ConversationComplete
1910
1002
  });
1911
1003
  function FormRoot({ children, value }) {
1912
- const schemaRef = import_react5.default.useRef(undefined);
1913
- const built = import_react5.default.useRef(false);
1004
+ const schemaRef = React4.useRef(undefined);
1005
+ const built = React4.useRef(false);
1914
1006
  if (!built.current) {
1915
1007
  built.current = true;
1916
1008
  const schema = {};
1917
- import_react5.default.Children.forEach(children, (child) => {
1918
- if (!import_react5.default.isValidElement(child))
1009
+ React4.Children.forEach(children, (child) => {
1010
+ if (!React4.isValidElement(child))
1919
1011
  return;
1920
1012
  if (child.type === FormFieldChild) {
1921
1013
  const p = child.props;
@@ -1927,30 +1019,30 @@ function FormRoot({ children, value }) {
1927
1019
  const internalForm = useForm(schemaRef.current ?? {});
1928
1020
  const form = value ?? internalForm;
1929
1021
  let completeContent = null;
1930
- import_react5.default.Children.forEach(children, (child) => {
1931
- if (import_react5.default.isValidElement(child) && child.type === FormCompleteChild) {
1022
+ React4.Children.forEach(children, (child) => {
1023
+ if (React4.isValidElement(child) && child.type === FormCompleteChild) {
1932
1024
  completeContent = child.props.children;
1933
1025
  }
1934
1026
  });
1935
1027
  const el = form.render(() => {
1936
1028
  if (typeof completeContent === "function")
1937
1029
  return completeContent(form);
1938
- return completeContent ?? import_react5.default.createElement("tg-message", { text: "\u2713" });
1030
+ return completeContent ?? React4.createElement("tg-message", { text: "\u2713" });
1939
1031
  });
1940
- return import_react5.default.createElement(FormCtxInternal.Provider, { value: form }, el);
1032
+ return React4.createElement(FormCtxInternal.Provider, { value: form }, el);
1941
1033
  }
1942
1034
  var Form = Object.assign(FormRoot, {
1943
1035
  Field: FormFieldChild,
1944
1036
  Complete: FormCompleteChild
1945
1037
  });
1946
1038
  // src/stream.ts
1947
- var import_react7 = __toESM(require_react(), 1);
1039
+ import { useState as useState3, useCallback as useCallback3, useRef } from "react";
1948
1040
  function useStream(opts) {
1949
- const [text, setText] = import_react7.useState("");
1950
- const [isStreaming, setIsStreaming] = import_react7.useState(false);
1041
+ const [text, setText] = useState3("");
1042
+ const [isStreaming, setIsStreaming] = useState3(false);
1951
1043
  const throttle = opts?.throttleMs ?? 500;
1952
- const generationRef = import_react7.useRef(0);
1953
- const startStream = import_react7.useCallback((source) => {
1044
+ const generationRef = useRef(0);
1045
+ const startStream = useCallback3((source) => {
1954
1046
  const id = ++generationRef.current;
1955
1047
  setIsStreaming(true);
1956
1048
  setText("");
@@ -1976,10 +1068,10 @@ function useStream(opts) {
1976
1068
  return { text, isStreaming, stream: startStream };
1977
1069
  }
1978
1070
  // src/auth.ts
1979
- var import_react8 = __toESM(require_react(), 1);
1980
- var AuthCtx = import_react8.createContext(null);
1071
+ import React5, { useContext as useContext4, createContext as createContext2 } from "react";
1072
+ var AuthCtx = createContext2(null);
1981
1073
  function useAuth() {
1982
- const ctx = import_react8.useContext(AuthCtx);
1074
+ const ctx = useContext4(AuthCtx);
1983
1075
  if (!ctx)
1984
1076
  throw new Error("useAuth requires the authPlugin to be registered");
1985
1077
  return ctx;
@@ -2018,7 +1110,7 @@ function authPlugin(config = {}) {
2018
1110
  return roles.some((r) => authState.is(r));
2019
1111
  }
2020
1112
  };
2021
- return import_react8.default.createElement(AuthCtx.Provider, { value: authState }, children);
1113
+ return React5.createElement(AuthCtx.Provider, { value: authState }, children);
2022
1114
  };
2023
1115
  return {
2024
1116
  name: "auth",
@@ -2026,26 +1118,26 @@ function authPlugin(config = {}) {
2026
1118
  };
2027
1119
  }
2028
1120
  // src/auth-session.ts
2029
- var import_react9 = __toESM(require_react(), 1);
1121
+ import { useCallback as useCallback4, useMemo as useMemo2 } from "react";
2030
1122
  var AUTH_KEY = "auth";
2031
1123
  function useAuthSession() {
2032
1124
  const [session, setSession] = useSession();
2033
1125
  const stored = session[AUTH_KEY];
2034
1126
  const isExpired = stored?.expiresAt ? Date.now() > stored.expiresAt : false;
2035
1127
  const isAuthenticated = !!stored?.accessToken && !isExpired;
2036
- const login = import_react9.useCallback((tokens) => {
1128
+ const login = useCallback4((tokens) => {
2037
1129
  setSession({ [AUTH_KEY]: tokens });
2038
1130
  }, [setSession]);
2039
- const logout = import_react9.useCallback(() => {
1131
+ const logout = useCallback4(() => {
2040
1132
  setSession({ [AUTH_KEY]: undefined });
2041
1133
  }, [setSession]);
2042
- const setAccessToken = import_react9.useCallback((token, expiresAt) => {
1134
+ const setAccessToken = useCallback4((token, expiresAt) => {
2043
1135
  const current = session[AUTH_KEY] ?? {};
2044
1136
  setSession({
2045
1137
  [AUTH_KEY]: { ...current, accessToken: token, ...expiresAt != null ? { expiresAt } : {} }
2046
1138
  });
2047
1139
  }, [session, setSession]);
2048
- return import_react9.useMemo(() => ({
1140
+ return useMemo2(() => ({
2049
1141
  isAuthenticated,
2050
1142
  accessToken: isAuthenticated ? stored?.accessToken ?? null : null,
2051
1143
  refreshToken: stored?.refreshToken ?? null,
@@ -2060,7 +1152,7 @@ function defineConfig(config) {
2060
1152
  return config;
2061
1153
  }
2062
1154
  // src/media-hooks.ts
2063
- var import_react10 = __toESM(require_react(), 1);
1155
+ import { useCallback as useCallback5 } from "react";
2064
1156
  function useChat() {
2065
1157
  const bot = useBot();
2066
1158
  return {
@@ -2086,53 +1178,53 @@ function useTelegram() {
2086
1178
  }
2087
1179
  function usePhoto() {
2088
1180
  const { api, chatId } = useTelegram();
2089
- return import_react10.useCallback((src, opts) => api?.sendPhoto(chatId, src, opts), [api, chatId]);
1181
+ return useCallback5((src, opts) => api?.sendPhoto(chatId, src, opts), [api, chatId]);
2090
1182
  }
2091
1183
  function useVideo() {
2092
1184
  const { api, chatId } = useTelegram();
2093
- return import_react10.useCallback((src, opts) => api?.sendVideo(chatId, src, opts), [api, chatId]);
1185
+ return useCallback5((src, opts) => api?.sendVideo(chatId, src, opts), [api, chatId]);
2094
1186
  }
2095
1187
  function useAnimation() {
2096
1188
  const { api, chatId } = useTelegram();
2097
- return import_react10.useCallback((src, opts) => api?.sendAnimation(chatId, src, opts), [api, chatId]);
1189
+ return useCallback5((src, opts) => api?.sendAnimation(chatId, src, opts), [api, chatId]);
2098
1190
  }
2099
1191
  function useAudio() {
2100
1192
  const { api, chatId } = useTelegram();
2101
- return import_react10.useCallback((src, opts) => api?.sendAudio(chatId, src, opts), [api, chatId]);
1193
+ return useCallback5((src, opts) => api?.sendAudio(chatId, src, opts), [api, chatId]);
2102
1194
  }
2103
1195
  function useVoice() {
2104
1196
  const { api, chatId } = useTelegram();
2105
- return import_react10.useCallback((src, opts) => api?.sendVoice(chatId, src, opts), [api, chatId]);
1197
+ return useCallback5((src, opts) => api?.sendVoice(chatId, src, opts), [api, chatId]);
2106
1198
  }
2107
1199
  function useDocument() {
2108
1200
  const { api, chatId } = useTelegram();
2109
- return import_react10.useCallback((src, opts) => api?.sendDocument(chatId, src, opts), [api, chatId]);
1201
+ return useCallback5((src, opts) => api?.sendDocument(chatId, src, opts), [api, chatId]);
2110
1202
  }
2111
1203
  function useSticker() {
2112
1204
  const { api, chatId } = useTelegram();
2113
- return import_react10.useCallback((src, opts) => api?.sendSticker(chatId, src, opts), [api, chatId]);
1205
+ return useCallback5((src, opts) => api?.sendSticker(chatId, src, opts), [api, chatId]);
2114
1206
  }
2115
1207
  function useLocation() {
2116
1208
  const { api, chatId } = useTelegram();
2117
- return import_react10.useCallback((latitude, longitude, opts) => api?.sendLocation(chatId, latitude, longitude, opts), [api, chatId]);
1209
+ return useCallback5((latitude, longitude, opts) => api?.sendLocation(chatId, latitude, longitude, opts), [api, chatId]);
2118
1210
  }
2119
1211
  function useContact() {
2120
1212
  const { api, chatId } = useTelegram();
2121
- return import_react10.useCallback((phoneNumber, firstName, opts) => api?.sendContact(chatId, phoneNumber, firstName, opts), [api, chatId]);
1213
+ return useCallback5((phoneNumber, firstName, opts) => api?.sendContact(chatId, phoneNumber, firstName, opts), [api, chatId]);
2122
1214
  }
2123
1215
  function useVenue() {
2124
1216
  const { api, chatId } = useTelegram();
2125
- return import_react10.useCallback((latitude, longitude, title, address, opts) => api?.sendVenue(chatId, latitude, longitude, title, address, opts), [api, chatId]);
1217
+ return useCallback5((latitude, longitude, title, address, opts) => api?.sendVenue(chatId, latitude, longitude, title, address, opts), [api, chatId]);
2126
1218
  }
2127
1219
  function usePoll() {
2128
1220
  const { api, chatId } = useTelegram();
2129
- return import_react10.useCallback((question, options, opts) => {
1221
+ return useCallback5((question, options, opts) => {
2130
1222
  const pollOptions = options.map((text) => ({ text }));
2131
1223
  return api?.sendPoll(chatId, question, pollOptions, opts);
2132
1224
  }, [api, chatId]);
2133
1225
  }
2134
1226
  // src/event-hooks.ts
2135
- var import_react11 = __toESM(require_react(), 1);
1227
+ import { useEffect, useRef as useRef2, useContext as useContext5 } from "react";
2136
1228
  function extractEventData(event, raw) {
2137
1229
  const msg = raw?.message;
2138
1230
  switch (event) {
@@ -2190,14 +1282,14 @@ function extractEventData(event, raw) {
2190
1282
  }
2191
1283
  function useOn(event, handler) {
2192
1284
  const bot = useBot();
2193
- const routerCtx = import_react11.useContext(RouterCtx);
1285
+ const routerCtx = useContext5(RouterCtx);
2194
1286
  const raw = bot.raw;
2195
- const handlerRef = import_react11.useRef(handler);
1287
+ const handlerRef = useRef2(handler);
2196
1288
  handlerRef.current = handler;
2197
- const lastProcessedRef = import_react11.useRef(null);
2198
- const navigateRef = import_react11.useRef(routerCtx?.navigate ?? (() => {}));
1289
+ const lastProcessedRef = useRef2(null);
1290
+ const navigateRef = useRef2(routerCtx?.navigate ?? (() => {}));
2199
1291
  navigateRef.current = routerCtx?.navigate ?? (() => {});
2200
- import_react11.useEffect(() => {
1292
+ useEffect(() => {
2201
1293
  if (!raw)
2202
1294
  return;
2203
1295
  const updateId = raw.update?.update_id ?? raw.message?.message_id ?? raw.callbackQuery?.id;
@@ -2236,2799 +1328,48 @@ function useEventData(event) {
2236
1328
  return extractEventData(event, raw);
2237
1329
  }
2238
1330
  // src/i18n.ts
2239
- var import_react15 = __toESM(require_react(), 1);
2240
-
2241
- // ../../node_modules/.bun/i18next@26.0.3+1fb4c65d43e298b9/node_modules/i18next/dist/esm/i18next.js
2242
- var isString = (obj) => typeof obj === "string";
2243
- var defer = () => {
2244
- let res;
2245
- let rej;
2246
- const promise = new Promise((resolve2, reject) => {
2247
- res = resolve2;
2248
- rej = reject;
2249
- });
2250
- promise.resolve = res;
2251
- promise.reject = rej;
2252
- return promise;
2253
- };
2254
- var makeString = (object) => {
2255
- if (object == null)
2256
- return "";
2257
- return String(object);
2258
- };
2259
- var copy = (a, s, t) => {
2260
- a.forEach((m) => {
2261
- if (s[m])
2262
- t[m] = s[m];
2263
- });
2264
- };
2265
- var lastOfPathSeparatorRegExp = /###/g;
2266
- var cleanKey = (key) => key && key.includes("###") ? key.replace(lastOfPathSeparatorRegExp, ".") : key;
2267
- var canNotTraverseDeeper = (object) => !object || isString(object);
2268
- var getLastOfPath = (object, path, Empty) => {
2269
- const stack = !isString(path) ? path : path.split(".");
2270
- let stackIndex = 0;
2271
- while (stackIndex < stack.length - 1) {
2272
- if (canNotTraverseDeeper(object))
2273
- return {};
2274
- const key = cleanKey(stack[stackIndex]);
2275
- if (!object[key] && Empty)
2276
- object[key] = new Empty;
2277
- if (Object.prototype.hasOwnProperty.call(object, key)) {
2278
- object = object[key];
2279
- } else {
2280
- object = {};
2281
- }
2282
- ++stackIndex;
2283
- }
2284
- if (canNotTraverseDeeper(object))
2285
- return {};
2286
- return {
2287
- obj: object,
2288
- k: cleanKey(stack[stackIndex])
2289
- };
2290
- };
2291
- var setPath = (object, path, newValue) => {
2292
- const {
2293
- obj,
2294
- k
2295
- } = getLastOfPath(object, path, Object);
2296
- if (obj !== undefined || path.length === 1) {
2297
- obj[k] = newValue;
2298
- return;
2299
- }
2300
- let e = path[path.length - 1];
2301
- let p = path.slice(0, path.length - 1);
2302
- let last = getLastOfPath(object, p, Object);
2303
- while (last.obj === undefined && p.length) {
2304
- e = `${p[p.length - 1]}.${e}`;
2305
- p = p.slice(0, p.length - 1);
2306
- last = getLastOfPath(object, p, Object);
2307
- if (last?.obj && typeof last.obj[`${last.k}.${e}`] !== "undefined") {
2308
- last.obj = undefined;
2309
- }
2310
- }
2311
- last.obj[`${last.k}.${e}`] = newValue;
2312
- };
2313
- var pushPath = (object, path, newValue, concat) => {
2314
- const {
2315
- obj,
2316
- k
2317
- } = getLastOfPath(object, path, Object);
2318
- obj[k] = obj[k] || [];
2319
- obj[k].push(newValue);
2320
- };
2321
- var getPath = (object, path) => {
2322
- const {
2323
- obj,
2324
- k
2325
- } = getLastOfPath(object, path);
2326
- if (!obj)
2327
- return;
2328
- if (!Object.prototype.hasOwnProperty.call(obj, k))
2329
- return;
2330
- return obj[k];
2331
- };
2332
- var getPathWithDefaults = (data, defaultData, key) => {
2333
- const value = getPath(data, key);
2334
- if (value !== undefined) {
2335
- return value;
2336
- }
2337
- return getPath(defaultData, key);
2338
- };
2339
- var deepExtend = (target, source, overwrite) => {
2340
- for (const prop in source) {
2341
- if (prop !== "__proto__" && prop !== "constructor") {
2342
- if (prop in target) {
2343
- if (isString(target[prop]) || target[prop] instanceof String || isString(source[prop]) || source[prop] instanceof String) {
2344
- if (overwrite)
2345
- target[prop] = source[prop];
2346
- } else {
2347
- deepExtend(target[prop], source[prop], overwrite);
2348
- }
2349
- } else {
2350
- target[prop] = source[prop];
2351
- }
2352
- }
2353
- }
2354
- return target;
2355
- };
2356
- var regexEscape = (str) => str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
2357
- var _entityMap = {
2358
- "&": "&amp;",
2359
- "<": "&lt;",
2360
- ">": "&gt;",
2361
- '"': "&quot;",
2362
- "'": "&#39;",
2363
- "/": "&#x2F;"
2364
- };
2365
- var escape = (data) => {
2366
- if (isString(data)) {
2367
- return data.replace(/[&<>"'\/]/g, (s) => _entityMap[s]);
2368
- }
2369
- return data;
2370
- };
2371
-
2372
- class RegExpCache {
2373
- constructor(capacity) {
2374
- this.capacity = capacity;
2375
- this.regExpMap = new Map;
2376
- this.regExpQueue = [];
2377
- }
2378
- getRegExp(pattern) {
2379
- const regExpFromCache = this.regExpMap.get(pattern);
2380
- if (regExpFromCache !== undefined) {
2381
- return regExpFromCache;
2382
- }
2383
- const regExpNew = new RegExp(pattern);
2384
- if (this.regExpQueue.length === this.capacity) {
2385
- this.regExpMap.delete(this.regExpQueue.shift());
2386
- }
2387
- this.regExpMap.set(pattern, regExpNew);
2388
- this.regExpQueue.push(pattern);
2389
- return regExpNew;
2390
- }
2391
- }
2392
- var chars = [" ", ",", "?", "!", ";"];
2393
- var looksLikeObjectPathRegExpCache = new RegExpCache(20);
2394
- var looksLikeObjectPath = (key, nsSeparator, keySeparator) => {
2395
- nsSeparator = nsSeparator || "";
2396
- keySeparator = keySeparator || "";
2397
- const possibleChars = chars.filter((c) => !nsSeparator.includes(c) && !keySeparator.includes(c));
2398
- if (possibleChars.length === 0)
2399
- return true;
2400
- const r = looksLikeObjectPathRegExpCache.getRegExp(`(${possibleChars.map((c) => c === "?" ? "\\?" : c).join("|")})`);
2401
- let matched = !r.test(key);
2402
- if (!matched) {
2403
- const ki = key.indexOf(keySeparator);
2404
- if (ki > 0 && !r.test(key.substring(0, ki))) {
2405
- matched = true;
2406
- }
2407
- }
2408
- return matched;
2409
- };
2410
- var deepFind = (obj, path, keySeparator = ".") => {
2411
- if (!obj)
2412
- return;
2413
- if (obj[path]) {
2414
- if (!Object.prototype.hasOwnProperty.call(obj, path))
2415
- return;
2416
- return obj[path];
2417
- }
2418
- const tokens = path.split(keySeparator);
2419
- let current = obj;
2420
- for (let i = 0;i < tokens.length; ) {
2421
- if (!current || typeof current !== "object") {
2422
- return;
2423
- }
2424
- let next;
2425
- let nextPath = "";
2426
- for (let j = i;j < tokens.length; ++j) {
2427
- if (j !== i) {
2428
- nextPath += keySeparator;
2429
- }
2430
- nextPath += tokens[j];
2431
- next = current[nextPath];
2432
- if (next !== undefined) {
2433
- if (["string", "number", "boolean"].includes(typeof next) && j < tokens.length - 1) {
2434
- continue;
2435
- }
2436
- i += j - i + 1;
2437
- break;
2438
- }
2439
- }
2440
- current = next;
2441
- }
2442
- return current;
2443
- };
2444
- var getCleanedCode = (code) => code?.replace(/_/g, "-");
2445
- var consoleLogger = {
2446
- type: "logger",
2447
- log(args) {
2448
- this.output("log", args);
2449
- },
2450
- warn(args) {
2451
- this.output("warn", args);
2452
- },
2453
- error(args) {
2454
- this.output("error", args);
2455
- },
2456
- output(type, args) {
2457
- console?.[type]?.apply?.(console, args);
2458
- }
2459
- };
2460
-
2461
- class Logger {
2462
- constructor(concreteLogger, options = {}) {
2463
- this.init(concreteLogger, options);
2464
- }
2465
- init(concreteLogger, options = {}) {
2466
- this.prefix = options.prefix || "i18next:";
2467
- this.logger = concreteLogger || consoleLogger;
2468
- this.options = options;
2469
- this.debug = options.debug;
2470
- }
2471
- log(...args) {
2472
- return this.forward(args, "log", "", true);
2473
- }
2474
- warn(...args) {
2475
- return this.forward(args, "warn", "", true);
2476
- }
2477
- error(...args) {
2478
- return this.forward(args, "error", "");
2479
- }
2480
- deprecate(...args) {
2481
- return this.forward(args, "warn", "WARNING DEPRECATED: ", true);
2482
- }
2483
- forward(args, lvl, prefix, debugOnly) {
2484
- if (debugOnly && !this.debug)
2485
- return null;
2486
- if (isString(args[0]))
2487
- args[0] = `${prefix}${this.prefix} ${args[0]}`;
2488
- return this.logger[lvl](args);
2489
- }
2490
- create(moduleName) {
2491
- return new Logger(this.logger, {
2492
- ...{
2493
- prefix: `${this.prefix}:${moduleName}:`
2494
- },
2495
- ...this.options
2496
- });
2497
- }
2498
- clone(options) {
2499
- options = options || this.options;
2500
- options.prefix = options.prefix || this.prefix;
2501
- return new Logger(this.logger, options);
2502
- }
2503
- }
2504
- var baseLogger = new Logger;
2505
-
2506
- class EventEmitter {
2507
- constructor() {
2508
- this.observers = {};
2509
- }
2510
- on(events, listener) {
2511
- events.split(" ").forEach((event) => {
2512
- if (!this.observers[event])
2513
- this.observers[event] = new Map;
2514
- const numListeners = this.observers[event].get(listener) || 0;
2515
- this.observers[event].set(listener, numListeners + 1);
2516
- });
2517
- return this;
2518
- }
2519
- off(event, listener) {
2520
- if (!this.observers[event])
2521
- return;
2522
- if (!listener) {
2523
- delete this.observers[event];
2524
- return;
2525
- }
2526
- this.observers[event].delete(listener);
2527
- }
2528
- once(event, listener) {
2529
- const wrapper = (...args) => {
2530
- listener(...args);
2531
- this.off(event, wrapper);
2532
- };
2533
- this.on(event, wrapper);
2534
- return this;
2535
- }
2536
- emit(event, ...args) {
2537
- if (this.observers[event]) {
2538
- const cloned = Array.from(this.observers[event].entries());
2539
- cloned.forEach(([observer, numTimesAdded]) => {
2540
- for (let i = 0;i < numTimesAdded; i++) {
2541
- observer(...args);
2542
- }
2543
- });
2544
- }
2545
- if (this.observers["*"]) {
2546
- const cloned = Array.from(this.observers["*"].entries());
2547
- cloned.forEach(([observer, numTimesAdded]) => {
2548
- for (let i = 0;i < numTimesAdded; i++) {
2549
- observer(event, ...args);
2550
- }
2551
- });
2552
- }
2553
- }
2554
- }
2555
-
2556
- class ResourceStore extends EventEmitter {
2557
- constructor(data, options = {
2558
- ns: ["translation"],
2559
- defaultNS: "translation"
2560
- }) {
2561
- super();
2562
- this.data = data || {};
2563
- this.options = options;
2564
- if (this.options.keySeparator === undefined) {
2565
- this.options.keySeparator = ".";
2566
- }
2567
- if (this.options.ignoreJSONStructure === undefined) {
2568
- this.options.ignoreJSONStructure = true;
2569
- }
2570
- }
2571
- addNamespaces(ns) {
2572
- if (!this.options.ns.includes(ns)) {
2573
- this.options.ns.push(ns);
2574
- }
2575
- }
2576
- removeNamespaces(ns) {
2577
- const index = this.options.ns.indexOf(ns);
2578
- if (index > -1) {
2579
- this.options.ns.splice(index, 1);
2580
- }
2581
- }
2582
- getResource(lng, ns, key, options = {}) {
2583
- const keySeparator = options.keySeparator !== undefined ? options.keySeparator : this.options.keySeparator;
2584
- const ignoreJSONStructure = options.ignoreJSONStructure !== undefined ? options.ignoreJSONStructure : this.options.ignoreJSONStructure;
2585
- let path;
2586
- if (lng.includes(".")) {
2587
- path = lng.split(".");
2588
- } else {
2589
- path = [lng, ns];
2590
- if (key) {
2591
- if (Array.isArray(key)) {
2592
- path.push(...key);
2593
- } else if (isString(key) && keySeparator) {
2594
- path.push(...key.split(keySeparator));
2595
- } else {
2596
- path.push(key);
2597
- }
2598
- }
2599
- }
2600
- const result = getPath(this.data, path);
2601
- if (!result && !ns && !key && lng.includes(".")) {
2602
- lng = path[0];
2603
- ns = path[1];
2604
- key = path.slice(2).join(".");
2605
- }
2606
- if (result || !ignoreJSONStructure || !isString(key))
2607
- return result;
2608
- return deepFind(this.data?.[lng]?.[ns], key, keySeparator);
2609
- }
2610
- addResource(lng, ns, key, value, options = {
2611
- silent: false
2612
- }) {
2613
- const keySeparator = options.keySeparator !== undefined ? options.keySeparator : this.options.keySeparator;
2614
- let path = [lng, ns];
2615
- if (key)
2616
- path = path.concat(keySeparator ? key.split(keySeparator) : key);
2617
- if (lng.includes(".")) {
2618
- path = lng.split(".");
2619
- value = ns;
2620
- ns = path[1];
2621
- }
2622
- this.addNamespaces(ns);
2623
- setPath(this.data, path, value);
2624
- if (!options.silent)
2625
- this.emit("added", lng, ns, key, value);
2626
- }
2627
- addResources(lng, ns, resources, options = {
2628
- silent: false
2629
- }) {
2630
- for (const m in resources) {
2631
- if (isString(resources[m]) || Array.isArray(resources[m]))
2632
- this.addResource(lng, ns, m, resources[m], {
2633
- silent: true
2634
- });
2635
- }
2636
- if (!options.silent)
2637
- this.emit("added", lng, ns, resources);
2638
- }
2639
- addResourceBundle(lng, ns, resources, deep, overwrite, options = {
2640
- silent: false,
2641
- skipCopy: false
2642
- }) {
2643
- let path = [lng, ns];
2644
- if (lng.includes(".")) {
2645
- path = lng.split(".");
2646
- deep = resources;
2647
- resources = ns;
2648
- ns = path[1];
2649
- }
2650
- this.addNamespaces(ns);
2651
- let pack = getPath(this.data, path) || {};
2652
- if (!options.skipCopy)
2653
- resources = JSON.parse(JSON.stringify(resources));
2654
- if (deep) {
2655
- deepExtend(pack, resources, overwrite);
2656
- } else {
2657
- pack = {
2658
- ...pack,
2659
- ...resources
2660
- };
2661
- }
2662
- setPath(this.data, path, pack);
2663
- if (!options.silent)
2664
- this.emit("added", lng, ns, resources);
2665
- }
2666
- removeResourceBundle(lng, ns) {
2667
- if (this.hasResourceBundle(lng, ns)) {
2668
- delete this.data[lng][ns];
2669
- }
2670
- this.removeNamespaces(ns);
2671
- this.emit("removed", lng, ns);
2672
- }
2673
- hasResourceBundle(lng, ns) {
2674
- return this.getResource(lng, ns) !== undefined;
2675
- }
2676
- getResourceBundle(lng, ns) {
2677
- if (!ns)
2678
- ns = this.options.defaultNS;
2679
- return this.getResource(lng, ns);
2680
- }
2681
- getDataByLanguage(lng) {
2682
- return this.data[lng];
2683
- }
2684
- hasLanguageSomeTranslations(lng) {
2685
- const data = this.getDataByLanguage(lng);
2686
- const n = data && Object.keys(data) || [];
2687
- return !!n.find((v) => data[v] && Object.keys(data[v]).length > 0);
2688
- }
2689
- toJSON() {
2690
- return this.data;
2691
- }
2692
- }
2693
- var postProcessor = {
2694
- processors: {},
2695
- addPostProcessor(module) {
2696
- this.processors[module.name] = module;
2697
- },
2698
- handle(processors, value, key, options, translator) {
2699
- processors.forEach((processor) => {
2700
- value = this.processors[processor]?.process(value, key, options, translator) ?? value;
2701
- });
2702
- return value;
2703
- }
2704
- };
2705
- var PATH_KEY = Symbol("i18next/PATH_KEY");
2706
- function createProxy() {
2707
- const state = [];
2708
- const handler = Object.create(null);
2709
- let proxy;
2710
- handler.get = (target, key) => {
2711
- proxy?.revoke?.();
2712
- if (key === PATH_KEY)
2713
- return state;
2714
- state.push(key);
2715
- proxy = Proxy.revocable(target, handler);
2716
- return proxy.proxy;
2717
- };
2718
- return Proxy.revocable(Object.create(null), handler).proxy;
2719
- }
2720
- function keysFromSelector(selector, opts) {
2721
- const {
2722
- [PATH_KEY]: path
2723
- } = selector(createProxy());
2724
- const keySeparator = opts?.keySeparator ?? ".";
2725
- const nsSeparator = opts?.nsSeparator ?? ":";
2726
- if (path.length > 1 && nsSeparator) {
2727
- const ns = opts?.ns;
2728
- const nsArray = Array.isArray(ns) ? ns : null;
2729
- if (nsArray && nsArray.length > 1 && nsArray.slice(1).includes(path[0])) {
2730
- return `${path[0]}${nsSeparator}${path.slice(1).join(keySeparator)}`;
2731
- }
2732
- }
2733
- return path.join(keySeparator);
2734
- }
2735
- var shouldHandleAsObject = (res) => !isString(res) && typeof res !== "boolean" && typeof res !== "number";
2736
-
2737
- class Translator extends EventEmitter {
2738
- constructor(services, options = {}) {
2739
- super();
2740
- copy(["resourceStore", "languageUtils", "pluralResolver", "interpolator", "backendConnector", "i18nFormat", "utils"], services, this);
2741
- this.options = options;
2742
- if (this.options.keySeparator === undefined) {
2743
- this.options.keySeparator = ".";
2744
- }
2745
- this.logger = baseLogger.create("translator");
2746
- this.checkedLoadedFor = {};
2747
- }
2748
- changeLanguage(lng) {
2749
- if (lng)
2750
- this.language = lng;
2751
- }
2752
- exists(key, o = {
2753
- interpolation: {}
2754
- }) {
2755
- const opt = {
2756
- ...o
2757
- };
2758
- if (key == null)
2759
- return false;
2760
- const resolved = this.resolve(key, opt);
2761
- if (resolved?.res === undefined)
2762
- return false;
2763
- const isObject = shouldHandleAsObject(resolved.res);
2764
- if (opt.returnObjects === false && isObject) {
2765
- return false;
2766
- }
2767
- return true;
2768
- }
2769
- extractFromKey(key, opt) {
2770
- let nsSeparator = opt.nsSeparator !== undefined ? opt.nsSeparator : this.options.nsSeparator;
2771
- if (nsSeparator === undefined)
2772
- nsSeparator = ":";
2773
- const keySeparator = opt.keySeparator !== undefined ? opt.keySeparator : this.options.keySeparator;
2774
- let namespaces = opt.ns || this.options.defaultNS || [];
2775
- const wouldCheckForNsInKey = nsSeparator && key.includes(nsSeparator);
2776
- const seemsNaturalLanguage = !this.options.userDefinedKeySeparator && !opt.keySeparator && !this.options.userDefinedNsSeparator && !opt.nsSeparator && !looksLikeObjectPath(key, nsSeparator, keySeparator);
2777
- if (wouldCheckForNsInKey && !seemsNaturalLanguage) {
2778
- const m = key.match(this.interpolator.nestingRegexp);
2779
- if (m && m.length > 0) {
2780
- return {
2781
- key,
2782
- namespaces: isString(namespaces) ? [namespaces] : namespaces
2783
- };
2784
- }
2785
- const parts = key.split(nsSeparator);
2786
- if (nsSeparator !== keySeparator || nsSeparator === keySeparator && this.options.ns.includes(parts[0]))
2787
- namespaces = parts.shift();
2788
- key = parts.join(keySeparator);
2789
- }
2790
- return {
2791
- key,
2792
- namespaces: isString(namespaces) ? [namespaces] : namespaces
2793
- };
2794
- }
2795
- translate(keys, o, lastKey) {
2796
- let opt = typeof o === "object" ? {
2797
- ...o
2798
- } : o;
2799
- if (typeof opt !== "object" && this.options.overloadTranslationOptionHandler) {
2800
- opt = this.options.overloadTranslationOptionHandler(arguments);
2801
- }
2802
- if (typeof opt === "object")
2803
- opt = {
2804
- ...opt
2805
- };
2806
- if (!opt)
2807
- opt = {};
2808
- if (keys == null)
2809
- return "";
2810
- if (typeof keys === "function")
2811
- keys = keysFromSelector(keys, {
2812
- ...this.options,
2813
- ...opt
2814
- });
2815
- if (!Array.isArray(keys))
2816
- keys = [String(keys)];
2817
- keys = keys.map((k) => typeof k === "function" ? keysFromSelector(k, {
2818
- ...this.options,
2819
- ...opt
2820
- }) : String(k));
2821
- const returnDetails = opt.returnDetails !== undefined ? opt.returnDetails : this.options.returnDetails;
2822
- const keySeparator = opt.keySeparator !== undefined ? opt.keySeparator : this.options.keySeparator;
2823
- const {
2824
- key,
2825
- namespaces
2826
- } = this.extractFromKey(keys[keys.length - 1], opt);
2827
- const namespace = namespaces[namespaces.length - 1];
2828
- let nsSeparator = opt.nsSeparator !== undefined ? opt.nsSeparator : this.options.nsSeparator;
2829
- if (nsSeparator === undefined)
2830
- nsSeparator = ":";
2831
- const lng = opt.lng || this.language;
2832
- const appendNamespaceToCIMode = opt.appendNamespaceToCIMode || this.options.appendNamespaceToCIMode;
2833
- if (lng?.toLowerCase() === "cimode") {
2834
- if (appendNamespaceToCIMode) {
2835
- if (returnDetails) {
2836
- return {
2837
- res: `${namespace}${nsSeparator}${key}`,
2838
- usedKey: key,
2839
- exactUsedKey: key,
2840
- usedLng: lng,
2841
- usedNS: namespace,
2842
- usedParams: this.getUsedParamsDetails(opt)
2843
- };
2844
- }
2845
- return `${namespace}${nsSeparator}${key}`;
2846
- }
2847
- if (returnDetails) {
2848
- return {
2849
- res: key,
2850
- usedKey: key,
2851
- exactUsedKey: key,
2852
- usedLng: lng,
2853
- usedNS: namespace,
2854
- usedParams: this.getUsedParamsDetails(opt)
2855
- };
2856
- }
2857
- return key;
2858
- }
2859
- const resolved = this.resolve(keys, opt);
2860
- let res = resolved?.res;
2861
- const resUsedKey = resolved?.usedKey || key;
2862
- const resExactUsedKey = resolved?.exactUsedKey || key;
2863
- const noObject = ["[object Number]", "[object Function]", "[object RegExp]"];
2864
- const joinArrays = opt.joinArrays !== undefined ? opt.joinArrays : this.options.joinArrays;
2865
- const handleAsObjectInI18nFormat = !this.i18nFormat || this.i18nFormat.handleAsObject;
2866
- const needsPluralHandling = opt.count !== undefined && !isString(opt.count);
2867
- const hasDefaultValue = Translator.hasDefaultValue(opt);
2868
- const defaultValueSuffix = needsPluralHandling ? this.pluralResolver.getSuffix(lng, opt.count, opt) : "";
2869
- const defaultValueSuffixOrdinalFallback = opt.ordinal && needsPluralHandling ? this.pluralResolver.getSuffix(lng, opt.count, {
2870
- ordinal: false
2871
- }) : "";
2872
- const needsZeroSuffixLookup = needsPluralHandling && !opt.ordinal && opt.count === 0;
2873
- const defaultValue = needsZeroSuffixLookup && opt[`defaultValue${this.options.pluralSeparator}zero`] || opt[`defaultValue${defaultValueSuffix}`] || opt[`defaultValue${defaultValueSuffixOrdinalFallback}`] || opt.defaultValue;
2874
- let resForObjHndl = res;
2875
- if (handleAsObjectInI18nFormat && !res && hasDefaultValue) {
2876
- resForObjHndl = defaultValue;
2877
- }
2878
- const handleAsObject = shouldHandleAsObject(resForObjHndl);
2879
- const resType = Object.prototype.toString.apply(resForObjHndl);
2880
- if (handleAsObjectInI18nFormat && resForObjHndl && handleAsObject && !noObject.includes(resType) && !(isString(joinArrays) && Array.isArray(resForObjHndl))) {
2881
- if (!opt.returnObjects && !this.options.returnObjects) {
2882
- if (!this.options.returnedObjectHandler) {
2883
- this.logger.warn("accessing an object - but returnObjects options is not enabled!");
2884
- }
2885
- const r = this.options.returnedObjectHandler ? this.options.returnedObjectHandler(resUsedKey, resForObjHndl, {
2886
- ...opt,
2887
- ns: namespaces
2888
- }) : `key '${key} (${this.language})' returned an object instead of string.`;
2889
- if (returnDetails) {
2890
- resolved.res = r;
2891
- resolved.usedParams = this.getUsedParamsDetails(opt);
2892
- return resolved;
2893
- }
2894
- return r;
2895
- }
2896
- if (keySeparator) {
2897
- const resTypeIsArray = Array.isArray(resForObjHndl);
2898
- const copy2 = resTypeIsArray ? [] : {};
2899
- const newKeyToUse = resTypeIsArray ? resExactUsedKey : resUsedKey;
2900
- for (const m in resForObjHndl) {
2901
- if (Object.prototype.hasOwnProperty.call(resForObjHndl, m)) {
2902
- const deepKey = `${newKeyToUse}${keySeparator}${m}`;
2903
- if (hasDefaultValue && !res) {
2904
- copy2[m] = this.translate(deepKey, {
2905
- ...opt,
2906
- defaultValue: shouldHandleAsObject(defaultValue) ? defaultValue[m] : undefined,
2907
- ...{
2908
- joinArrays: false,
2909
- ns: namespaces
2910
- }
2911
- });
2912
- } else {
2913
- copy2[m] = this.translate(deepKey, {
2914
- ...opt,
2915
- ...{
2916
- joinArrays: false,
2917
- ns: namespaces
2918
- }
2919
- });
2920
- }
2921
- if (copy2[m] === deepKey)
2922
- copy2[m] = resForObjHndl[m];
2923
- }
2924
- }
2925
- res = copy2;
2926
- }
2927
- } else if (handleAsObjectInI18nFormat && isString(joinArrays) && Array.isArray(res)) {
2928
- res = res.join(joinArrays);
2929
- if (res)
2930
- res = this.extendTranslation(res, keys, opt, lastKey);
2931
- } else {
2932
- let usedDefault = false;
2933
- let usedKey = false;
2934
- if (!this.isValidLookup(res) && hasDefaultValue) {
2935
- usedDefault = true;
2936
- res = defaultValue;
2937
- }
2938
- if (!this.isValidLookup(res)) {
2939
- usedKey = true;
2940
- res = key;
2941
- }
2942
- const missingKeyNoValueFallbackToKey = opt.missingKeyNoValueFallbackToKey || this.options.missingKeyNoValueFallbackToKey;
2943
- const resForMissing = missingKeyNoValueFallbackToKey && usedKey ? undefined : res;
2944
- const updateMissing = hasDefaultValue && defaultValue !== res && this.options.updateMissing;
2945
- if (usedKey || usedDefault || updateMissing) {
2946
- this.logger.log(updateMissing ? "updateKey" : "missingKey", lng, namespace, key, updateMissing ? defaultValue : res);
2947
- if (keySeparator) {
2948
- const fk = this.resolve(key, {
2949
- ...opt,
2950
- keySeparator: false
2951
- });
2952
- if (fk && fk.res)
2953
- this.logger.warn("Seems the loaded translations were in flat JSON format instead of nested. Either set keySeparator: false on init or make sure your translations are published in nested format.");
2954
- }
2955
- let lngs = [];
2956
- const fallbackLngs = this.languageUtils.getFallbackCodes(this.options.fallbackLng, opt.lng || this.language);
2957
- if (this.options.saveMissingTo === "fallback" && fallbackLngs && fallbackLngs[0]) {
2958
- for (let i = 0;i < fallbackLngs.length; i++) {
2959
- lngs.push(fallbackLngs[i]);
2960
- }
2961
- } else if (this.options.saveMissingTo === "all") {
2962
- lngs = this.languageUtils.toResolveHierarchy(opt.lng || this.language);
2963
- } else {
2964
- lngs.push(opt.lng || this.language);
2965
- }
2966
- const send = (l, k, specificDefaultValue) => {
2967
- const defaultForMissing = hasDefaultValue && specificDefaultValue !== res ? specificDefaultValue : resForMissing;
2968
- if (this.options.missingKeyHandler) {
2969
- this.options.missingKeyHandler(l, namespace, k, defaultForMissing, updateMissing, opt);
2970
- } else if (this.backendConnector?.saveMissing) {
2971
- this.backendConnector.saveMissing(l, namespace, k, defaultForMissing, updateMissing, opt);
2972
- }
2973
- this.emit("missingKey", l, namespace, k, res);
2974
- };
2975
- if (this.options.saveMissing) {
2976
- if (this.options.saveMissingPlurals && needsPluralHandling) {
2977
- lngs.forEach((language) => {
2978
- const suffixes = this.pluralResolver.getSuffixes(language, opt);
2979
- if (needsZeroSuffixLookup && opt[`defaultValue${this.options.pluralSeparator}zero`] && !suffixes.includes(`${this.options.pluralSeparator}zero`)) {
2980
- suffixes.push(`${this.options.pluralSeparator}zero`);
2981
- }
2982
- suffixes.forEach((suffix) => {
2983
- send([language], key + suffix, opt[`defaultValue${suffix}`] || defaultValue);
2984
- });
2985
- });
2986
- } else {
2987
- send(lngs, key, defaultValue);
2988
- }
2989
- }
2990
- }
2991
- res = this.extendTranslation(res, keys, opt, resolved, lastKey);
2992
- if (usedKey && res === key && this.options.appendNamespaceToMissingKey) {
2993
- res = `${namespace}${nsSeparator}${key}`;
2994
- }
2995
- if ((usedKey || usedDefault) && this.options.parseMissingKeyHandler) {
2996
- res = this.options.parseMissingKeyHandler(this.options.appendNamespaceToMissingKey ? `${namespace}${nsSeparator}${key}` : key, usedDefault ? res : undefined, opt);
2997
- }
2998
- }
2999
- if (returnDetails) {
3000
- resolved.res = res;
3001
- resolved.usedParams = this.getUsedParamsDetails(opt);
3002
- return resolved;
3003
- }
3004
- return res;
3005
- }
3006
- extendTranslation(res, key, opt, resolved, lastKey) {
3007
- if (this.i18nFormat?.parse) {
3008
- res = this.i18nFormat.parse(res, {
3009
- ...this.options.interpolation.defaultVariables,
3010
- ...opt
3011
- }, opt.lng || this.language || resolved.usedLng, resolved.usedNS, resolved.usedKey, {
3012
- resolved
3013
- });
3014
- } else if (!opt.skipInterpolation) {
3015
- if (opt.interpolation)
3016
- this.interpolator.init({
3017
- ...opt,
3018
- ...{
3019
- interpolation: {
3020
- ...this.options.interpolation,
3021
- ...opt.interpolation
3022
- }
3023
- }
3024
- });
3025
- const skipOnVariables = isString(res) && (opt?.interpolation?.skipOnVariables !== undefined ? opt.interpolation.skipOnVariables : this.options.interpolation.skipOnVariables);
3026
- let nestBef;
3027
- if (skipOnVariables) {
3028
- const nb = res.match(this.interpolator.nestingRegexp);
3029
- nestBef = nb && nb.length;
3030
- }
3031
- let data = opt.replace && !isString(opt.replace) ? opt.replace : opt;
3032
- if (this.options.interpolation.defaultVariables)
3033
- data = {
3034
- ...this.options.interpolation.defaultVariables,
3035
- ...data
3036
- };
3037
- res = this.interpolator.interpolate(res, data, opt.lng || this.language || resolved.usedLng, opt);
3038
- if (skipOnVariables) {
3039
- const na = res.match(this.interpolator.nestingRegexp);
3040
- const nestAft = na && na.length;
3041
- if (nestBef < nestAft)
3042
- opt.nest = false;
3043
- }
3044
- if (!opt.lng && resolved && resolved.res)
3045
- opt.lng = this.language || resolved.usedLng;
3046
- if (opt.nest !== false)
3047
- res = this.interpolator.nest(res, (...args) => {
3048
- if (lastKey?.[0] === args[0] && !opt.context) {
3049
- this.logger.warn(`It seems you are nesting recursively key: ${args[0]} in key: ${key[0]}`);
3050
- return null;
3051
- }
3052
- return this.translate(...args, key);
3053
- }, opt);
3054
- if (opt.interpolation)
3055
- this.interpolator.reset();
3056
- }
3057
- const postProcess = opt.postProcess || this.options.postProcess;
3058
- const postProcessorNames = isString(postProcess) ? [postProcess] : postProcess;
3059
- if (res != null && postProcessorNames?.length && opt.applyPostProcessor !== false) {
3060
- res = postProcessor.handle(postProcessorNames, res, key, this.options && this.options.postProcessPassResolved ? {
3061
- i18nResolved: {
3062
- ...resolved,
3063
- usedParams: this.getUsedParamsDetails(opt)
3064
- },
3065
- ...opt
3066
- } : opt, this);
3067
- }
3068
- return res;
3069
- }
3070
- resolve(keys, opt = {}) {
3071
- let found;
3072
- let usedKey;
3073
- let exactUsedKey;
3074
- let usedLng;
3075
- let usedNS;
3076
- if (isString(keys))
3077
- keys = [keys];
3078
- if (Array.isArray(keys))
3079
- keys = keys.map((k) => typeof k === "function" ? keysFromSelector(k, {
3080
- ...this.options,
3081
- ...opt
3082
- }) : k);
3083
- keys.forEach((k) => {
3084
- if (this.isValidLookup(found))
3085
- return;
3086
- const extracted = this.extractFromKey(k, opt);
3087
- const key = extracted.key;
3088
- usedKey = key;
3089
- let namespaces = extracted.namespaces;
3090
- if (this.options.fallbackNS)
3091
- namespaces = namespaces.concat(this.options.fallbackNS);
3092
- const needsPluralHandling = opt.count !== undefined && !isString(opt.count);
3093
- const needsZeroSuffixLookup = needsPluralHandling && !opt.ordinal && opt.count === 0;
3094
- const needsContextHandling = opt.context !== undefined && (isString(opt.context) || typeof opt.context === "number") && opt.context !== "";
3095
- const codes = opt.lngs ? opt.lngs : this.languageUtils.toResolveHierarchy(opt.lng || this.language, opt.fallbackLng);
3096
- namespaces.forEach((ns) => {
3097
- if (this.isValidLookup(found))
3098
- return;
3099
- usedNS = ns;
3100
- if (!this.checkedLoadedFor[`${codes[0]}-${ns}`] && this.utils?.hasLoadedNamespace && !this.utils?.hasLoadedNamespace(usedNS)) {
3101
- this.checkedLoadedFor[`${codes[0]}-${ns}`] = true;
3102
- this.logger.warn(`key "${usedKey}" for languages "${codes.join(", ")}" won't get resolved as namespace "${usedNS}" was not yet loaded`, "This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!");
3103
- }
3104
- codes.forEach((code) => {
3105
- if (this.isValidLookup(found))
3106
- return;
3107
- usedLng = code;
3108
- const finalKeys = [key];
3109
- if (this.i18nFormat?.addLookupKeys) {
3110
- this.i18nFormat.addLookupKeys(finalKeys, key, code, ns, opt);
3111
- } else {
3112
- let pluralSuffix;
3113
- if (needsPluralHandling)
3114
- pluralSuffix = this.pluralResolver.getSuffix(code, opt.count, opt);
3115
- const zeroSuffix = `${this.options.pluralSeparator}zero`;
3116
- const ordinalPrefix = `${this.options.pluralSeparator}ordinal${this.options.pluralSeparator}`;
3117
- if (needsPluralHandling) {
3118
- if (opt.ordinal && pluralSuffix.startsWith(ordinalPrefix)) {
3119
- finalKeys.push(key + pluralSuffix.replace(ordinalPrefix, this.options.pluralSeparator));
3120
- }
3121
- finalKeys.push(key + pluralSuffix);
3122
- if (needsZeroSuffixLookup) {
3123
- finalKeys.push(key + zeroSuffix);
3124
- }
3125
- }
3126
- if (needsContextHandling) {
3127
- const contextKey = `${key}${this.options.contextSeparator || "_"}${opt.context}`;
3128
- finalKeys.push(contextKey);
3129
- if (needsPluralHandling) {
3130
- if (opt.ordinal && pluralSuffix.startsWith(ordinalPrefix)) {
3131
- finalKeys.push(contextKey + pluralSuffix.replace(ordinalPrefix, this.options.pluralSeparator));
3132
- }
3133
- finalKeys.push(contextKey + pluralSuffix);
3134
- if (needsZeroSuffixLookup) {
3135
- finalKeys.push(contextKey + zeroSuffix);
3136
- }
3137
- }
3138
- }
3139
- }
3140
- let possibleKey;
3141
- while (possibleKey = finalKeys.pop()) {
3142
- if (!this.isValidLookup(found)) {
3143
- exactUsedKey = possibleKey;
3144
- found = this.getResource(code, ns, possibleKey, opt);
3145
- }
3146
- }
3147
- });
3148
- });
3149
- });
3150
- return {
3151
- res: found,
3152
- usedKey,
3153
- exactUsedKey,
3154
- usedLng,
3155
- usedNS
3156
- };
3157
- }
3158
- isValidLookup(res) {
3159
- return res !== undefined && !(!this.options.returnNull && res === null) && !(!this.options.returnEmptyString && res === "");
3160
- }
3161
- getResource(code, ns, key, options = {}) {
3162
- if (this.i18nFormat?.getResource)
3163
- return this.i18nFormat.getResource(code, ns, key, options);
3164
- return this.resourceStore.getResource(code, ns, key, options);
3165
- }
3166
- getUsedParamsDetails(options = {}) {
3167
- const optionsKeys = ["defaultValue", "ordinal", "context", "replace", "lng", "lngs", "fallbackLng", "ns", "keySeparator", "nsSeparator", "returnObjects", "returnDetails", "joinArrays", "postProcess", "interpolation"];
3168
- const useOptionsReplaceForData = options.replace && !isString(options.replace);
3169
- let data = useOptionsReplaceForData ? options.replace : options;
3170
- if (useOptionsReplaceForData && typeof options.count !== "undefined") {
3171
- data.count = options.count;
3172
- }
3173
- if (this.options.interpolation.defaultVariables) {
3174
- data = {
3175
- ...this.options.interpolation.defaultVariables,
3176
- ...data
3177
- };
3178
- }
3179
- if (!useOptionsReplaceForData) {
3180
- data = {
3181
- ...data
3182
- };
3183
- for (const key of optionsKeys) {
3184
- delete data[key];
3185
- }
3186
- }
3187
- return data;
3188
- }
3189
- static hasDefaultValue(options) {
3190
- const prefix = "defaultValue";
3191
- for (const option in options) {
3192
- if (Object.prototype.hasOwnProperty.call(options, option) && option.startsWith(prefix) && options[option] !== undefined) {
3193
- return true;
3194
- }
3195
- }
3196
- return false;
3197
- }
3198
- }
3199
-
3200
- class LanguageUtil {
3201
- constructor(options) {
3202
- this.options = options;
3203
- this.supportedLngs = this.options.supportedLngs || false;
3204
- this.logger = baseLogger.create("languageUtils");
3205
- }
3206
- getScriptPartFromCode(code) {
3207
- code = getCleanedCode(code);
3208
- if (!code || !code.includes("-"))
3209
- return null;
3210
- const p = code.split("-");
3211
- if (p.length === 2)
3212
- return null;
3213
- p.pop();
3214
- if (p[p.length - 1].toLowerCase() === "x")
3215
- return null;
3216
- return this.formatLanguageCode(p.join("-"));
3217
- }
3218
- getLanguagePartFromCode(code) {
3219
- code = getCleanedCode(code);
3220
- if (!code || !code.includes("-"))
3221
- return code;
3222
- const p = code.split("-");
3223
- return this.formatLanguageCode(p[0]);
3224
- }
3225
- formatLanguageCode(code) {
3226
- if (isString(code) && code.includes("-")) {
3227
- let formattedCode;
3228
- try {
3229
- formattedCode = Intl.getCanonicalLocales(code)[0];
3230
- } catch (e) {}
3231
- if (formattedCode && this.options.lowerCaseLng) {
3232
- formattedCode = formattedCode.toLowerCase();
3233
- }
3234
- if (formattedCode)
3235
- return formattedCode;
3236
- if (this.options.lowerCaseLng) {
3237
- return code.toLowerCase();
3238
- }
3239
- return code;
3240
- }
3241
- return this.options.cleanCode || this.options.lowerCaseLng ? code.toLowerCase() : code;
3242
- }
3243
- isSupportedCode(code) {
3244
- if (this.options.load === "languageOnly" || this.options.nonExplicitSupportedLngs) {
3245
- code = this.getLanguagePartFromCode(code);
3246
- }
3247
- return !this.supportedLngs || !this.supportedLngs.length || this.supportedLngs.includes(code);
3248
- }
3249
- getBestMatchFromCodes(codes) {
3250
- if (!codes)
3251
- return null;
3252
- let found;
3253
- codes.forEach((code) => {
3254
- if (found)
3255
- return;
3256
- const cleanedLng = this.formatLanguageCode(code);
3257
- if (!this.options.supportedLngs || this.isSupportedCode(cleanedLng))
3258
- found = cleanedLng;
3259
- });
3260
- if (!found && this.options.supportedLngs) {
3261
- codes.forEach((code) => {
3262
- if (found)
3263
- return;
3264
- const lngScOnly = this.getScriptPartFromCode(code);
3265
- if (this.isSupportedCode(lngScOnly))
3266
- return found = lngScOnly;
3267
- const lngOnly = this.getLanguagePartFromCode(code);
3268
- if (this.isSupportedCode(lngOnly))
3269
- return found = lngOnly;
3270
- found = this.options.supportedLngs.find((supportedLng) => {
3271
- if (supportedLng === lngOnly)
3272
- return true;
3273
- if (!supportedLng.includes("-") && !lngOnly.includes("-"))
3274
- return false;
3275
- if (supportedLng.includes("-") && !lngOnly.includes("-") && supportedLng.slice(0, supportedLng.indexOf("-")) === lngOnly)
3276
- return true;
3277
- if (supportedLng.startsWith(lngOnly) && lngOnly.length > 1)
3278
- return true;
3279
- return false;
3280
- });
3281
- });
3282
- }
3283
- if (!found)
3284
- found = this.getFallbackCodes(this.options.fallbackLng)[0];
3285
- return found;
3286
- }
3287
- getFallbackCodes(fallbacks, code) {
3288
- if (!fallbacks)
3289
- return [];
3290
- if (typeof fallbacks === "function")
3291
- fallbacks = fallbacks(code);
3292
- if (isString(fallbacks))
3293
- fallbacks = [fallbacks];
3294
- if (Array.isArray(fallbacks))
3295
- return fallbacks;
3296
- if (!code)
3297
- return fallbacks.default || [];
3298
- let found = fallbacks[code];
3299
- if (!found)
3300
- found = fallbacks[this.getScriptPartFromCode(code)];
3301
- if (!found)
3302
- found = fallbacks[this.formatLanguageCode(code)];
3303
- if (!found)
3304
- found = fallbacks[this.getLanguagePartFromCode(code)];
3305
- if (!found)
3306
- found = fallbacks.default;
3307
- return found || [];
3308
- }
3309
- toResolveHierarchy(code, fallbackCode) {
3310
- const fallbackCodes = this.getFallbackCodes((fallbackCode === false ? [] : fallbackCode) || this.options.fallbackLng || [], code);
3311
- const codes = [];
3312
- const addCode = (c) => {
3313
- if (!c)
3314
- return;
3315
- if (this.isSupportedCode(c)) {
3316
- codes.push(c);
3317
- } else {
3318
- this.logger.warn(`rejecting language code not found in supportedLngs: ${c}`);
3319
- }
3320
- };
3321
- if (isString(code) && (code.includes("-") || code.includes("_"))) {
3322
- if (this.options.load !== "languageOnly")
3323
- addCode(this.formatLanguageCode(code));
3324
- if (this.options.load !== "languageOnly" && this.options.load !== "currentOnly")
3325
- addCode(this.getScriptPartFromCode(code));
3326
- if (this.options.load !== "currentOnly")
3327
- addCode(this.getLanguagePartFromCode(code));
3328
- } else if (isString(code)) {
3329
- addCode(this.formatLanguageCode(code));
3330
- }
3331
- fallbackCodes.forEach((fc) => {
3332
- if (!codes.includes(fc))
3333
- addCode(this.formatLanguageCode(fc));
3334
- });
3335
- return codes;
3336
- }
3337
- }
3338
- var suffixesOrder = {
3339
- zero: 0,
3340
- one: 1,
3341
- two: 2,
3342
- few: 3,
3343
- many: 4,
3344
- other: 5
3345
- };
3346
- var dummyRule = {
3347
- select: (count) => count === 1 ? "one" : "other",
3348
- resolvedOptions: () => ({
3349
- pluralCategories: ["one", "other"]
3350
- })
3351
- };
3352
-
3353
- class PluralResolver {
3354
- constructor(languageUtils, options = {}) {
3355
- this.languageUtils = languageUtils;
3356
- this.options = options;
3357
- this.logger = baseLogger.create("pluralResolver");
3358
- this.pluralRulesCache = {};
3359
- }
3360
- clearCache() {
3361
- this.pluralRulesCache = {};
3362
- }
3363
- getRule(code, options = {}) {
3364
- const cleanedCode = getCleanedCode(code === "dev" ? "en" : code);
3365
- const type = options.ordinal ? "ordinal" : "cardinal";
3366
- const cacheKey = JSON.stringify({
3367
- cleanedCode,
3368
- type
3369
- });
3370
- if (cacheKey in this.pluralRulesCache) {
3371
- return this.pluralRulesCache[cacheKey];
3372
- }
3373
- let rule;
3374
- try {
3375
- rule = new Intl.PluralRules(cleanedCode, {
3376
- type
3377
- });
3378
- } catch (err) {
3379
- if (typeof Intl === "undefined") {
3380
- this.logger.error("No Intl support, please use an Intl polyfill!");
3381
- return dummyRule;
3382
- }
3383
- if (!code.match(/-|_/))
3384
- return dummyRule;
3385
- const lngPart = this.languageUtils.getLanguagePartFromCode(code);
3386
- rule = this.getRule(lngPart, options);
3387
- }
3388
- this.pluralRulesCache[cacheKey] = rule;
3389
- return rule;
3390
- }
3391
- needsPlural(code, options = {}) {
3392
- let rule = this.getRule(code, options);
3393
- if (!rule)
3394
- rule = this.getRule("dev", options);
3395
- return rule?.resolvedOptions().pluralCategories.length > 1;
3396
- }
3397
- getPluralFormsOfKey(code, key, options = {}) {
3398
- return this.getSuffixes(code, options).map((suffix) => `${key}${suffix}`);
3399
- }
3400
- getSuffixes(code, options = {}) {
3401
- let rule = this.getRule(code, options);
3402
- if (!rule)
3403
- rule = this.getRule("dev", options);
3404
- if (!rule)
3405
- return [];
3406
- return rule.resolvedOptions().pluralCategories.sort((pluralCategory1, pluralCategory2) => suffixesOrder[pluralCategory1] - suffixesOrder[pluralCategory2]).map((pluralCategory) => `${this.options.prepend}${options.ordinal ? `ordinal${this.options.prepend}` : ""}${pluralCategory}`);
3407
- }
3408
- getSuffix(code, count, options = {}) {
3409
- const rule = this.getRule(code, options);
3410
- if (rule) {
3411
- return `${this.options.prepend}${options.ordinal ? `ordinal${this.options.prepend}` : ""}${rule.select(count)}`;
3412
- }
3413
- this.logger.warn(`no plural rule found for: ${code}`);
3414
- return this.getSuffix("dev", count, options);
3415
- }
3416
- }
3417
- var deepFindWithDefaults = (data, defaultData, key, keySeparator = ".", ignoreJSONStructure = true) => {
3418
- let path = getPathWithDefaults(data, defaultData, key);
3419
- if (!path && ignoreJSONStructure && isString(key)) {
3420
- path = deepFind(data, key, keySeparator);
3421
- if (path === undefined)
3422
- path = deepFind(defaultData, key, keySeparator);
3423
- }
3424
- return path;
3425
- };
3426
- var regexSafe = (val) => val.replace(/\$/g, "$$$$");
3427
-
3428
- class Interpolator {
3429
- constructor(options = {}) {
3430
- this.logger = baseLogger.create("interpolator");
3431
- this.options = options;
3432
- this.format = options?.interpolation?.format || ((value) => value);
3433
- this.init(options);
3434
- }
3435
- init(options = {}) {
3436
- if (!options.interpolation)
3437
- options.interpolation = {
3438
- escapeValue: true
3439
- };
3440
- const {
3441
- escape: escape$1,
3442
- escapeValue,
3443
- useRawValueToEscape,
3444
- prefix,
3445
- prefixEscaped,
3446
- suffix,
3447
- suffixEscaped,
3448
- formatSeparator,
3449
- unescapeSuffix,
3450
- unescapePrefix,
3451
- nestingPrefix,
3452
- nestingPrefixEscaped,
3453
- nestingSuffix,
3454
- nestingSuffixEscaped,
3455
- nestingOptionsSeparator,
3456
- maxReplaces,
3457
- alwaysFormat
3458
- } = options.interpolation;
3459
- this.escape = escape$1 !== undefined ? escape$1 : escape;
3460
- this.escapeValue = escapeValue !== undefined ? escapeValue : true;
3461
- this.useRawValueToEscape = useRawValueToEscape !== undefined ? useRawValueToEscape : false;
3462
- this.prefix = prefix ? regexEscape(prefix) : prefixEscaped || "{{";
3463
- this.suffix = suffix ? regexEscape(suffix) : suffixEscaped || "}}";
3464
- this.formatSeparator = formatSeparator || ",";
3465
- this.unescapePrefix = unescapeSuffix ? "" : unescapePrefix || "-";
3466
- this.unescapeSuffix = this.unescapePrefix ? "" : unescapeSuffix || "";
3467
- this.nestingPrefix = nestingPrefix ? regexEscape(nestingPrefix) : nestingPrefixEscaped || regexEscape("$t(");
3468
- this.nestingSuffix = nestingSuffix ? regexEscape(nestingSuffix) : nestingSuffixEscaped || regexEscape(")");
3469
- this.nestingOptionsSeparator = nestingOptionsSeparator || ",";
3470
- this.maxReplaces = maxReplaces || 1000;
3471
- this.alwaysFormat = alwaysFormat !== undefined ? alwaysFormat : false;
3472
- this.resetRegExp();
3473
- }
3474
- reset() {
3475
- if (this.options)
3476
- this.init(this.options);
3477
- }
3478
- resetRegExp() {
3479
- const getOrResetRegExp = (existingRegExp, pattern) => {
3480
- if (existingRegExp?.source === pattern) {
3481
- existingRegExp.lastIndex = 0;
3482
- return existingRegExp;
3483
- }
3484
- return new RegExp(pattern, "g");
3485
- };
3486
- this.regexp = getOrResetRegExp(this.regexp, `${this.prefix}(.+?)${this.suffix}`);
3487
- this.regexpUnescape = getOrResetRegExp(this.regexpUnescape, `${this.prefix}${this.unescapePrefix}(.+?)${this.unescapeSuffix}${this.suffix}`);
3488
- this.nestingRegexp = getOrResetRegExp(this.nestingRegexp, `${this.nestingPrefix}((?:[^()"']+|"[^"]*"|'[^']*'|\\((?:[^()]|"[^"]*"|'[^']*')*\\))*?)${this.nestingSuffix}`);
3489
- }
3490
- interpolate(str, data, lng, options) {
3491
- let match;
3492
- let value;
3493
- let replaces;
3494
- const defaultData = this.options && this.options.interpolation && this.options.interpolation.defaultVariables || {};
3495
- const handleFormat = (key) => {
3496
- if (!key.includes(this.formatSeparator)) {
3497
- const path = deepFindWithDefaults(data, defaultData, key, this.options.keySeparator, this.options.ignoreJSONStructure);
3498
- return this.alwaysFormat ? this.format(path, undefined, lng, {
3499
- ...options,
3500
- ...data,
3501
- interpolationkey: key
3502
- }) : path;
3503
- }
3504
- const p = key.split(this.formatSeparator);
3505
- const k = p.shift().trim();
3506
- const f = p.join(this.formatSeparator).trim();
3507
- return this.format(deepFindWithDefaults(data, defaultData, k, this.options.keySeparator, this.options.ignoreJSONStructure), f, lng, {
3508
- ...options,
3509
- ...data,
3510
- interpolationkey: k
3511
- });
3512
- };
3513
- this.resetRegExp();
3514
- const missingInterpolationHandler = options?.missingInterpolationHandler || this.options.missingInterpolationHandler;
3515
- const skipOnVariables = options?.interpolation?.skipOnVariables !== undefined ? options.interpolation.skipOnVariables : this.options.interpolation.skipOnVariables;
3516
- const todos = [{
3517
- regex: this.regexpUnescape,
3518
- safeValue: (val) => regexSafe(val)
3519
- }, {
3520
- regex: this.regexp,
3521
- safeValue: (val) => this.escapeValue ? regexSafe(this.escape(val)) : regexSafe(val)
3522
- }];
3523
- todos.forEach((todo) => {
3524
- replaces = 0;
3525
- while (match = todo.regex.exec(str)) {
3526
- const matchedVar = match[1].trim();
3527
- value = handleFormat(matchedVar);
3528
- if (value === undefined) {
3529
- if (typeof missingInterpolationHandler === "function") {
3530
- const temp = missingInterpolationHandler(str, match, options);
3531
- value = isString(temp) ? temp : "";
3532
- } else if (options && Object.prototype.hasOwnProperty.call(options, matchedVar)) {
3533
- value = "";
3534
- } else if (skipOnVariables) {
3535
- value = match[0];
3536
- continue;
3537
- } else {
3538
- this.logger.warn(`missed to pass in variable ${matchedVar} for interpolating ${str}`);
3539
- value = "";
3540
- }
3541
- } else if (!isString(value) && !this.useRawValueToEscape) {
3542
- value = makeString(value);
3543
- }
3544
- const safeValue = todo.safeValue(value);
3545
- str = str.replace(match[0], safeValue);
3546
- if (skipOnVariables) {
3547
- todo.regex.lastIndex += value.length;
3548
- todo.regex.lastIndex -= match[0].length;
3549
- } else {
3550
- todo.regex.lastIndex = 0;
3551
- }
3552
- replaces++;
3553
- if (replaces >= this.maxReplaces) {
3554
- break;
3555
- }
3556
- }
3557
- });
3558
- return str;
3559
- }
3560
- nest(str, fc, options = {}) {
3561
- let match;
3562
- let value;
3563
- let clonedOptions;
3564
- const handleHasOptions = (key, inheritedOptions) => {
3565
- const sep = this.nestingOptionsSeparator;
3566
- if (!key.includes(sep))
3567
- return key;
3568
- const c = key.split(new RegExp(`${regexEscape(sep)}[ ]*{`));
3569
- let optionsString = `{${c[1]}`;
3570
- key = c[0];
3571
- optionsString = this.interpolate(optionsString, clonedOptions);
3572
- const matchedSingleQuotes = optionsString.match(/'/g);
3573
- const matchedDoubleQuotes = optionsString.match(/"/g);
3574
- if ((matchedSingleQuotes?.length ?? 0) % 2 === 0 && !matchedDoubleQuotes || (matchedDoubleQuotes?.length ?? 0) % 2 !== 0) {
3575
- optionsString = optionsString.replace(/'/g, '"');
3576
- }
3577
- try {
3578
- clonedOptions = JSON.parse(optionsString);
3579
- if (inheritedOptions)
3580
- clonedOptions = {
3581
- ...inheritedOptions,
3582
- ...clonedOptions
3583
- };
3584
- } catch (e) {
3585
- this.logger.warn(`failed parsing options string in nesting for key ${key}`, e);
3586
- return `${key}${sep}${optionsString}`;
3587
- }
3588
- if (clonedOptions.defaultValue && clonedOptions.defaultValue.includes(this.prefix))
3589
- delete clonedOptions.defaultValue;
3590
- return key;
3591
- };
3592
- while (match = this.nestingRegexp.exec(str)) {
3593
- let formatters = [];
3594
- clonedOptions = {
3595
- ...options
3596
- };
3597
- clonedOptions = clonedOptions.replace && !isString(clonedOptions.replace) ? clonedOptions.replace : clonedOptions;
3598
- clonedOptions.applyPostProcessor = false;
3599
- delete clonedOptions.defaultValue;
3600
- const keyEndIndex = /{.*}/.test(match[1]) ? match[1].lastIndexOf("}") + 1 : match[1].indexOf(this.formatSeparator);
3601
- if (keyEndIndex !== -1) {
3602
- formatters = match[1].slice(keyEndIndex).split(this.formatSeparator).map((elem) => elem.trim()).filter(Boolean);
3603
- match[1] = match[1].slice(0, keyEndIndex);
3604
- }
3605
- value = fc(handleHasOptions.call(this, match[1].trim(), clonedOptions), clonedOptions);
3606
- if (value && match[0] === str && !isString(value))
3607
- return value;
3608
- if (!isString(value))
3609
- value = makeString(value);
3610
- if (!value) {
3611
- this.logger.warn(`missed to resolve ${match[1]} for nesting ${str}`);
3612
- value = "";
3613
- }
3614
- if (formatters.length) {
3615
- value = formatters.reduce((v, f) => this.format(v, f, options.lng, {
3616
- ...options,
3617
- interpolationkey: match[1].trim()
3618
- }), value.trim());
3619
- }
3620
- str = str.replace(match[0], value);
3621
- this.regexp.lastIndex = 0;
3622
- }
3623
- return str;
3624
- }
3625
- }
3626
- var parseFormatStr = (formatStr) => {
3627
- let formatName = formatStr.toLowerCase().trim();
3628
- const formatOptions = {};
3629
- if (formatStr.includes("(")) {
3630
- const p = formatStr.split("(");
3631
- formatName = p[0].toLowerCase().trim();
3632
- const optStr = p[1].slice(0, -1);
3633
- if (formatName === "currency" && !optStr.includes(":")) {
3634
- if (!formatOptions.currency)
3635
- formatOptions.currency = optStr.trim();
3636
- } else if (formatName === "relativetime" && !optStr.includes(":")) {
3637
- if (!formatOptions.range)
3638
- formatOptions.range = optStr.trim();
3639
- } else {
3640
- const opts = optStr.split(";");
3641
- opts.forEach((opt) => {
3642
- if (opt) {
3643
- const [key, ...rest] = opt.split(":");
3644
- const val = rest.join(":").trim().replace(/^'+|'+$/g, "");
3645
- const trimmedKey = key.trim();
3646
- if (!formatOptions[trimmedKey])
3647
- formatOptions[trimmedKey] = val;
3648
- if (val === "false")
3649
- formatOptions[trimmedKey] = false;
3650
- if (val === "true")
3651
- formatOptions[trimmedKey] = true;
3652
- if (!isNaN(val))
3653
- formatOptions[trimmedKey] = parseInt(val, 10);
3654
- }
3655
- });
3656
- }
3657
- }
3658
- return {
3659
- formatName,
3660
- formatOptions
3661
- };
3662
- };
3663
- var createCachedFormatter = (fn) => {
3664
- const cache = {};
3665
- return (v, l, o) => {
3666
- let optForCache = o;
3667
- if (o && o.interpolationkey && o.formatParams && o.formatParams[o.interpolationkey] && o[o.interpolationkey]) {
3668
- optForCache = {
3669
- ...optForCache,
3670
- [o.interpolationkey]: undefined
3671
- };
3672
- }
3673
- const key = l + JSON.stringify(optForCache);
3674
- let frm = cache[key];
3675
- if (!frm) {
3676
- frm = fn(getCleanedCode(l), o);
3677
- cache[key] = frm;
3678
- }
3679
- return frm(v);
3680
- };
3681
- };
3682
- var createNonCachedFormatter = (fn) => (v, l, o) => fn(getCleanedCode(l), o)(v);
3683
-
3684
- class Formatter {
3685
- constructor(options = {}) {
3686
- this.logger = baseLogger.create("formatter");
3687
- this.options = options;
3688
- this.init(options);
3689
- }
3690
- init(services, options = {
3691
- interpolation: {}
3692
- }) {
3693
- this.formatSeparator = options.interpolation.formatSeparator || ",";
3694
- const cf = options.cacheInBuiltFormats ? createCachedFormatter : createNonCachedFormatter;
3695
- this.formats = {
3696
- number: cf((lng, opt) => {
3697
- const formatter = new Intl.NumberFormat(lng, {
3698
- ...opt
3699
- });
3700
- return (val) => formatter.format(val);
3701
- }),
3702
- currency: cf((lng, opt) => {
3703
- const formatter = new Intl.NumberFormat(lng, {
3704
- ...opt,
3705
- style: "currency"
3706
- });
3707
- return (val) => formatter.format(val);
3708
- }),
3709
- datetime: cf((lng, opt) => {
3710
- const formatter = new Intl.DateTimeFormat(lng, {
3711
- ...opt
3712
- });
3713
- return (val) => formatter.format(val);
3714
- }),
3715
- relativetime: cf((lng, opt) => {
3716
- const formatter = new Intl.RelativeTimeFormat(lng, {
3717
- ...opt
3718
- });
3719
- return (val) => formatter.format(val, opt.range || "day");
3720
- }),
3721
- list: cf((lng, opt) => {
3722
- const formatter = new Intl.ListFormat(lng, {
3723
- ...opt
3724
- });
3725
- return (val) => formatter.format(val);
3726
- })
3727
- };
3728
- }
3729
- add(name, fc) {
3730
- this.formats[name.toLowerCase().trim()] = fc;
3731
- }
3732
- addCached(name, fc) {
3733
- this.formats[name.toLowerCase().trim()] = createCachedFormatter(fc);
3734
- }
3735
- format(value, format, lng, options = {}) {
3736
- if (!format)
3737
- return value;
3738
- if (value == null)
3739
- return value;
3740
- const formats = format.split(this.formatSeparator);
3741
- if (formats.length > 1 && formats[0].indexOf("(") > 1 && !formats[0].includes(")") && formats.find((f) => f.includes(")"))) {
3742
- const lastIndex = formats.findIndex((f) => f.includes(")"));
3743
- formats[0] = [formats[0], ...formats.splice(1, lastIndex)].join(this.formatSeparator);
3744
- }
3745
- const result = formats.reduce((mem, f) => {
3746
- const {
3747
- formatName,
3748
- formatOptions
3749
- } = parseFormatStr(f);
3750
- if (this.formats[formatName]) {
3751
- let formatted = mem;
3752
- try {
3753
- const valOptions = options?.formatParams?.[options.interpolationkey] || {};
3754
- const l = valOptions.locale || valOptions.lng || options.locale || options.lng || lng;
3755
- formatted = this.formats[formatName](mem, l, {
3756
- ...formatOptions,
3757
- ...options,
3758
- ...valOptions
3759
- });
3760
- } catch (error) {
3761
- this.logger.warn(error);
3762
- }
3763
- return formatted;
3764
- } else {
3765
- this.logger.warn(`there was no format function for ${formatName}`);
3766
- }
3767
- return mem;
3768
- }, value);
3769
- return result;
3770
- }
3771
- }
3772
- var removePending = (q, name) => {
3773
- if (q.pending[name] !== undefined) {
3774
- delete q.pending[name];
3775
- q.pendingCount--;
3776
- }
3777
- };
3778
-
3779
- class Connector extends EventEmitter {
3780
- constructor(backend, store, services, options = {}) {
3781
- super();
3782
- this.backend = backend;
3783
- this.store = store;
3784
- this.services = services;
3785
- this.languageUtils = services.languageUtils;
3786
- this.options = options;
3787
- this.logger = baseLogger.create("backendConnector");
3788
- this.waitingReads = [];
3789
- this.maxParallelReads = options.maxParallelReads || 10;
3790
- this.readingCalls = 0;
3791
- this.maxRetries = options.maxRetries >= 0 ? options.maxRetries : 5;
3792
- this.retryTimeout = options.retryTimeout >= 1 ? options.retryTimeout : 350;
3793
- this.state = {};
3794
- this.queue = [];
3795
- this.backend?.init?.(services, options.backend, options);
3796
- }
3797
- queueLoad(languages, namespaces, options, callback) {
3798
- const toLoad = {};
3799
- const pending = {};
3800
- const toLoadLanguages = {};
3801
- const toLoadNamespaces = {};
3802
- languages.forEach((lng) => {
3803
- let hasAllNamespaces = true;
3804
- namespaces.forEach((ns) => {
3805
- const name = `${lng}|${ns}`;
3806
- if (!options.reload && this.store.hasResourceBundle(lng, ns)) {
3807
- this.state[name] = 2;
3808
- } else if (this.state[name] < 0)
3809
- ;
3810
- else if (this.state[name] === 1) {
3811
- if (pending[name] === undefined)
3812
- pending[name] = true;
3813
- } else {
3814
- this.state[name] = 1;
3815
- hasAllNamespaces = false;
3816
- if (pending[name] === undefined)
3817
- pending[name] = true;
3818
- if (toLoad[name] === undefined)
3819
- toLoad[name] = true;
3820
- if (toLoadNamespaces[ns] === undefined)
3821
- toLoadNamespaces[ns] = true;
3822
- }
3823
- });
3824
- if (!hasAllNamespaces)
3825
- toLoadLanguages[lng] = true;
3826
- });
3827
- if (Object.keys(toLoad).length || Object.keys(pending).length) {
3828
- this.queue.push({
3829
- pending,
3830
- pendingCount: Object.keys(pending).length,
3831
- loaded: {},
3832
- errors: [],
3833
- callback
3834
- });
3835
- }
3836
- return {
3837
- toLoad: Object.keys(toLoad),
3838
- pending: Object.keys(pending),
3839
- toLoadLanguages: Object.keys(toLoadLanguages),
3840
- toLoadNamespaces: Object.keys(toLoadNamespaces)
3841
- };
3842
- }
3843
- loaded(name, err, data) {
3844
- const s = name.split("|");
3845
- const lng = s[0];
3846
- const ns = s[1];
3847
- if (err)
3848
- this.emit("failedLoading", lng, ns, err);
3849
- if (!err && data) {
3850
- this.store.addResourceBundle(lng, ns, data, undefined, undefined, {
3851
- skipCopy: true
3852
- });
3853
- }
3854
- this.state[name] = err ? -1 : 2;
3855
- if (err && data)
3856
- this.state[name] = 0;
3857
- const loaded = {};
3858
- this.queue.forEach((q) => {
3859
- pushPath(q.loaded, [lng], ns);
3860
- removePending(q, name);
3861
- if (err)
3862
- q.errors.push(err);
3863
- if (q.pendingCount === 0 && !q.done) {
3864
- Object.keys(q.loaded).forEach((l) => {
3865
- if (!loaded[l])
3866
- loaded[l] = {};
3867
- const loadedKeys = q.loaded[l];
3868
- if (loadedKeys.length) {
3869
- loadedKeys.forEach((n) => {
3870
- if (loaded[l][n] === undefined)
3871
- loaded[l][n] = true;
3872
- });
3873
- }
3874
- });
3875
- q.done = true;
3876
- if (q.errors.length) {
3877
- q.callback(q.errors);
3878
- } else {
3879
- q.callback();
3880
- }
3881
- }
3882
- });
3883
- this.emit("loaded", loaded);
3884
- this.queue = this.queue.filter((q) => !q.done);
3885
- }
3886
- read(lng, ns, fcName, tried = 0, wait = this.retryTimeout, callback) {
3887
- if (!lng.length)
3888
- return callback(null, {});
3889
- if (this.readingCalls >= this.maxParallelReads) {
3890
- this.waitingReads.push({
3891
- lng,
3892
- ns,
3893
- fcName,
3894
- tried,
3895
- wait,
3896
- callback
3897
- });
3898
- return;
3899
- }
3900
- this.readingCalls++;
3901
- const resolver = (err, data) => {
3902
- this.readingCalls--;
3903
- if (this.waitingReads.length > 0) {
3904
- const next = this.waitingReads.shift();
3905
- this.read(next.lng, next.ns, next.fcName, next.tried, next.wait, next.callback);
3906
- }
3907
- if (err && data && tried < this.maxRetries) {
3908
- setTimeout(() => {
3909
- this.read(lng, ns, fcName, tried + 1, wait * 2, callback);
3910
- }, wait);
3911
- return;
3912
- }
3913
- callback(err, data);
3914
- };
3915
- const fc = this.backend[fcName].bind(this.backend);
3916
- if (fc.length === 2) {
3917
- try {
3918
- const r = fc(lng, ns);
3919
- if (r && typeof r.then === "function") {
3920
- r.then((data) => resolver(null, data)).catch(resolver);
3921
- } else {
3922
- resolver(null, r);
3923
- }
3924
- } catch (err) {
3925
- resolver(err);
3926
- }
3927
- return;
3928
- }
3929
- return fc(lng, ns, resolver);
3930
- }
3931
- prepareLoading(languages, namespaces, options = {}, callback) {
3932
- if (!this.backend) {
3933
- this.logger.warn("No backend was added via i18next.use. Will not load resources.");
3934
- return callback && callback();
3935
- }
3936
- if (isString(languages))
3937
- languages = this.languageUtils.toResolveHierarchy(languages);
3938
- if (isString(namespaces))
3939
- namespaces = [namespaces];
3940
- const toLoad = this.queueLoad(languages, namespaces, options, callback);
3941
- if (!toLoad.toLoad.length) {
3942
- if (!toLoad.pending.length)
3943
- callback();
3944
- return null;
3945
- }
3946
- toLoad.toLoad.forEach((name) => {
3947
- this.loadOne(name);
3948
- });
3949
- }
3950
- load(languages, namespaces, callback) {
3951
- this.prepareLoading(languages, namespaces, {}, callback);
3952
- }
3953
- reload(languages, namespaces, callback) {
3954
- this.prepareLoading(languages, namespaces, {
3955
- reload: true
3956
- }, callback);
3957
- }
3958
- loadOne(name, prefix = "") {
3959
- const s = name.split("|");
3960
- const lng = s[0];
3961
- const ns = s[1];
3962
- this.read(lng, ns, "read", undefined, undefined, (err, data) => {
3963
- if (err)
3964
- this.logger.warn(`${prefix}loading namespace ${ns} for language ${lng} failed`, err);
3965
- if (!err && data)
3966
- this.logger.log(`${prefix}loaded namespace ${ns} for language ${lng}`, data);
3967
- this.loaded(name, err, data);
3968
- });
3969
- }
3970
- saveMissing(languages, namespace, key, fallbackValue, isUpdate, options = {}, clb = () => {}) {
3971
- if (this.services?.utils?.hasLoadedNamespace && !this.services?.utils?.hasLoadedNamespace(namespace)) {
3972
- this.logger.warn(`did not save key "${key}" as the namespace "${namespace}" was not yet loaded`, "This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!");
3973
- return;
3974
- }
3975
- if (key === undefined || key === null || key === "")
3976
- return;
3977
- if (this.backend?.create) {
3978
- const opts = {
3979
- ...options,
3980
- isUpdate
3981
- };
3982
- const fc = this.backend.create.bind(this.backend);
3983
- if (fc.length < 6) {
3984
- try {
3985
- let r;
3986
- if (fc.length === 5) {
3987
- r = fc(languages, namespace, key, fallbackValue, opts);
3988
- } else {
3989
- r = fc(languages, namespace, key, fallbackValue);
3990
- }
3991
- if (r && typeof r.then === "function") {
3992
- r.then((data) => clb(null, data)).catch(clb);
3993
- } else {
3994
- clb(null, r);
3995
- }
3996
- } catch (err) {
3997
- clb(err);
3998
- }
3999
- } else {
4000
- fc(languages, namespace, key, fallbackValue, clb, opts);
4001
- }
4002
- }
4003
- if (!languages || !languages[0])
4004
- return;
4005
- this.store.addResource(languages[0], namespace, key, fallbackValue);
4006
- }
4007
- }
4008
- var get = () => ({
4009
- debug: false,
4010
- initAsync: true,
4011
- ns: ["translation"],
4012
- defaultNS: ["translation"],
4013
- fallbackLng: ["dev"],
4014
- fallbackNS: false,
4015
- supportedLngs: false,
4016
- nonExplicitSupportedLngs: false,
4017
- load: "all",
4018
- preload: false,
4019
- keySeparator: ".",
4020
- nsSeparator: ":",
4021
- pluralSeparator: "_",
4022
- contextSeparator: "_",
4023
- partialBundledLanguages: false,
4024
- saveMissing: false,
4025
- updateMissing: false,
4026
- saveMissingTo: "fallback",
4027
- saveMissingPlurals: true,
4028
- missingKeyHandler: false,
4029
- missingInterpolationHandler: false,
4030
- postProcess: false,
4031
- postProcessPassResolved: false,
4032
- returnNull: false,
4033
- returnEmptyString: true,
4034
- returnObjects: false,
4035
- joinArrays: false,
4036
- returnedObjectHandler: false,
4037
- parseMissingKeyHandler: false,
4038
- appendNamespaceToMissingKey: false,
4039
- appendNamespaceToCIMode: false,
4040
- overloadTranslationOptionHandler: (args) => {
4041
- let ret = {};
4042
- if (typeof args[1] === "object")
4043
- ret = args[1];
4044
- if (isString(args[1]))
4045
- ret.defaultValue = args[1];
4046
- if (isString(args[2]))
4047
- ret.tDescription = args[2];
4048
- if (typeof args[2] === "object" || typeof args[3] === "object") {
4049
- const options = args[3] || args[2];
4050
- Object.keys(options).forEach((key) => {
4051
- ret[key] = options[key];
4052
- });
4053
- }
4054
- return ret;
4055
- },
4056
- interpolation: {
4057
- escapeValue: true,
4058
- prefix: "{{",
4059
- suffix: "}}",
4060
- formatSeparator: ",",
4061
- unescapePrefix: "-",
4062
- nestingPrefix: "$t(",
4063
- nestingSuffix: ")",
4064
- nestingOptionsSeparator: ",",
4065
- maxReplaces: 1000,
4066
- skipOnVariables: true
4067
- },
4068
- cacheInBuiltFormats: true
4069
- });
4070
- var transformOptions = (options) => {
4071
- if (isString(options.ns))
4072
- options.ns = [options.ns];
4073
- if (isString(options.fallbackLng))
4074
- options.fallbackLng = [options.fallbackLng];
4075
- if (isString(options.fallbackNS))
4076
- options.fallbackNS = [options.fallbackNS];
4077
- if (options.supportedLngs && !options.supportedLngs.includes("cimode")) {
4078
- options.supportedLngs = options.supportedLngs.concat(["cimode"]);
4079
- }
4080
- return options;
4081
- };
4082
- var noop = () => {};
4083
- var bindMemberFunctions = (inst) => {
4084
- const mems = Object.getOwnPropertyNames(Object.getPrototypeOf(inst));
4085
- mems.forEach((mem) => {
4086
- if (typeof inst[mem] === "function") {
4087
- inst[mem] = inst[mem].bind(inst);
4088
- }
4089
- });
4090
- };
4091
-
4092
- class I18n extends EventEmitter {
4093
- constructor(options = {}, callback) {
4094
- super();
4095
- this.options = transformOptions(options);
4096
- this.services = {};
4097
- this.logger = baseLogger;
4098
- this.modules = {
4099
- external: []
4100
- };
4101
- bindMemberFunctions(this);
4102
- if (callback && !this.isInitialized && !options.isClone) {
4103
- if (!this.options.initAsync) {
4104
- this.init(options, callback);
4105
- return this;
4106
- }
4107
- setTimeout(() => {
4108
- this.init(options, callback);
4109
- }, 0);
4110
- }
4111
- }
4112
- init(options = {}, callback) {
4113
- this.isInitializing = true;
4114
- if (typeof options === "function") {
4115
- callback = options;
4116
- options = {};
4117
- }
4118
- if (options.defaultNS == null && options.ns) {
4119
- if (isString(options.ns)) {
4120
- options.defaultNS = options.ns;
4121
- } else if (!options.ns.includes("translation")) {
4122
- options.defaultNS = options.ns[0];
4123
- }
4124
- }
4125
- const defOpts = get();
4126
- this.options = {
4127
- ...defOpts,
4128
- ...this.options,
4129
- ...transformOptions(options)
4130
- };
4131
- this.options.interpolation = {
4132
- ...defOpts.interpolation,
4133
- ...this.options.interpolation
4134
- };
4135
- if (options.keySeparator !== undefined) {
4136
- this.options.userDefinedKeySeparator = options.keySeparator;
4137
- }
4138
- if (options.nsSeparator !== undefined) {
4139
- this.options.userDefinedNsSeparator = options.nsSeparator;
4140
- }
4141
- if (typeof this.options.overloadTranslationOptionHandler !== "function") {
4142
- this.options.overloadTranslationOptionHandler = defOpts.overloadTranslationOptionHandler;
4143
- }
4144
- const createClassOnDemand = (ClassOrObject) => {
4145
- if (!ClassOrObject)
4146
- return null;
4147
- if (typeof ClassOrObject === "function")
4148
- return new ClassOrObject;
4149
- return ClassOrObject;
4150
- };
4151
- if (!this.options.isClone) {
4152
- if (this.modules.logger) {
4153
- baseLogger.init(createClassOnDemand(this.modules.logger), this.options);
4154
- } else {
4155
- baseLogger.init(null, this.options);
4156
- }
4157
- let formatter;
4158
- if (this.modules.formatter) {
4159
- formatter = this.modules.formatter;
4160
- } else {
4161
- formatter = Formatter;
4162
- }
4163
- const lu = new LanguageUtil(this.options);
4164
- this.store = new ResourceStore(this.options.resources, this.options);
4165
- const s = this.services;
4166
- s.logger = baseLogger;
4167
- s.resourceStore = this.store;
4168
- s.languageUtils = lu;
4169
- s.pluralResolver = new PluralResolver(lu, {
4170
- prepend: this.options.pluralSeparator
4171
- });
4172
- if (formatter) {
4173
- s.formatter = createClassOnDemand(formatter);
4174
- if (s.formatter.init)
4175
- s.formatter.init(s, this.options);
4176
- this.options.interpolation.format = s.formatter.format.bind(s.formatter);
4177
- }
4178
- s.interpolator = new Interpolator(this.options);
4179
- s.utils = {
4180
- hasLoadedNamespace: this.hasLoadedNamespace.bind(this)
4181
- };
4182
- s.backendConnector = new Connector(createClassOnDemand(this.modules.backend), s.resourceStore, s, this.options);
4183
- s.backendConnector.on("*", (event, ...args) => {
4184
- this.emit(event, ...args);
4185
- });
4186
- if (this.modules.languageDetector) {
4187
- s.languageDetector = createClassOnDemand(this.modules.languageDetector);
4188
- if (s.languageDetector.init)
4189
- s.languageDetector.init(s, this.options.detection, this.options);
4190
- }
4191
- if (this.modules.i18nFormat) {
4192
- s.i18nFormat = createClassOnDemand(this.modules.i18nFormat);
4193
- if (s.i18nFormat.init)
4194
- s.i18nFormat.init(this);
4195
- }
4196
- this.translator = new Translator(this.services, this.options);
4197
- this.translator.on("*", (event, ...args) => {
4198
- this.emit(event, ...args);
4199
- });
4200
- this.modules.external.forEach((m) => {
4201
- if (m.init)
4202
- m.init(this);
4203
- });
4204
- }
4205
- this.format = this.options.interpolation.format;
4206
- if (!callback)
4207
- callback = noop;
4208
- if (this.options.fallbackLng && !this.services.languageDetector && !this.options.lng) {
4209
- const codes = this.services.languageUtils.getFallbackCodes(this.options.fallbackLng);
4210
- if (codes.length > 0 && codes[0] !== "dev")
4211
- this.options.lng = codes[0];
4212
- }
4213
- if (!this.services.languageDetector && !this.options.lng) {
4214
- this.logger.warn("init: no languageDetector is used and no lng is defined");
4215
- }
4216
- const storeApi = ["getResource", "hasResourceBundle", "getResourceBundle", "getDataByLanguage"];
4217
- storeApi.forEach((fcName) => {
4218
- this[fcName] = (...args) => this.store[fcName](...args);
4219
- });
4220
- const storeApiChained = ["addResource", "addResources", "addResourceBundle", "removeResourceBundle"];
4221
- storeApiChained.forEach((fcName) => {
4222
- this[fcName] = (...args) => {
4223
- this.store[fcName](...args);
4224
- return this;
4225
- };
4226
- });
4227
- const deferred = defer();
4228
- const load = () => {
4229
- const finish = (err, t) => {
4230
- this.isInitializing = false;
4231
- if (this.isInitialized && !this.initializedStoreOnce)
4232
- this.logger.warn("init: i18next is already initialized. You should call init just once!");
4233
- this.isInitialized = true;
4234
- if (!this.options.isClone)
4235
- this.logger.log("initialized", this.options);
4236
- this.emit("initialized", this.options);
4237
- deferred.resolve(t);
4238
- callback(err, t);
4239
- };
4240
- if (this.languages && !this.isInitialized)
4241
- return finish(null, this.t.bind(this));
4242
- this.changeLanguage(this.options.lng, finish);
4243
- };
4244
- if (this.options.resources || !this.options.initAsync) {
4245
- load();
4246
- } else {
4247
- setTimeout(load, 0);
4248
- }
4249
- return deferred;
4250
- }
4251
- loadResources(language, callback = noop) {
4252
- let usedCallback = callback;
4253
- const usedLng = isString(language) ? language : this.language;
4254
- if (typeof language === "function")
4255
- usedCallback = language;
4256
- if (!this.options.resources || this.options.partialBundledLanguages) {
4257
- if (usedLng?.toLowerCase() === "cimode" && (!this.options.preload || this.options.preload.length === 0))
4258
- return usedCallback();
4259
- const toLoad = [];
4260
- const append = (lng) => {
4261
- if (!lng)
4262
- return;
4263
- if (lng === "cimode")
4264
- return;
4265
- const lngs = this.services.languageUtils.toResolveHierarchy(lng);
4266
- lngs.forEach((l) => {
4267
- if (l === "cimode")
4268
- return;
4269
- if (!toLoad.includes(l))
4270
- toLoad.push(l);
4271
- });
4272
- };
4273
- if (!usedLng) {
4274
- const fallbacks = this.services.languageUtils.getFallbackCodes(this.options.fallbackLng);
4275
- fallbacks.forEach((l) => append(l));
4276
- } else {
4277
- append(usedLng);
4278
- }
4279
- this.options.preload?.forEach?.((l) => append(l));
4280
- this.services.backendConnector.load(toLoad, this.options.ns, (e) => {
4281
- if (!e && !this.resolvedLanguage && this.language)
4282
- this.setResolvedLanguage(this.language);
4283
- usedCallback(e);
4284
- });
4285
- } else {
4286
- usedCallback(null);
4287
- }
4288
- }
4289
- reloadResources(lngs, ns, callback) {
4290
- const deferred = defer();
4291
- if (typeof lngs === "function") {
4292
- callback = lngs;
4293
- lngs = undefined;
4294
- }
4295
- if (typeof ns === "function") {
4296
- callback = ns;
4297
- ns = undefined;
4298
- }
4299
- if (!lngs)
4300
- lngs = this.languages;
4301
- if (!ns)
4302
- ns = this.options.ns;
4303
- if (!callback)
4304
- callback = noop;
4305
- this.services.backendConnector.reload(lngs, ns, (err) => {
4306
- deferred.resolve();
4307
- callback(err);
4308
- });
4309
- return deferred;
4310
- }
4311
- use(module) {
4312
- if (!module)
4313
- throw new Error("You are passing an undefined module! Please check the object you are passing to i18next.use()");
4314
- if (!module.type)
4315
- throw new Error("You are passing a wrong module! Please check the object you are passing to i18next.use()");
4316
- if (module.type === "backend") {
4317
- this.modules.backend = module;
4318
- }
4319
- if (module.type === "logger" || module.log && module.warn && module.error) {
4320
- this.modules.logger = module;
4321
- }
4322
- if (module.type === "languageDetector") {
4323
- this.modules.languageDetector = module;
4324
- }
4325
- if (module.type === "i18nFormat") {
4326
- this.modules.i18nFormat = module;
4327
- }
4328
- if (module.type === "postProcessor") {
4329
- postProcessor.addPostProcessor(module);
4330
- }
4331
- if (module.type === "formatter") {
4332
- this.modules.formatter = module;
4333
- }
4334
- if (module.type === "3rdParty") {
4335
- this.modules.external.push(module);
4336
- }
4337
- return this;
4338
- }
4339
- setResolvedLanguage(l) {
4340
- if (!l || !this.languages)
4341
- return;
4342
- if (["cimode", "dev"].includes(l))
4343
- return;
4344
- for (let li = 0;li < this.languages.length; li++) {
4345
- const lngInLngs = this.languages[li];
4346
- if (["cimode", "dev"].includes(lngInLngs))
4347
- continue;
4348
- if (this.store.hasLanguageSomeTranslations(lngInLngs)) {
4349
- this.resolvedLanguage = lngInLngs;
4350
- break;
4351
- }
4352
- }
4353
- if (!this.resolvedLanguage && !this.languages.includes(l) && this.store.hasLanguageSomeTranslations(l)) {
4354
- this.resolvedLanguage = l;
4355
- this.languages.unshift(l);
4356
- }
4357
- }
4358
- changeLanguage(lng, callback) {
4359
- this.isLanguageChangingTo = lng;
4360
- const deferred = defer();
4361
- this.emit("languageChanging", lng);
4362
- const setLngProps = (l) => {
4363
- this.language = l;
4364
- this.languages = this.services.languageUtils.toResolveHierarchy(l);
4365
- this.resolvedLanguage = undefined;
4366
- this.setResolvedLanguage(l);
4367
- };
4368
- const done = (err, l) => {
4369
- if (l) {
4370
- if (this.isLanguageChangingTo === lng) {
4371
- setLngProps(l);
4372
- this.translator.changeLanguage(l);
4373
- this.isLanguageChangingTo = undefined;
4374
- this.emit("languageChanged", l);
4375
- this.logger.log("languageChanged", l);
4376
- }
4377
- } else {
4378
- this.isLanguageChangingTo = undefined;
4379
- }
4380
- deferred.resolve((...args) => this.t(...args));
4381
- if (callback)
4382
- callback(err, (...args) => this.t(...args));
4383
- };
4384
- const setLng = (lngs) => {
4385
- if (!lng && !lngs && this.services.languageDetector)
4386
- lngs = [];
4387
- const fl = isString(lngs) ? lngs : lngs && lngs[0];
4388
- const l = this.store.hasLanguageSomeTranslations(fl) ? fl : this.services.languageUtils.getBestMatchFromCodes(isString(lngs) ? [lngs] : lngs);
4389
- if (l) {
4390
- if (!this.language) {
4391
- setLngProps(l);
4392
- }
4393
- if (!this.translator.language)
4394
- this.translator.changeLanguage(l);
4395
- this.services.languageDetector?.cacheUserLanguage?.(l);
4396
- }
4397
- this.loadResources(l, (err) => {
4398
- done(err, l);
4399
- });
4400
- };
4401
- if (!lng && this.services.languageDetector && !this.services.languageDetector.async) {
4402
- setLng(this.services.languageDetector.detect());
4403
- } else if (!lng && this.services.languageDetector && this.services.languageDetector.async) {
4404
- if (this.services.languageDetector.detect.length === 0) {
4405
- this.services.languageDetector.detect().then(setLng);
4406
- } else {
4407
- this.services.languageDetector.detect(setLng);
4408
- }
4409
- } else {
4410
- setLng(lng);
4411
- }
4412
- return deferred;
4413
- }
4414
- getFixedT(lng, ns, keyPrefix) {
4415
- const fixedT = (key, opts, ...rest) => {
4416
- let o;
4417
- if (typeof opts !== "object") {
4418
- o = this.options.overloadTranslationOptionHandler([key, opts].concat(rest));
4419
- } else {
4420
- o = {
4421
- ...opts
4422
- };
4423
- }
4424
- o.lng = o.lng || fixedT.lng;
4425
- o.lngs = o.lngs || fixedT.lngs;
4426
- o.ns = o.ns || fixedT.ns;
4427
- if (o.keyPrefix !== "")
4428
- o.keyPrefix = o.keyPrefix || keyPrefix || fixedT.keyPrefix;
4429
- const selectorOpts = {
4430
- ...this.options,
4431
- ...o
4432
- };
4433
- if (typeof o.keyPrefix === "function")
4434
- o.keyPrefix = keysFromSelector(o.keyPrefix, selectorOpts);
4435
- const keySeparator = this.options.keySeparator || ".";
4436
- let resultKey;
4437
- if (o.keyPrefix && Array.isArray(key)) {
4438
- resultKey = key.map((k) => {
4439
- if (typeof k === "function")
4440
- k = keysFromSelector(k, selectorOpts);
4441
- return `${o.keyPrefix}${keySeparator}${k}`;
4442
- });
4443
- } else {
4444
- if (typeof key === "function")
4445
- key = keysFromSelector(key, selectorOpts);
4446
- resultKey = o.keyPrefix ? `${o.keyPrefix}${keySeparator}${key}` : key;
4447
- }
4448
- return this.t(resultKey, o);
4449
- };
4450
- if (isString(lng)) {
4451
- fixedT.lng = lng;
4452
- } else {
4453
- fixedT.lngs = lng;
4454
- }
4455
- fixedT.ns = ns;
4456
- fixedT.keyPrefix = keyPrefix;
4457
- return fixedT;
4458
- }
4459
- t(...args) {
4460
- return this.translator?.translate(...args);
4461
- }
4462
- exists(...args) {
4463
- return this.translator?.exists(...args);
4464
- }
4465
- setDefaultNamespace(ns) {
4466
- this.options.defaultNS = ns;
4467
- }
4468
- hasLoadedNamespace(ns, options = {}) {
4469
- if (!this.isInitialized) {
4470
- this.logger.warn("hasLoadedNamespace: i18next was not initialized", this.languages);
4471
- return false;
4472
- }
4473
- if (!this.languages || !this.languages.length) {
4474
- this.logger.warn("hasLoadedNamespace: i18n.languages were undefined or empty", this.languages);
4475
- return false;
4476
- }
4477
- const lng = options.lng || this.resolvedLanguage || this.languages[0];
4478
- const fallbackLng = this.options ? this.options.fallbackLng : false;
4479
- const lastLng = this.languages[this.languages.length - 1];
4480
- if (lng.toLowerCase() === "cimode")
4481
- return true;
4482
- const loadNotPending = (l, n) => {
4483
- const loadState = this.services.backendConnector.state[`${l}|${n}`];
4484
- return loadState === -1 || loadState === 0 || loadState === 2;
4485
- };
4486
- if (options.precheck) {
4487
- const preResult = options.precheck(this, loadNotPending);
4488
- if (preResult !== undefined)
4489
- return preResult;
4490
- }
4491
- if (this.hasResourceBundle(lng, ns))
4492
- return true;
4493
- if (!this.services.backendConnector.backend || this.options.resources && !this.options.partialBundledLanguages)
4494
- return true;
4495
- if (loadNotPending(lng, ns) && (!fallbackLng || loadNotPending(lastLng, ns)))
4496
- return true;
4497
- return false;
4498
- }
4499
- loadNamespaces(ns, callback) {
4500
- const deferred = defer();
4501
- if (!this.options.ns) {
4502
- if (callback)
4503
- callback();
4504
- return Promise.resolve();
4505
- }
4506
- if (isString(ns))
4507
- ns = [ns];
4508
- ns.forEach((n) => {
4509
- if (!this.options.ns.includes(n))
4510
- this.options.ns.push(n);
4511
- });
4512
- this.loadResources((err) => {
4513
- deferred.resolve();
4514
- if (callback)
4515
- callback(err);
4516
- });
4517
- return deferred;
4518
- }
4519
- loadLanguages(lngs, callback) {
4520
- const deferred = defer();
4521
- if (isString(lngs))
4522
- lngs = [lngs];
4523
- const preloaded = this.options.preload || [];
4524
- const newLngs = lngs.filter((lng) => !preloaded.includes(lng) && this.services.languageUtils.isSupportedCode(lng));
4525
- if (!newLngs.length) {
4526
- if (callback)
4527
- callback();
4528
- return Promise.resolve();
4529
- }
4530
- this.options.preload = preloaded.concat(newLngs);
4531
- this.loadResources((err) => {
4532
- deferred.resolve();
4533
- if (callback)
4534
- callback(err);
4535
- });
4536
- return deferred;
4537
- }
4538
- dir(lng) {
4539
- if (!lng)
4540
- lng = this.resolvedLanguage || (this.languages?.length > 0 ? this.languages[0] : this.language);
4541
- if (!lng)
4542
- return "rtl";
4543
- try {
4544
- const l = new Intl.Locale(lng);
4545
- if (l && l.getTextInfo) {
4546
- const ti = l.getTextInfo();
4547
- if (ti && ti.direction)
4548
- return ti.direction;
4549
- }
4550
- } catch (e) {}
4551
- const rtlLngs = ["ar", "shu", "sqr", "ssh", "xaa", "yhd", "yud", "aao", "abh", "abv", "acm", "acq", "acw", "acx", "acy", "adf", "ads", "aeb", "aec", "afb", "ajp", "apc", "apd", "arb", "arq", "ars", "ary", "arz", "auz", "avl", "ayh", "ayl", "ayn", "ayp", "bbz", "pga", "he", "iw", "ps", "pbt", "pbu", "pst", "prp", "prd", "ug", "ur", "ydd", "yds", "yih", "ji", "yi", "hbo", "men", "xmn", "fa", "jpr", "peo", "pes", "prs", "dv", "sam", "ckb"];
4552
- const languageUtils = this.services?.languageUtils || new LanguageUtil(get());
4553
- if (lng.toLowerCase().indexOf("-latn") > 1)
4554
- return "ltr";
4555
- return rtlLngs.includes(languageUtils.getLanguagePartFromCode(lng)) || lng.toLowerCase().indexOf("-arab") > 1 ? "rtl" : "ltr";
4556
- }
4557
- static createInstance(options = {}, callback) {
4558
- const instance = new I18n(options, callback);
4559
- instance.createInstance = I18n.createInstance;
4560
- return instance;
4561
- }
4562
- cloneInstance(options = {}, callback = noop) {
4563
- const forkResourceStore = options.forkResourceStore;
4564
- if (forkResourceStore)
4565
- delete options.forkResourceStore;
4566
- const mergedOptions = {
4567
- ...this.options,
4568
- ...options,
4569
- ...{
4570
- isClone: true
4571
- }
4572
- };
4573
- const clone = new I18n(mergedOptions);
4574
- if (options.debug !== undefined || options.prefix !== undefined) {
4575
- clone.logger = clone.logger.clone(options);
4576
- }
4577
- const membersToCopy = ["store", "services", "language"];
4578
- membersToCopy.forEach((m) => {
4579
- clone[m] = this[m];
4580
- });
4581
- clone.services = {
4582
- ...this.services
4583
- };
4584
- clone.services.utils = {
4585
- hasLoadedNamespace: clone.hasLoadedNamespace.bind(clone)
4586
- };
4587
- if (forkResourceStore) {
4588
- const clonedData = Object.keys(this.store.data).reduce((prev, l) => {
4589
- prev[l] = {
4590
- ...this.store.data[l]
4591
- };
4592
- prev[l] = Object.keys(prev[l]).reduce((acc, n) => {
4593
- acc[n] = {
4594
- ...prev[l][n]
4595
- };
4596
- return acc;
4597
- }, prev[l]);
4598
- return prev;
4599
- }, {});
4600
- clone.store = new ResourceStore(clonedData, mergedOptions);
4601
- clone.services.resourceStore = clone.store;
4602
- }
4603
- if (options.interpolation) {
4604
- const defOpts = get();
4605
- const mergedInterpolation = {
4606
- ...defOpts.interpolation,
4607
- ...this.options.interpolation,
4608
- ...options.interpolation
4609
- };
4610
- const mergedForInterpolator = {
4611
- ...mergedOptions,
4612
- interpolation: mergedInterpolation
4613
- };
4614
- clone.services.interpolator = new Interpolator(mergedForInterpolator);
4615
- }
4616
- clone.translator = new Translator(clone.services, mergedOptions);
4617
- clone.translator.on("*", (event, ...args) => {
4618
- clone.emit(event, ...args);
4619
- });
4620
- clone.init(mergedOptions, callback);
4621
- clone.translator.options = mergedOptions;
4622
- clone.translator.backendConnector.services.utils = {
4623
- hasLoadedNamespace: clone.hasLoadedNamespace.bind(clone)
4624
- };
4625
- return clone;
4626
- }
4627
- toJSON() {
4628
- return {
4629
- options: this.options,
4630
- store: this.store,
4631
- language: this.language,
4632
- languages: this.languages,
4633
- resolvedLanguage: this.resolvedLanguage
4634
- };
4635
- }
4636
- }
4637
- var instance = I18n.createInstance();
4638
- var createInstance = instance.createInstance;
4639
- var dir = instance.dir;
4640
- var init = instance.init;
4641
- var loadResources = instance.loadResources;
4642
- var reloadResources = instance.reloadResources;
4643
- var use = instance.use;
4644
- var changeLanguage = instance.changeLanguage;
4645
- var getFixedT = instance.getFixedT;
4646
- var t = instance.t;
4647
- var exists = instance.exists;
4648
- var setDefaultNamespace = instance.setDefaultNamespace;
4649
- var hasLoadedNamespace = instance.hasLoadedNamespace;
4650
- var loadNamespaces = instance.loadNamespaces;
4651
- var loadLanguages = instance.loadLanguages;
4652
-
4653
- // ../../node_modules/.bun/react-i18next@17.0.2+fae4c6524ff71ef1/node_modules/react-i18next/dist/es/utils.js
4654
- var warn = (i18n, code, msg, rest) => {
4655
- const args = [msg, {
4656
- code,
4657
- ...rest || {}
4658
- }];
4659
- if (i18n?.services?.logger?.forward) {
4660
- return i18n.services.logger.forward(args, "warn", "react-i18next::", true);
4661
- }
4662
- if (isString2(args[0]))
4663
- args[0] = `react-i18next:: ${args[0]}`;
4664
- if (i18n?.services?.logger?.warn) {
4665
- i18n.services.logger.warn(...args);
4666
- } else if (console?.warn) {
4667
- console.warn(...args);
4668
- }
4669
- };
4670
- var alreadyWarned = {};
4671
- var warnOnce = (i18n, code, msg, rest) => {
4672
- if (isString2(msg) && alreadyWarned[msg])
4673
- return;
4674
- if (isString2(msg))
4675
- alreadyWarned[msg] = new Date;
4676
- warn(i18n, code, msg, rest);
4677
- };
4678
- var loadedClb = (i18n, cb) => () => {
4679
- if (i18n.isInitialized) {
4680
- cb();
4681
- } else {
4682
- const initialized = () => {
4683
- setTimeout(() => {
4684
- i18n.off("initialized", initialized);
4685
- }, 0);
4686
- cb();
4687
- };
4688
- i18n.on("initialized", initialized);
4689
- }
4690
- };
4691
- var loadNamespaces2 = (i18n, ns, cb) => {
4692
- i18n.loadNamespaces(ns, loadedClb(i18n, cb));
4693
- };
4694
- var loadLanguages2 = (i18n, lng, ns, cb) => {
4695
- if (isString2(ns))
4696
- ns = [ns];
4697
- if (i18n.options.preload && i18n.options.preload.indexOf(lng) > -1)
4698
- return loadNamespaces2(i18n, ns, cb);
4699
- ns.forEach((n) => {
4700
- if (i18n.options.ns.indexOf(n) < 0)
4701
- i18n.options.ns.push(n);
4702
- });
4703
- i18n.loadLanguages(lng, loadedClb(i18n, cb));
4704
- };
4705
- var hasLoadedNamespace2 = (ns, i18n, options = {}) => {
4706
- if (!i18n.languages || !i18n.languages.length) {
4707
- warnOnce(i18n, "NO_LANGUAGES", "i18n.languages were undefined or empty", {
4708
- languages: i18n.languages
4709
- });
4710
- return true;
4711
- }
4712
- return i18n.hasLoadedNamespace(ns, {
4713
- lng: options.lng,
4714
- precheck: (i18nInstance, loadNotPending) => {
4715
- if (options.bindI18n && options.bindI18n.indexOf("languageChanging") > -1 && i18nInstance.services.backendConnector.backend && i18nInstance.isLanguageChangingTo && !loadNotPending(i18nInstance.isLanguageChangingTo, ns))
4716
- return false;
4717
- }
4718
- });
4719
- };
4720
- var isString2 = (obj) => typeof obj === "string";
4721
- var isObject = (obj) => typeof obj === "object" && obj !== null;
4722
-
4723
- // ../../node_modules/.bun/react-i18next@17.0.2+fae4c6524ff71ef1/node_modules/react-i18next/dist/es/unescape.js
4724
- var matchHtmlEntity = /&(?:amp|#38|lt|#60|gt|#62|apos|#39|quot|#34|nbsp|#160|copy|#169|reg|#174|hellip|#8230|#x2F|#47);/g;
4725
- var htmlEntities = {
4726
- "&amp;": "&",
4727
- "&#38;": "&",
4728
- "&lt;": "<",
4729
- "&#60;": "<",
4730
- "&gt;": ">",
4731
- "&#62;": ">",
4732
- "&apos;": "'",
4733
- "&#39;": "'",
4734
- "&quot;": '"',
4735
- "&#34;": '"',
4736
- "&nbsp;": " ",
4737
- "&#160;": " ",
4738
- "&copy;": "\xA9",
4739
- "&#169;": "\xA9",
4740
- "&reg;": "\xAE",
4741
- "&#174;": "\xAE",
4742
- "&hellip;": "\u2026",
4743
- "&#8230;": "\u2026",
4744
- "&#x2F;": "/",
4745
- "&#47;": "/"
4746
- };
4747
- var unescapeHtmlEntity = (m) => htmlEntities[m];
4748
- var unescape = (text) => text.replace(matchHtmlEntity, unescapeHtmlEntity);
4749
-
4750
- // ../../node_modules/.bun/react-i18next@17.0.2+fae4c6524ff71ef1/node_modules/react-i18next/dist/es/defaults.js
4751
- var defaultOptions = {
4752
- bindI18n: "languageChanged",
4753
- bindI18nStore: "",
4754
- transEmptyNodeValue: "",
4755
- transSupportBasicHtmlNodes: true,
4756
- transWrapTextNodes: "",
4757
- transKeepBasicHtmlNodesFor: ["br", "strong", "i", "p"],
4758
- useSuspense: true,
4759
- unescape,
4760
- transDefaultProps: undefined
4761
- };
4762
- var setDefaults = (options = {}) => {
4763
- defaultOptions = {
4764
- ...defaultOptions,
4765
- ...options
4766
- };
4767
- };
4768
- var getDefaults = () => defaultOptions;
4769
-
4770
- // ../../node_modules/.bun/react-i18next@17.0.2+fae4c6524ff71ef1/node_modules/react-i18next/dist/es/i18nInstance.js
4771
- var i18nInstance;
4772
- var setI18n = (instance2) => {
4773
- i18nInstance = instance2;
4774
- };
4775
- var getI18n = () => i18nInstance;
4776
-
4777
- // ../../node_modules/.bun/react-i18next@17.0.2+fae4c6524ff71ef1/node_modules/react-i18next/dist/es/context.js
4778
- var import_react12 = __toESM(require_react(), 1);
4779
-
4780
- // ../../node_modules/.bun/react-i18next@17.0.2+fae4c6524ff71ef1/node_modules/react-i18next/dist/es/initReactI18next.js
4781
- var initReactI18next = {
4782
- type: "3rdParty",
4783
- init(instance2) {
4784
- setDefaults(instance2.options.react);
4785
- setI18n(instance2);
4786
- }
4787
- };
4788
-
4789
- // ../../node_modules/.bun/react-i18next@17.0.2+fae4c6524ff71ef1/node_modules/react-i18next/dist/es/context.js
4790
- var I18nContext = import_react12.createContext();
4791
-
4792
- class ReportNamespaces {
4793
- constructor() {
4794
- this.usedNamespaces = {};
4795
- }
4796
- addUsedNamespaces(namespaces) {
4797
- namespaces.forEach((ns) => {
4798
- if (!this.usedNamespaces[ns])
4799
- this.usedNamespaces[ns] = true;
4800
- });
4801
- }
4802
- getUsedNamespaces() {
4803
- return Object.keys(this.usedNamespaces);
4804
- }
4805
- }
4806
-
4807
- // ../../node_modules/.bun/react-i18next@17.0.2+fae4c6524ff71ef1/node_modules/react-i18next/dist/es/useTranslation.js
4808
- var import_react13 = __toESM(require_react(), 1);
4809
- var import_shim = __toESM(require_shim(), 1);
4810
- var notReadyT = (k, optsOrDefaultValue) => {
4811
- if (isString2(optsOrDefaultValue))
4812
- return optsOrDefaultValue;
4813
- if (isObject(optsOrDefaultValue) && isString2(optsOrDefaultValue.defaultValue))
4814
- return optsOrDefaultValue.defaultValue;
4815
- if (typeof k === "function")
4816
- return "";
4817
- if (Array.isArray(k)) {
4818
- const last = k[k.length - 1];
4819
- return typeof last === "function" ? "" : last;
4820
- }
4821
- return k;
4822
- };
4823
- var notReadySnapshot = {
4824
- t: notReadyT,
4825
- ready: false
4826
- };
4827
- var dummySubscribe = () => () => {};
4828
- var useTranslation = (ns, props = {}) => {
4829
- const {
4830
- i18n: i18nFromProps
4831
- } = props;
4832
- const {
4833
- i18n: i18nFromContext,
4834
- defaultNS: defaultNSFromContext
4835
- } = import_react13.useContext(I18nContext) || {};
4836
- const i18n = i18nFromProps || i18nFromContext || getI18n();
4837
- if (i18n && !i18n.reportNamespaces)
4838
- i18n.reportNamespaces = new ReportNamespaces;
4839
- if (!i18n) {
4840
- warnOnce(i18n, "NO_I18NEXT_INSTANCE", "useTranslation: You will need to pass in an i18next instance by using initReactI18next");
4841
- }
4842
- const i18nOptions = import_react13.useMemo(() => ({
4843
- ...getDefaults(),
4844
- ...i18n?.options?.react,
4845
- ...props
4846
- }), [i18n, props]);
4847
- const {
4848
- useSuspense,
4849
- keyPrefix
4850
- } = i18nOptions;
4851
- const nsOrContext = ns || defaultNSFromContext || i18n?.options?.defaultNS;
4852
- const unstableNamespaces = isString2(nsOrContext) ? [nsOrContext] : nsOrContext || ["translation"];
4853
- const namespaces = import_react13.useMemo(() => unstableNamespaces, unstableNamespaces);
4854
- i18n?.reportNamespaces?.addUsedNamespaces?.(namespaces);
4855
- const revisionRef = import_react13.useRef(0);
4856
- const subscribe = import_react13.useCallback((callback) => {
4857
- if (!i18n)
4858
- return dummySubscribe;
4859
- const {
4860
- bindI18n,
4861
- bindI18nStore
4862
- } = i18nOptions;
4863
- const wrappedCallback = () => {
4864
- revisionRef.current += 1;
4865
- callback();
4866
- };
4867
- if (bindI18n)
4868
- i18n.on(bindI18n, wrappedCallback);
4869
- if (bindI18nStore)
4870
- i18n.store.on(bindI18nStore, wrappedCallback);
4871
- return () => {
4872
- if (bindI18n)
4873
- bindI18n.split(" ").forEach((e) => i18n.off(e, wrappedCallback));
4874
- if (bindI18nStore)
4875
- bindI18nStore.split(" ").forEach((e) => i18n.store.off(e, wrappedCallback));
4876
- };
4877
- }, [i18n, i18nOptions]);
4878
- const snapshotRef = import_react13.useRef();
4879
- const getSnapshot = import_react13.useCallback(() => {
4880
- if (!i18n) {
4881
- return notReadySnapshot;
4882
- }
4883
- const calculatedReady = !!(i18n.isInitialized || i18n.initializedStoreOnce) && namespaces.every((n) => hasLoadedNamespace2(n, i18n, i18nOptions));
4884
- const currentLng = props.lng || i18n.language;
4885
- const currentRevision = revisionRef.current;
4886
- const lastSnapshot = snapshotRef.current;
4887
- if (lastSnapshot && lastSnapshot.ready === calculatedReady && lastSnapshot.lng === currentLng && lastSnapshot.keyPrefix === keyPrefix && lastSnapshot.revision === currentRevision) {
4888
- return lastSnapshot;
4889
- }
4890
- const calculatedT = i18n.getFixedT(currentLng, i18nOptions.nsMode === "fallback" ? namespaces : namespaces[0], keyPrefix);
4891
- const newSnapshot = {
4892
- t: calculatedT,
4893
- ready: calculatedReady,
4894
- lng: currentLng,
4895
- keyPrefix,
4896
- revision: currentRevision
4897
- };
4898
- snapshotRef.current = newSnapshot;
4899
- return newSnapshot;
4900
- }, [i18n, namespaces, keyPrefix, i18nOptions, props.lng]);
4901
- const [loadCount, setLoadCount] = import_react13.useState(0);
4902
- const {
4903
- t: t2,
4904
- ready
4905
- } = import_shim.useSyncExternalStore(subscribe, getSnapshot, getSnapshot);
4906
- import_react13.useEffect(() => {
4907
- if (i18n && !ready && !useSuspense) {
4908
- const onLoaded = () => setLoadCount((c) => c + 1);
4909
- if (props.lng) {
4910
- loadLanguages2(i18n, props.lng, namespaces, onLoaded);
4911
- } else {
4912
- loadNamespaces2(i18n, namespaces, onLoaded);
4913
- }
4914
- }
4915
- }, [i18n, props.lng, namespaces, ready, useSuspense, loadCount]);
4916
- const finalI18n = i18n || {};
4917
- const wrapperRef = import_react13.useRef(null);
4918
- const wrapperLangRef = import_react13.useRef();
4919
- const createI18nWrapper = (original) => {
4920
- const descriptors = Object.getOwnPropertyDescriptors(original);
4921
- if (descriptors.__original)
4922
- delete descriptors.__original;
4923
- const wrapper = Object.create(Object.getPrototypeOf(original), descriptors);
4924
- if (!Object.prototype.hasOwnProperty.call(wrapper, "__original")) {
4925
- try {
4926
- Object.defineProperty(wrapper, "__original", {
4927
- value: original,
4928
- writable: false,
4929
- enumerable: false,
4930
- configurable: false
4931
- });
4932
- } catch (_) {}
4933
- }
4934
- return wrapper;
4935
- };
4936
- const ret = import_react13.useMemo(() => {
4937
- const original = finalI18n;
4938
- const lang = original?.language;
4939
- let i18nWrapper = original;
4940
- if (original) {
4941
- if (wrapperRef.current && wrapperRef.current.__original === original) {
4942
- if (wrapperLangRef.current !== lang) {
4943
- i18nWrapper = createI18nWrapper(original);
4944
- wrapperRef.current = i18nWrapper;
4945
- wrapperLangRef.current = lang;
4946
- } else {
4947
- i18nWrapper = wrapperRef.current;
4948
- }
4949
- } else {
4950
- i18nWrapper = createI18nWrapper(original);
4951
- wrapperRef.current = i18nWrapper;
4952
- wrapperLangRef.current = lang;
4953
- }
4954
- }
4955
- const effectiveT = !ready && !useSuspense ? (...args) => {
4956
- warnOnce(i18n, "USE_T_BEFORE_READY", "useTranslation: t was called before ready. When using useSuspense: false, make sure to check the ready flag before using t.");
4957
- return t2(...args);
4958
- } : t2;
4959
- const arr = [effectiveT, i18nWrapper, ready];
4960
- arr.t = effectiveT;
4961
- arr.i18n = i18nWrapper;
4962
- arr.ready = ready;
4963
- return arr;
4964
- }, [t2, finalI18n, ready, finalI18n.resolvedLanguage, finalI18n.language, finalI18n.languages]);
4965
- if (i18n && useSuspense && !ready) {
4966
- throw new Promise((resolve2) => {
4967
- const onLoaded = () => resolve2();
4968
- if (props.lng) {
4969
- loadLanguages2(i18n, props.lng, namespaces, onLoaded);
4970
- } else {
4971
- loadNamespaces2(i18n, namespaces, onLoaded);
4972
- }
4973
- });
4974
- }
4975
- return ret;
4976
- };
4977
- // ../../node_modules/.bun/react-i18next@17.0.2+fae4c6524ff71ef1/node_modules/react-i18next/dist/es/I18nextProvider.js
4978
- var import_react14 = __toESM(require_react(), 1);
4979
- function I18nextProvider({
4980
- i18n,
4981
- defaultNS,
4982
- children
4983
- }) {
4984
- const value = import_react14.useMemo(() => ({
4985
- i18n,
4986
- defaultNS
4987
- }), [i18n, defaultNS]);
4988
- return import_react14.createElement(I18nContext.Provider, {
4989
- value
4990
- }, children);
4991
- }
4992
- // src/i18n.ts
4993
- var LocaleCtx = import_react15.createContext(null);
1331
+ import React6, { useState as useState4, useContext as useContext6, useCallback as useCallback6, useMemo as useMemo3, createContext as createContext3 } from "react";
1332
+ import i18next from "i18next";
1333
+ import { initReactI18next, useTranslation, I18nextProvider } from "react-i18next";
1334
+ var LocaleCtx = createContext3(null);
4994
1335
  function createI18n(config) {
4995
- const instance2 = instance.createInstance();
4996
- instance2.use(initReactI18next).init({
1336
+ const instance = i18next.createInstance();
1337
+ instance.use(initReactI18next).init({
4997
1338
  resources: config.resources,
4998
1339
  lng: config.defaultLocale,
4999
1340
  fallbackLng: config.fallbackLocale ?? config.defaultLocale,
5000
1341
  interpolation: { escapeValue: false }
5001
1342
  });
5002
1343
  function Provider({ children }) {
5003
- const [locale, setLocaleState] = import_react15.useState(config.defaultLocale);
5004
- const setLocale = import_react15.useCallback((lng) => {
1344
+ const [locale, setLocaleState] = useState4(config.defaultLocale);
1345
+ const setLocale = useCallback6((lng) => {
5005
1346
  setLocaleState(lng);
5006
1347
  }, []);
5007
- const ctxValue = import_react15.useMemo(() => ({ locale, setLocale }), [locale, setLocale]);
5008
- return import_react15.default.createElement(LocaleCtx.Provider, { value: ctxValue }, import_react15.default.createElement(I18nextProvider, { i18n: instance2 }, children));
1348
+ const ctxValue = useMemo3(() => ({ locale, setLocale }), [locale, setLocale]);
1349
+ return React6.createElement(LocaleCtx.Provider, { value: ctxValue }, React6.createElement(I18nextProvider, { i18n: instance }, children));
5009
1350
  }
5010
- return { Provider, instance: instance2 };
1351
+ return { Provider, instance };
5011
1352
  }
5012
1353
  function useLocale() {
5013
- const localeCtx = import_react15.useContext(LocaleCtx);
1354
+ const localeCtx = useContext6(LocaleCtx);
5014
1355
  const { i18n } = useTranslation();
5015
1356
  const locale = localeCtx?.locale ?? i18n.language;
5016
- const t2 = import_react15.useMemo(() => i18n.getFixedT(locale), [i18n, locale]);
1357
+ const t = useMemo3(() => i18n.getFixedT(locale), [i18n, locale]);
5017
1358
  return {
5018
- t: t2,
1359
+ t,
5019
1360
  locale,
5020
1361
  setLocale: localeCtx?.setLocale ?? (() => {}),
5021
1362
  availableLocales: Object.keys(i18n.options.resources ?? {})
5022
1363
  };
5023
1364
  }
5024
1365
  // src/invoice.ts
5025
- var import_react16 = __toESM(require_react(), 1);
1366
+ import { useState as useState5, useCallback as useCallback7, useRef as useRef3 } from "react";
5026
1367
  function useInvoice(config) {
5027
1368
  const bot = useBot();
5028
- const [status, setStatus] = import_react16.useState("idle");
5029
- const [receipt, setReceipt] = import_react16.useState(null);
5030
- const [error, setError] = import_react16.useState(null);
5031
- const configRef = import_react16.useRef(config);
1369
+ const [status, setStatus] = useState5("idle");
1370
+ const [receipt, setReceipt] = useState5(null);
1371
+ const [error, setError] = useState5(null);
1372
+ const configRef = useRef3(config);
5032
1373
  configRef.current = config;
5033
1374
  useOn("successful_payment", (data) => {
5034
1375
  if (data?.invoice_payload === configRef.current.payload) {
@@ -5043,7 +1384,7 @@ function useInvoice(config) {
5043
1384
  });
5044
1385
  }
5045
1386
  });
5046
- const send = import_react16.useCallback(async () => {
1387
+ const send = useCallback7(async () => {
5047
1388
  const raw = bot.raw;
5048
1389
  if (!raw?.api)
5049
1390
  return;