hevy-shared 1.0.949 → 1.0.951

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.
@@ -49,9 +49,9 @@ class HevyAPIClient {
49
49
  }
50
50
  }
51
51
  get _authHeaders() {
52
- return Object.assign(Object.assign(Object.assign({}, (this._authToken
52
+ return Object.assign(Object.assign({}, (this._authToken
53
53
  ? { authorization: `Bearer ${this._authToken.access_token}` }
54
- : {})), (this._legacyAuthToken ? { 'auth-token': this._legacyAuthToken } : {})), { 'x-client-time': String(new Date().valueOf() / 1000) });
54
+ : {})), (this._legacyAuthToken ? { 'auth-token': this._legacyAuthToken } : {}));
55
55
  }
56
56
  refreshExpiredAuthToken(userContext) {
57
57
  return __awaiter(this, void 0, void 0, function* () {
@@ -99,10 +99,7 @@ class HevyAPIClient {
99
99
  this._lastTokenRefresh = new Date();
100
100
  const { access_token, refresh_token } = authToken;
101
101
  const { method, url } = this.refreshAuthTokenApiEndpoint;
102
- const headers = {
103
- authorization: `Bearer ${access_token}`,
104
- 'x-client-time': String(new Date().valueOf() / 1000),
105
- };
102
+ const headers = { authorization: `Bearer ${access_token}` };
106
103
  // This will throw and bail out if the request fails.
107
104
  const response = yield this._handleResponse({
108
105
  method,
@@ -1,5 +1,4 @@
1
- import { EquipmentFilter, LibraryExercise, MuscleGroupFilter, CustomExercise } from './index';
2
- import { Language } from './translations';
1
+ import { EquipmentFilter, Language, LibraryExercise, MuscleGroupFilter, CustomExercise } from './index';
3
2
  export interface SearchableLibraryExercise extends LibraryExercise {
4
3
  localized_muscle_group_name: string;
5
4
  }
@@ -1,4 +1,4 @@
1
- import { WeeklyTrainingFrequency, TrainingGoal, TrainingLevel, SimplifiedMuscleGroup, MuscleGroup, LibraryExercise, ExerciseCategory, GranularEquipment, HevyTrainerProgramEquipment } from '.';
1
+ import { WeeklyTrainingFrequency, TrainingGoal, TrainingLevel, SimplifiedMuscleGroup, MuscleGroup, LibraryExercise, ExerciseCategory, GranularEquipment, HevyTrainerProgramEquipment, RestTimerLength } from '.';
2
2
  export type HevyTrainerExerciseCategory = typeof hevyTrainerExerciseCategories[number];
3
3
  export type HevyTrainerRoutineName = typeof routineNames[number];
4
4
  export declare const workoutDurationOptions: readonly [40, 60, 80];
@@ -45,6 +45,7 @@ export interface ProgramGenerationParams<T extends HevyTrainerLibraryExercise> {
45
45
  selectedLevel: TrainingLevel;
46
46
  selectedEquipments: GranularEquipment[];
47
47
  selectedWorkoutDurationMinutes?: WorkoutDurationMinutes;
48
+ selectedRestTimerLength: RestTimerLength;
48
49
  exerciseStore: T[];
49
50
  focusMuscle?: SimplifiedMuscleGroup;
50
51
  excludedExerciseIds?: Set<string>;
@@ -71,8 +72,11 @@ export type RepRanges = {
71
72
  export type RestTimersPerCategory = {
72
73
  [key in HevyTrainerExerciseCategory]: number;
73
74
  };
75
+ export type CategoryPerRestTimerLength = {
76
+ [key in RestTimerLength]: RestTimersPerCategory;
77
+ };
74
78
  export type RestTimers = {
75
- [key in TrainingGoal]: RestTimersPerCategory;
79
+ [key in TrainingGoal]: CategoryPerRestTimerLength;
76
80
  };
77
81
  export type ExercisePriorities = {
78
82
  [key in MuscleGroup]: exerciseId[];
@@ -135,7 +139,7 @@ export interface TrainerProgram {
135
139
  }
136
140
  export declare const getTrainerSetCount: (trainerAlgorithmSettings: TrainerAlgorithmSettings, goal: TrainingGoal, frequency: WeeklyTrainingFrequency) => number;
137
141
  export declare const getTrainerRepRange: (trainerAlgorithmSettings: TrainerAlgorithmSettings, goal: TrainingGoal, exerciseCategory: HevyTrainerExerciseCategory) => RepRange;
138
- export declare const getTrainerRestTimerSeconds: (trainerAlgorithmSettings: TrainerAlgorithmSettings, goal: TrainingGoal, exerciseCategory: HevyTrainerExerciseCategory) => number;
142
+ export declare const getTrainerRestTimerSeconds: (trainerAlgorithmSettings: TrainerAlgorithmSettings, goal: TrainingGoal, length: RestTimerLength, exerciseCategory: HevyTrainerExerciseCategory) => number;
139
143
  /**
140
144
  * Normalizes the exercise category to a HevyTrainerExerciseCategory
141
145
  * - Treat custom exercises and exercises with no category as `compound`
@@ -203,8 +203,8 @@ const getTrainerRepRange = (trainerAlgorithmSettings, goal, exerciseCategory) =>
203
203
  return trainerAlgorithmSettings.rep_ranges[goal][exerciseCategory];
204
204
  };
205
205
  exports.getTrainerRepRange = getTrainerRepRange;
206
- const getTrainerRestTimerSeconds = (trainerAlgorithmSettings, goal, exerciseCategory) => {
207
- return trainerAlgorithmSettings.rest_timers[goal][exerciseCategory];
206
+ const getTrainerRestTimerSeconds = (trainerAlgorithmSettings, goal, length, exerciseCategory) => {
207
+ return trainerAlgorithmSettings.rest_timers[goal][length][exerciseCategory];
208
208
  };
209
209
  exports.getTrainerRestTimerSeconds = getTrainerRestTimerSeconds;
210
210
  /**
@@ -498,7 +498,7 @@ exports.pickExerciseForPrescription = pickExerciseForPrescription;
498
498
  */
499
499
  const generateProgram = (params) => {
500
500
  var _a;
501
- const { trainerAlgorithmSettings, selectedDays, selectedGoal, selectedLevel, selectedEquipments, selectedWorkoutDurationMinutes, exerciseStore, focusMuscle, excludedExerciseIds, } = params;
501
+ const { trainerAlgorithmSettings, selectedDays, selectedGoal, selectedLevel, selectedEquipments, selectedWorkoutDurationMinutes, selectedRestTimerLength, exerciseStore, focusMuscle, excludedExerciseIds, } = params;
502
502
  const routines = exports.programSplits[selectedDays];
503
503
  const program = {
504
504
  name: selectedDays,
@@ -565,7 +565,7 @@ const generateProgram = (params) => {
565
565
  sets: (0, exports.getTrainerSetCount)(trainerAlgorithmSettings, selectedGoal, selectedDays),
566
566
  repRangeStart: repRange.rep_range_start,
567
567
  repRangeEnd: repRange.rep_range_end,
568
- restTimerSeconds: (0, exports.getTrainerRestTimerSeconds)(trainerAlgorithmSettings, selectedGoal, exercisePrescription.category),
568
+ restTimerSeconds: (0, exports.getTrainerRestTimerSeconds)(trainerAlgorithmSettings, selectedGoal, selectedRestTimerLength, exercisePrescription.category),
569
569
  warmupSetCount: exercisePrescription.warmup_set_count,
570
570
  notes: (_a = trainerAlgorithmSettings.exercise_notes[exercise.id]) !== null && _a !== void 0 ? _a : '',
571
571
  });
package/built/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { WorkoutDurationMinutes } from './hevyTrainer';
2
- import { Language } from './translations';
2
+ import { Language } from './translationUtils';
3
3
  import { Lookup } from './typeUtils';
4
4
  export * from './constants';
5
5
  export * from './utils';
@@ -21,7 +21,7 @@ export * from './async';
21
21
  export * from './adminPermissions';
22
22
  export * from './adjustEventTokens';
23
23
  export * from './hevyTrainer';
24
- export * from './translations';
24
+ export * from './translationUtils';
25
25
  export type WeightUnit = 'kg' | 'lbs';
26
26
  export declare const isWeightUnit: (x: string) => x is WeightUnit;
27
27
  export type DistanceUnit = 'kilometers' | 'miles';
@@ -640,9 +640,11 @@ export declare const isCustomExerciseType: (x: any) => x is CustomExerciseType;
640
640
  export declare const trainingGoals: readonly ["strength", "build_muscle", "fat_loss"];
641
641
  export declare const trainingLevels: readonly ["beginner", "intermediate", "advanced"];
642
642
  export declare const exerciseCategories: readonly ["isolation", "compound", "assistance-compound"];
643
+ export declare const restTimerLengths: readonly ["short", "medium", "long"];
643
644
  export type TrainingGoal = Lookup<typeof trainingGoals>;
644
645
  export type TrainingLevel = Lookup<typeof trainingLevels>;
645
646
  export type ExerciseCategory = Lookup<typeof exerciseCategories>;
647
+ export type RestTimerLength = typeof restTimerLengths[number];
646
648
  export type HevyTrainerProgramEquipment = Extract<Equipment, 'barbell' | 'dumbbell' | 'machine'>;
647
649
  export declare const hevyTrainerProgramEquipments: readonly ["barbell", "dumbbell", "machine"];
648
650
  export declare const granularEquipments: readonly ["barbell", "dumbbell", "kettlebell", "plate", "medicine_ball", "ez_bar", "landmine", "trap_bar", "pullup_bar", "dip_bar", "squat_rack", "flat_bench", "adjustable_bench", "dual_cable_machine", "single_cable_machine", "lat_pulldown_cable", "leg_press_machine", "smith_machine", "t_bar", "plate_machines", "stack_machines", "treadmill", "elliptical_trainer", "rowing_machine", "spinning", "stair_machine", "air_bike", "suspension_band", "resistance_band", "battle_rope", "rings", "jump_rope"];
@@ -1259,6 +1261,7 @@ export interface HevyTrainerProgram {
1259
1261
  focus_muscle?: SimplifiedMuscleGroup;
1260
1262
  next_workout_index: number;
1261
1263
  workout_duration_minutes?: WorkoutDurationMinutes;
1264
+ rest_timer_length: RestTimerLength;
1262
1265
  }
1263
1266
  export interface PostHevyTrainerProgramRequestBody {
1264
1267
  program: {
@@ -1271,6 +1274,7 @@ export interface PostHevyTrainerProgramRequestBody {
1271
1274
  routines: RoutineUpdate[];
1272
1275
  next_workout_index?: number;
1273
1276
  workout_duration_minutes?: WorkoutDurationMinutes;
1277
+ rest_timer_length: RestTimerLength;
1274
1278
  };
1275
1279
  }
1276
1280
  export interface UpdateHevyTrainerProgramRequestBody {
@@ -1284,6 +1288,7 @@ export interface UpdateHevyTrainerProgramRequestBody {
1284
1288
  focus_muscle?: SimplifiedMuscleGroup;
1285
1289
  next_workout_index?: number;
1286
1290
  workout_duration_minutes?: WorkoutDurationMinutes;
1291
+ rest_timer_length?: RestTimerLength;
1287
1292
  routines: {
1288
1293
  id: string;
1289
1294
  title: string;
package/built/index.js CHANGED
@@ -14,8 +14,8 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
14
  for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
15
  };
16
16
  Object.defineProperty(exports, "__esModule", { value: true });
17
- exports.isHeartRateSamples = exports.isPublicWorkout = exports.isSetType = exports.isRPE = exports.validRpeValues = exports.isSetPersonalRecordType = exports.supportedInstructionsLanguages = exports.weeklyTrainingFrequencies = exports.isGranularEquipment = exports.granularEquipments = exports.hevyTrainerProgramEquipments = exports.exerciseCategories = exports.trainingLevels = exports.trainingGoals = exports.isCustomExerciseType = exports.customExericseTypes = exports.isExerciseType = exports.exerciseTypes = exports.isExerciseRepType = exports.exerciseRepTypes = exports.isEquipmentFilter = exports.equipmentFilters = exports.isEquipment = exports.equipments = exports.simplifiedMuscleGroupToMuscleGroups = exports.isMuscleGroupFilter = exports.muscleGroupFilters = exports.isMuscleGroup = exports.muscleGroups = exports.isSimplifiedMuscleGroup = exports.simplifiedMuscleGroups = exports.miscellaneousMuscles = exports.chestMuscles = exports.backMuscles = exports.legMuscles = exports.armMuscles = exports.shoulderMuscles = exports.coreMuscles = exports.DefaultClientConfiguration = exports.parseClientAuthTokenResponse = exports.isCoachRole = exports.isErrorResponse = exports.isLivePRVolumeOption = exports.isTimerVolumeOption = exports.isWeekday = exports.orderedWeekdays = exports.isBodyMeasurementUnit = exports.isDistanceUnitShort = exports.isDistanceUnit = exports.isWeightUnit = void 0;
18
- exports.isOAuthScope = exports.supportedScopes = exports.isSuggestedUserSource = exports.isValidUserWorkoutMetricsType = exports.isBodyMeasurementKey = exports.measurementsList = exports.isHevyTrainerRoutine = exports.isWorkoutBiometrics = void 0;
17
+ exports.isPublicWorkout = exports.isSetType = exports.isRPE = exports.validRpeValues = exports.isSetPersonalRecordType = exports.supportedInstructionsLanguages = exports.weeklyTrainingFrequencies = exports.isGranularEquipment = exports.granularEquipments = exports.hevyTrainerProgramEquipments = exports.restTimerLengths = exports.exerciseCategories = exports.trainingLevels = exports.trainingGoals = exports.isCustomExerciseType = exports.customExericseTypes = exports.isExerciseType = exports.exerciseTypes = exports.isExerciseRepType = exports.exerciseRepTypes = exports.isEquipmentFilter = exports.equipmentFilters = exports.isEquipment = exports.equipments = exports.simplifiedMuscleGroupToMuscleGroups = exports.isMuscleGroupFilter = exports.muscleGroupFilters = exports.isMuscleGroup = exports.muscleGroups = exports.isSimplifiedMuscleGroup = exports.simplifiedMuscleGroups = exports.miscellaneousMuscles = exports.chestMuscles = exports.backMuscles = exports.legMuscles = exports.armMuscles = exports.shoulderMuscles = exports.coreMuscles = exports.DefaultClientConfiguration = exports.parseClientAuthTokenResponse = exports.isCoachRole = exports.isErrorResponse = exports.isLivePRVolumeOption = exports.isTimerVolumeOption = exports.isWeekday = exports.orderedWeekdays = exports.isBodyMeasurementUnit = exports.isDistanceUnitShort = exports.isDistanceUnit = exports.isWeightUnit = void 0;
18
+ exports.isOAuthScope = exports.supportedScopes = exports.isSuggestedUserSource = exports.isValidUserWorkoutMetricsType = exports.isBodyMeasurementKey = exports.measurementsList = exports.isHevyTrainerRoutine = exports.isWorkoutBiometrics = exports.isHeartRateSamples = void 0;
19
19
  const typeUtils_1 = require("./typeUtils");
20
20
  __exportStar(require("./constants"), exports);
21
21
  __exportStar(require("./utils"), exports);
@@ -37,7 +37,7 @@ __exportStar(require("./async"), exports);
37
37
  __exportStar(require("./adminPermissions"), exports);
38
38
  __exportStar(require("./adjustEventTokens"), exports);
39
39
  __exportStar(require("./hevyTrainer"), exports);
40
- __exportStar(require("./translations"), exports);
40
+ __exportStar(require("./translationUtils"), exports);
41
41
  const isWeightUnit = (x) => {
42
42
  return x === 'kg' || x === 'lbs';
43
43
  };
@@ -227,6 +227,7 @@ exports.exerciseCategories = [
227
227
  'compound',
228
228
  'assistance-compound',
229
229
  ];
230
+ exports.restTimerLengths = ['short', 'medium', 'long'];
230
231
  exports.hevyTrainerProgramEquipments = [
231
232
  'barbell',
232
233
  'dumbbell',
@@ -0,0 +1,5 @@
1
+ import { Lookup } from './typeUtils';
2
+ export declare const supportedLanguages: readonly ["en", "es", "de", "fr", "it", "pt", "tr", "zh_CN", "zh_TW", "ru", "ja", "ko"];
3
+ export type Language = Lookup<typeof supportedLanguages>;
4
+ export declare const isLanguage: (x: string) => x is Language;
5
+ export declare const interpolate: (str: string, params: any[]) => string;
@@ -0,0 +1,30 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.interpolate = exports.isLanguage = exports.supportedLanguages = void 0;
4
+ const typeUtils_1 = require("./typeUtils");
5
+ exports.supportedLanguages = [
6
+ 'en',
7
+ 'es',
8
+ 'de',
9
+ 'fr',
10
+ 'it',
11
+ 'pt',
12
+ 'tr',
13
+ 'zh_CN',
14
+ 'zh_TW',
15
+ 'ru',
16
+ 'ja',
17
+ 'ko',
18
+ ];
19
+ const isLanguage = (x) => (0, typeUtils_1.isInArray)(x, exports.supportedLanguages);
20
+ exports.isLanguage = isLanguage;
21
+ const interpolate = (str, params) => {
22
+ let i = 0;
23
+ return str
24
+ .replace(/%s/g, () => {
25
+ i += 1;
26
+ return params[i - 1];
27
+ })
28
+ .replace(/%{([\w-]*)}/g, (__, key) => params[0][key]);
29
+ };
30
+ exports.interpolate = interpolate;
package/built/utils.d.ts CHANGED
@@ -287,8 +287,4 @@ interface getSetValueParams {
287
287
  }
288
288
  export declare const formatSetValue: ({ exerciseType, set, units, lokalizedLabels, }: getSetValueParams) => string;
289
289
  export declare const rawInstructionsToIndexedSteps: (rawInstructions: string) => ExerciseInstructionsStep[];
290
- export declare const roundToKnownValue: (value: number, knownValues: number[]) => number | undefined;
291
- export declare const indexByNearestValue: <T>(value: number, map: {
292
- [key: number]: T;
293
- }) => T | undefined;
294
290
  export {};
package/built/utils.js CHANGED
@@ -4,7 +4,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.calculateCurrentWeekStreak = exports.getYoutubeVideoId = exports.validateYoutubeUrl = exports.splitAtUsernamesAndLinks = exports.isVersionAGreaterOrEqualToVersionB = exports.generateUserGroupValue = exports.generateUserGroup = exports.isBaseExerciseTemplate = exports.getStrengthLevelFromPercentile = exports.numberToLocaleString = exports.numberWithCommas = exports.setVolume = exports.oneRepMax = exports.oneRepMaxPercentageMap = exports.getEstimatedExercisesDurationSeconds = exports.ESTIMATED_REST_TIMER_DURATION = exports.ESTIMATED_SET_DURATION = exports.UserFacingIndicatorToSetIndicator = exports.workoutSetCount = exports.userExerciseSetWeight = exports.workoutDistanceMeters = exports.workoutReps = exports.workoutDurationSeconds = exports.removeAccents = exports.getClosestDataPointAroundTargetDate = exports.getClosestDataPointBeforeTargetDate = exports.toFragmentedJSON = exports.findMapped = exports.stringToNumber = exports.forceStringToNumber = exports.formatDurationInput = exports.isValidFormattedTime = exports.isWholeNumber = exports.isNumber = exports.isValidUuid = exports.isValidPhoneNumber = exports.isValidWebUrl = exports.URL_REGEX = exports.isValidEmail = exports.secondsToWordFormatMinutes = exports.secondsToWordFormat = exports.secondsToClockFormat = exports.secondsToClockParts = exports.isValidUsername = exports.roundToWholeNumber = exports.roundToOneDecimal = exports.roundToTwoDecimal = exports.divide = exports.clampNumber = exports.num = void 0;
7
- exports.indexByNearestValue = exports.roundToKnownValue = exports.rawInstructionsToIndexedSteps = exports.formatSetValue = exports.exerciseWeight = exports.distance = exports.weekdayNumberMap = exports.startOfWeek = void 0;
7
+ exports.rawInstructionsToIndexedSteps = exports.formatSetValue = exports.exerciseWeight = exports.distance = exports.weekdayNumberMap = exports.startOfWeek = void 0;
8
8
  const dayjs_1 = __importDefault(require("dayjs"));
9
9
  const _1 = require(".");
10
10
  /**
@@ -903,28 +903,3 @@ const rawInstructionsToIndexedSteps = (rawInstructions) => {
903
903
  return instructionsByStep;
904
904
  };
905
905
  exports.rawInstructionsToIndexedSteps = rawInstructionsToIndexedSteps;
906
- const roundToKnownValue = (value, knownValues) => {
907
- if (knownValues.length === 0)
908
- return undefined;
909
- const boundingValues = knownValues.reduce(([lower, upper], v) => {
910
- return [
911
- v > lower && v <= value ? v : lower,
912
- v < upper && v >= value ? v : upper,
913
- ];
914
- }, [-Infinity, Infinity]);
915
- if (boundingValues[0] === -Infinity && boundingValues[1] === Infinity)
916
- return undefined;
917
- if (boundingValues[0] === -Infinity)
918
- return boundingValues[1];
919
- if (boundingValues[1] === Infinity)
920
- return boundingValues[0];
921
- return value - boundingValues[0] < boundingValues[1] - value
922
- ? boundingValues[0]
923
- : boundingValues[1];
924
- };
925
- exports.roundToKnownValue = roundToKnownValue;
926
- const indexByNearestValue = (value, map) => {
927
- const index = (0, exports.roundToKnownValue)(value, Object.keys(map).map((e) => Number(e)));
928
- return index ? map[index] : undefined;
929
- };
930
- exports.indexByNearestValue = indexByNearestValue;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "hevy-shared",
3
- "version": "1.0.949",
3
+ "version": "1.0.951",
4
4
  "description": "",
5
5
  "main": "built/index.js",
6
6
  "types": "built/index.d.ts",
@@ -17,16 +17,12 @@
17
17
  },
18
18
  "exports": {
19
19
  ".": "./built/index.js",
20
- "./API": "./built/API/index.js",
21
- "./translations": "./built/translations/index.js"
20
+ "./API": "./built/API/index.js"
22
21
  },
23
22
  "typesVersions": {
24
23
  "*": {
25
24
  "API": [
26
25
  "built/API/index.d.ts"
27
- ],
28
- "translations": [
29
- "built/translations/index.d.ts"
30
26
  ]
31
27
  }
32
28
  },
@@ -1,2 +0,0 @@
1
- export * from './translationUtils';
2
- export * from './types';
@@ -1,18 +0,0 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
- for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
- };
16
- Object.defineProperty(exports, "__esModule", { value: true });
17
- __exportStar(require("./translationUtils"), exports);
18
- __exportStar(require("./types"), exports);
@@ -1,2 +0,0 @@
1
- import { PositionalTextParams, NamedTextParams, PositionalReactParams, NamedReactParams } from './types';
2
- export declare function interpolate<T extends string>(str: string, params: PositionalTextParams | NamedTextParams<T> | PositionalReactParams | NamedReactParams<T>): string | (string | number)[];
@@ -1,61 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.interpolate = interpolate;
4
- const hasReact = (params) => Object.values(params).some((v) => v !== null &&
5
- v !== undefined &&
6
- typeof v !== 'string' &&
7
- typeof v !== 'number' &&
8
- typeof v !== 'boolean');
9
- function interpolate(str, params) {
10
- if (Array.isArray(params)) {
11
- const positionalParams = params;
12
- const hasReactParams = hasReact(positionalParams);
13
- const re = () => /(%s)/g;
14
- let i = 0;
15
- if (hasReactParams) {
16
- return str
17
- .split(/(%s)/g)
18
- .filter((w) => !!w)
19
- .map((w) => {
20
- var _a, _b;
21
- const [, key] = (_a = re().exec(w)) !== null && _a !== void 0 ? _a : [];
22
- if (!key) {
23
- return w;
24
- }
25
- else {
26
- return ((_b = positionalParams[i++]) !== null && _b !== void 0 ? _b : (console.error(`Missing param ${i} in the string "${str}"`), w));
27
- }
28
- });
29
- }
30
- else {
31
- return str.replace(re(), (_) => { var _a; return String((_a = positionalParams[i++]) !== null && _a !== void 0 ? _a : _); });
32
- }
33
- }
34
- else {
35
- const namedParams = params;
36
- const hasReactParams = hasReact(namedParams);
37
- const re = () => /%{([^}]*)}/g;
38
- if (hasReactParams) {
39
- return str
40
- .split(/(%{[^}]*})/g)
41
- .filter((w) => !!w)
42
- .map((w) => {
43
- var _a, _b;
44
- const [, key] = (_a = re().exec(w)) !== null && _a !== void 0 ? _a : [];
45
- if (!key) {
46
- if (key === '') {
47
- console.error(`Empty param in the string "${str}"`);
48
- }
49
- return w;
50
- }
51
- else {
52
- return ((_b = namedParams[key]) !== null && _b !== void 0 ? _b : (console.error(`Missing param "${key}" in the string "${str}"`),
53
- w));
54
- }
55
- });
56
- }
57
- else {
58
- return str.replace(re(), (_, key) => { var _a; return String((_a = namedParams[key]) !== null && _a !== void 0 ? _a : _); });
59
- }
60
- }
61
- }
@@ -1,8 +0,0 @@
1
- import { Lookup } from '../typeUtils';
2
- export declare const supportedLanguages: readonly ["en", "es", "de", "fr", "it", "pt", "tr", "zh_CN", "zh_TW", "ru", "ja", "ko"];
3
- export type Language = Lookup<typeof supportedLanguages>;
4
- export declare const isLanguage: (x: string) => x is Language;
5
- export type PositionalTextParams = (string | number)[];
6
- export type NamedTextParams<T extends string> = Record<T, string | number>;
7
- export type PositionalReactParams = (string | number | object)[];
8
- export type NamedReactParams<T extends string> = Record<T, string | number | object>;
@@ -1,20 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.isLanguage = exports.supportedLanguages = void 0;
4
- const typeUtils_1 = require("../typeUtils");
5
- exports.supportedLanguages = [
6
- 'en',
7
- 'es',
8
- 'de',
9
- 'fr',
10
- 'it',
11
- 'pt',
12
- 'tr',
13
- 'zh_CN',
14
- 'zh_TW',
15
- 'ru',
16
- 'ja',
17
- 'ko',
18
- ];
19
- const isLanguage = (x) => (0, typeUtils_1.isInArray)(x, exports.supportedLanguages);
20
- exports.isLanguage = isLanguage;