file_path stringlengths 3 280 | file_language stringclasses 66 values | content stringlengths 1 1.04M | repo_name stringlengths 5 92 | repo_stars int64 0 154k | repo_description stringlengths 0 402 | repo_primary_language stringclasses 108 values | developer_username stringlengths 1 25 | developer_name stringlengths 0 30 | developer_company stringlengths 0 82 |
|---|---|---|---|---|---|---|---|---|---|
VideoTool/src/test/java/com/yc/videotool/ExampleUnitTest.java | Java | package com.yc.videotool;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Example local unit test, which will execute on the development machine (host).
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() {
assertEquals(4, 2 + 2);
}
} | yangchong211/YCVideoPlayer | 2,245 | 🔥🔥🔥 基础封装视频播放器player,可以在ExoPlayer、MediaPlayer原生MediaPlayer可以自由切换内核;该播放器整体架构:播放器内核(自由切换) + 视频播放器 + 边播边缓存 + 高度定制播放器UI视图层。支持视频简单播放,列表播放,仿抖音滑动播放,自动切换播放,使用案例丰富,拓展性强。 | Java | yangchong211 | 杨充 | Tencent |
VideoView/build.gradle | Gradle | apply plugin: 'com.android.library'
apply from: rootProject.projectDir.absolutePath + "/VideoGradle/video.gradle"
android {
compileSdkVersion project.ext.androidCompileSdkVersion
buildToolsVersion project.ext.androidBuildToolsVersion
defaultConfig {
minSdkVersion project.ext.androidMinSdkVersion
targetSdkVersion project.ext.androidTargetSdkVersion
versionCode 35
versionName "3.0.5"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation project.ext.AppDependencies['appcompat']
}
/** 以下开始是将Android Library上传到jcenter的相关配置**/
apply plugin: 'com.github.dcendents.android-maven'
apply plugin: 'com.jfrog.bintray'
//项目主页
def siteUrl = 'https://github.com/yangchong211/YCVideoPlayer' // project homepage
//项目的版本控制地址
def gitUrl = 'https://github.com/yangchong211/YCVideoPlayer.git' // project git
//发布到组织名称名字,必须填写
group = "cn.yc"
//发布到JCenter上的项目名字,必须填写
def libName = "VideoView"
// 版本号,下次更新是只需要更改版本号即可
version = "3.0.5"
//生成源文件
task sourcesJar(type: Jar) {
from android.sourceSets.main.java.srcDirs
classifier = 'sources'
}
//生成文档
task javadoc(type: Javadoc) {
source = android.sourceSets.main.java.srcDirs
classpath += project.files(android.getBootClasspath().join(File.pathSeparator))
options.encoding "UTF-8"
options.charSet 'UTF-8'
options.author true
options.version true
options.links "https://github.com/linglongxin24/FastDev/tree/master/mylibrary/docs/javadoc"
failOnError false
}
//文档打包成jar
task javadocJar(type: Jar, dependsOn: javadoc) {
classifier = 'javadoc'
from javadoc.destinationDir
}
//拷贝javadoc文件
task copyDoc(type: Copy) {
from "${buildDir}/docs/"
into "docs"
}
//上传到jcenter所需要的源码文件
artifacts {
archives javadocJar
archives sourcesJar
}
// 配置maven库,生成POM.xml文件
install {
repositories.mavenInstaller {
// This generates POM.xml with proper parameters
pom {
project {
packaging 'aar'
//项目描述,自由填写
name 'This is video float view lib'
url siteUrl
licenses {
license {
//开源协议
name 'The Apache Software License, Version 2.0'
url 'http://www.apache.org/licenses/LICENSE-2.0.txt'
}
}
developers {
developer {
//开发者的个人信息,根据个人信息填写
id 'yangchong'
name 'yc'
email 'yangchong211@163.com'
}
}
scm {
connection gitUrl
developerConnection gitUrl
url siteUrl
}
}
}
}
}
//上传到jcenter
Properties properties = new Properties()
properties.load(project.rootProject.file('local.properties').newDataInputStream())
bintray {
user = properties.getProperty("bintray.user") //读取 local.properties 文件里面的 bintray.user
key = properties.getProperty("bintray.apikey") //读取 local.properties 文件里面的 bintray.apikey
configurations = ['archives']
pkg {
repo = "maven"
name = libName //发布到JCenter上的项目名字,必须填写
desc = 'android video float view' //项目描述
websiteUrl = siteUrl
vcsUrl = gitUrl
licenses = ["Apache-2.0"]
publish = true
}
}
javadoc {
options {
//如果你的项目里面有中文注释的话,必须将格式设置为UTF-8,不然会出现乱码
encoding "UTF-8"
charSet 'UTF-8'
author true
version true
links "http://docs.oracle.com/javase/7/docs/api"
}
}
| yangchong211/YCVideoPlayer | 2,245 | 🔥🔥🔥 基础封装视频播放器player,可以在ExoPlayer、MediaPlayer原生MediaPlayer可以自由切换内核;该播放器整体架构:播放器内核(自由切换) + 视频播放器 + 边播边缓存 + 高度定制播放器UI视图层。支持视频简单播放,列表播放,仿抖音滑动播放,自动切换播放,使用案例丰富,拓展性强。 | Java | yangchong211 | 杨充 | Tencent |
VideoView/src/main/java/com/yc/videoview/FloatLifecycle.java | Java | package com.yc.videoview;
import android.app.Activity;
import android.app.Application;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import androidx.annotation.RequiresApi;
/**
* 用于控制悬浮窗显示周期
* 使用了三种方法针对返回桌面时隐藏悬浮按钮
* 1.startCount计数,针对back到桌面可以及时隐藏
* 2.监听home键,从而及时隐藏
* 3.resumeCount计时,针对一些只执行onPause不执行onStop的奇葩情况
*/
@RequiresApi(api = Build.VERSION_CODES.ICE_CREAM_SANDWICH)
public class FloatLifecycle extends BroadcastReceiver implements Application.ActivityLifecycleCallbacks {
private static final String SYSTEM_DIALOG_REASON_KEY = "reason";
private static final String SYSTEM_DIALOG_REASON_HOME_KEY = "homekey";
private static final long delay = 300;
private Handler mHandler;
private Class[] activities;
private boolean showFlag;
private int startCount;
private int resumeCount;
private boolean appBackground;
private LifecycleListener mLifecycleListener;
FloatLifecycle(Context applicationContext, boolean showFlag, Class[] activities, LifecycleListener lifecycleListener) {
this.showFlag = showFlag;
this.activities = activities;
mLifecycleListener = lifecycleListener;
mHandler = new Handler();
((Application) applicationContext).registerActivityLifecycleCallbacks(this);
applicationContext.registerReceiver(this, new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS));
}
private boolean needShow(Activity activity) {
if (activities == null) {
return true;
}
for (Class a : activities) {
if (a.isInstance(activity)) {
return showFlag;
}
}
return !showFlag;
}
@Override
public void onActivityResumed(Activity activity) {
resumeCount++;
if (needShow(activity)) {
mLifecycleListener.onShow();
}
if (appBackground) {
appBackground = false;
}
}
@Override
public void onActivityPaused(Activity activity) {
resumeCount--;
mHandler.postDelayed(new Runnable() {
@Override
public void run() {
if (resumeCount == 0) {
appBackground = true;
//mLifecycleListener.onPostHide();
}
}
}, delay);
}
@Override
public void onActivityStarted(Activity activity) {
startCount++;
}
@Override
public void onActivityStopped(Activity activity) {
startCount--;
if (startCount == 0) {
//mLifecycleListener.onHide();
}
}
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action != null && action.equals(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)) {
String reason = intent.getStringExtra(SYSTEM_DIALOG_REASON_KEY);
if (SYSTEM_DIALOG_REASON_HOME_KEY.equals(reason)) {
//mLifecycleListener.onHide();
}
}
}
@Override
public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
}
@Override
public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
}
@Override
public void onActivityDestroyed(Activity activity) {
}
}
| yangchong211/YCVideoPlayer | 2,245 | 🔥🔥🔥 基础封装视频播放器player,可以在ExoPlayer、MediaPlayer原生MediaPlayer可以自由切换内核;该播放器整体架构:播放器内核(自由切换) + 视频播放器 + 边播边缓存 + 高度定制播放器UI视图层。支持视频简单播放,列表播放,仿抖音滑动播放,自动切换播放,使用案例丰富,拓展性强。 | Java | yangchong211 | 杨充 | Tencent |
VideoView/src/main/java/com/yc/videoview/FloatPhone.java | Java | package com.yc.videoview;
import android.content.Context;
import android.graphics.PixelFormat;
import android.os.Build;
import android.view.View;
import android.view.WindowManager;
/**
* 7.1及以上需申请权限
*/
public class FloatPhone extends FloatView {
private final Context mContext;
private final WindowManager mWindowManager;
private final WindowManager.LayoutParams mLayoutParams;
private View mView;
private int mX, mY;
FloatPhone(Context applicationContext) {
mContext = applicationContext;
mWindowManager = (WindowManager) applicationContext.getSystemService(Context.WINDOW_SERVICE);
mLayoutParams = new WindowManager.LayoutParams();
}
@Override
public void setSize(int width, int height) {
mLayoutParams.width = width;
mLayoutParams.height = height;
}
@Override
public void setView(View view) {
int layoutType;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
layoutType = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
} else {
layoutType = WindowManager.LayoutParams.TYPE_PHONE;
}
mLayoutParams.flags = WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
| WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
mLayoutParams.type = layoutType;
mLayoutParams.windowAnimations = 0;
mView = view;
}
@Override
public void setGravity(int gravity, int xOffset, int yOffset) {
mLayoutParams.gravity = gravity;
mLayoutParams.x = mX = xOffset;
mLayoutParams.y = mY = yOffset;
}
@Override
public void init() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (WindowUtil.hasPermission(mContext)) {
mLayoutParams.format = PixelFormat.RGBA_8888;
mWindowManager.addView(mView, mLayoutParams);
} else {
PermissionActivity.request(mContext, new PermissionActivity.PermissionListener() {
@Override
public void onSuccess() {
mLayoutParams.format = PixelFormat.RGBA_8888;
mWindowManager.addView(mView, mLayoutParams);
}
@Override
public void onFail() {
}
});
}
}
}
@Override
public void dismiss() {
if (mView!=null){
mWindowManager.removeView(mView);
}
}
@Override
public void updateXY(int x, int y) {
mLayoutParams.x = mX = x;
mLayoutParams.y = mY = y;
mWindowManager.updateViewLayout(mView, mLayoutParams);
}
@Override
void updateX(int x) {
mLayoutParams.x = mX = x;
mWindowManager.updateViewLayout(mView, mLayoutParams);
}
@Override
void updateY(int y) {
mLayoutParams.y = mY = y;
mWindowManager.updateViewLayout(mView, mLayoutParams);
}
@Override
int getX() {
return mX;
}
@Override
int getY() {
return mY;
}
}
| yangchong211/YCVideoPlayer | 2,245 | 🔥🔥🔥 基础封装视频播放器player,可以在ExoPlayer、MediaPlayer原生MediaPlayer可以自由切换内核;该播放器整体架构:播放器内核(自由切换) + 视频播放器 + 边播边缓存 + 高度定制播放器UI视图层。支持视频简单播放,列表播放,仿抖音滑动播放,自动切换播放,使用案例丰富,拓展性强。 | Java | yangchong211 | 杨充 | Tencent |
VideoView/src/main/java/com/yc/videoview/FloatToast.java | Java | package com.yc.videoview;
import android.content.Context;
import android.view.View;
import android.view.WindowManager;
import android.widget.Toast;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
/**
* 自定义 toast 方式,无需申请权限
*/
public class FloatToast extends FloatView {
private Toast toast;
private Object mTN;
private Method show;
private Method hide;
private int mWidth;
private int mHeight;
FloatToast(Context applicationContext) {
toast = new Toast(applicationContext);
}
@Override
public void setSize(int width, int height) {
mWidth = width;
mHeight = height;
}
@Override
public void setView(View view) {
toast.setView(view);
initTN();
}
@Override
public void setGravity(int gravity, int xOffset, int yOffset) {
toast.setGravity(gravity, xOffset, yOffset);
}
@Override
public void init() {
try {
show.invoke(mTN);
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void dismiss() {
try {
hide.invoke(mTN);
} catch (Exception e) {
e.printStackTrace();
}
}
private void initTN() {
try {
Field tnField = toast.getClass().getDeclaredField("mTN");
tnField.setAccessible(true);
mTN = tnField.get(toast);
if (mTN != null) {
show = mTN.getClass().getMethod("show");
hide = mTN.getClass().getMethod("hide");
Field tnParamsField = mTN.getClass().getDeclaredField("mParams");
tnParamsField.setAccessible(true);
WindowManager.LayoutParams params = (WindowManager.LayoutParams) tnParamsField.get(mTN);
if (params != null) {
params.flags = WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
| WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
params.width = mWidth;
params.height = mHeight;
params.windowAnimations = 0;
}
Field tnNextViewField = mTN.getClass().getDeclaredField("mNextView");
tnNextViewField.setAccessible(true);
tnNextViewField.set(mTN, toast.getView());
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
| yangchong211/YCVideoPlayer | 2,245 | 🔥🔥🔥 基础封装视频播放器player,可以在ExoPlayer、MediaPlayer原生MediaPlayer可以自由切换内核;该播放器整体架构:播放器内核(自由切换) + 视频播放器 + 边播边缓存 + 高度定制播放器UI视图层。支持视频简单播放,列表播放,仿抖音滑动播放,自动切换播放,使用案例丰富,拓展性强。 | Java | yangchong211 | 杨充 | Tencent |
VideoView/src/main/java/com/yc/videoview/FloatView.java | Java | package com.yc.videoview;
import android.view.View;
public abstract class FloatView {
abstract void setSize(int width, int height);
abstract void setView(View view);
abstract void setGravity(int gravity, int xOffset, int yOffset);
abstract void init();
abstract void dismiss();
void updateXY(int x, int y) {}
void updateX(int x) {}
void updateY(int y) {}
int getX() {
return 0;
}
int getY() {
return 0;
}
}
| yangchong211/YCVideoPlayer | 2,245 | 🔥🔥🔥 基础封装视频播放器player,可以在ExoPlayer、MediaPlayer原生MediaPlayer可以自由切换内核;该播放器整体架构:播放器内核(自由切换) + 视频播放器 + 边播边缓存 + 高度定制播放器UI视图层。支持视频简单播放,列表播放,仿抖音滑动播放,自动切换播放,使用案例丰富,拓展性强。 | Java | yangchong211 | 杨充 | Tencent |
VideoView/src/main/java/com/yc/videoview/FloatWindow.java | Java | package com.yc.videoview;
import android.animation.TimeInterpolator;
import android.content.Context;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.LayoutRes;
import androidx.annotation.MainThread;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import java.util.HashMap;
import java.util.Map;
/**
* 记得添加下面这个权限
* uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"
*/
public class FloatWindow {
/**
* 如果想要 Window 位于所有 Window 的最顶层,那么采用较大的层级即可,很显然系统 Window 的层级是最大的。
* 当我们采用系统层级时,一般选用TYPE_SYSTEM_ERROR或者TYPE_SYSTEM_OVERLAY,还需要声明权限。
* <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
*/
private FloatWindow() {
}
private static final String mDefaultTag = "default_float_window_tag";
private static Map<String, IFloatWindow> mFloatWindowMap;
public static IFloatWindow get() {
return get(mDefaultTag);
}
public static IFloatWindow get(@NonNull String tag) {
return mFloatWindowMap == null ? null : mFloatWindowMap.get(tag);
}
@MainThread
public static Builder with(@NonNull Context applicationContext) {
return new Builder(applicationContext);
}
public static void destroy() {
destroy(mDefaultTag);
}
public static void destroy(String tag) {
if (mFloatWindowMap == null || !mFloatWindowMap.containsKey(tag)) {
return;
}
IFloatWindow iFloatWindow = mFloatWindowMap.get(tag);
if (iFloatWindow != null) {
iFloatWindow.dismiss();
}
mFloatWindowMap.remove(tag);
}
public static class Builder {
Context mApplicationContext;
View mView;
private int mLayoutId;
int mWidth = ViewGroup.LayoutParams.WRAP_CONTENT;
int mHeight = ViewGroup.LayoutParams.WRAP_CONTENT;
int gravity = Gravity.TOP | Gravity.START;
int xOffset;
int yOffset;
boolean mShow = true;
Class[] mActivities;
int mMoveType = MoveType.fixed;
long mDuration = 300;
TimeInterpolator mInterpolator;
private String mTag = mDefaultTag;
private Builder() {
}
Builder(Context applicationContext) {
mApplicationContext = applicationContext;
}
public Builder setView(@NonNull View view) {
mView = view;
return this;
}
public Builder setView(@LayoutRes int layoutId) {
mLayoutId = layoutId;
return this;
}
public Builder setWidth(int width) {
mWidth = width;
return this;
}
public Builder setHeight(int height) {
mHeight = height;
return this;
}
public Builder setWidth(@WindowScreen.screenType int screenType, float ratio) {
mWidth = (int) ((screenType == WindowScreen.WIDTH ?
WindowUtil.getScreenWidth(mApplicationContext) :
WindowUtil.getScreenHeight(mApplicationContext)) * ratio);
return this;
}
public Builder setHeight(@WindowScreen.screenType int screenType, float ratio) {
mHeight = (int) ((screenType == WindowScreen.WIDTH ?
WindowUtil.getScreenWidth(mApplicationContext) :
WindowUtil.getScreenHeight(mApplicationContext)) * ratio);
return this;
}
public Builder setX(int x) {
xOffset = x;
return this;
}
public Builder setY(int y) {
yOffset = y;
return this;
}
public Builder setX(@WindowScreen.screenType int screenType, float ratio) {
xOffset = (int) ((screenType == WindowScreen.WIDTH ?
WindowUtil.getScreenWidth(mApplicationContext) :
WindowUtil.getScreenHeight(mApplicationContext)) * ratio);
return this;
}
public Builder setY(@WindowScreen.screenType int screenType, float ratio) {
yOffset = (int) ((screenType == WindowScreen.WIDTH ?
WindowUtil.getScreenWidth(mApplicationContext) :
WindowUtil.getScreenHeight(mApplicationContext)) * ratio);
return this;
}
/**
* 设置 Activity 过滤器,用于指定在哪些界面显示悬浮窗,默认全部界面都显示
*
* @param show 过滤类型,子类类型也会生效
* @param activities 过滤界面
*/
public Builder setFilter(boolean show, @NonNull Class... activities) {
mShow = show;
mActivities = activities;
return this;
}
public Builder setMoveType(@MoveType.MOVE_TYPE int moveType) {
mMoveType = moveType;
return this;
}
public Builder setMoveStyle(long duration, @Nullable TimeInterpolator interpolator) {
mDuration = duration;
mInterpolator = interpolator;
return this;
}
public Builder setTag(@NonNull String tag) {
mTag = tag;
return this;
}
public void build() {
if (mFloatWindowMap == null) {
mFloatWindowMap = new HashMap<>();
}
if (mFloatWindowMap.containsKey(mTag)) {
throw new IllegalArgumentException("FloatWindow of this tag has been added," +
" Please set a new tag for the new FloatWindow");
}
if (mView == null && mLayoutId == 0) {
throw new IllegalArgumentException("View has not been set!");
}
if (mView == null) {
LayoutInflater inflate = (LayoutInflater)
mApplicationContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (inflate != null) {
mView = inflate.inflate(mLayoutId, null);
}
}
IFloatWindow floatWindowImpl = new IFloatWindowImpl(this);
mFloatWindowMap.put(mTag, floatWindowImpl);
}
}
}
| yangchong211/YCVideoPlayer | 2,245 | 🔥🔥🔥 基础封装视频播放器player,可以在ExoPlayer、MediaPlayer原生MediaPlayer可以自由切换内核;该播放器整体架构:播放器内核(自由切换) + 视频播放器 + 边播边缓存 + 高度定制播放器UI视图层。支持视频简单播放,列表播放,仿抖音滑动播放,自动切换播放,使用案例丰富,拓展性强。 | Java | yangchong211 | 杨充 | Tencent |
VideoView/src/main/java/com/yc/videoview/IFloatWindow.java | Java | package com.yc.videoview;
import android.view.View;
public abstract class IFloatWindow {
public abstract void show();
public abstract void hide();
public abstract int getX();
public abstract int getY();
public abstract void updateX(int x);
public abstract void updateX(@WindowScreen.screenType int screenType, float ratio);
public abstract void updateY(int y);
public abstract void updateY(@WindowScreen.screenType int screenType, float ratio);
public abstract View getView();
abstract void dismiss();
}
| yangchong211/YCVideoPlayer | 2,245 | 🔥🔥🔥 基础封装视频播放器player,可以在ExoPlayer、MediaPlayer原生MediaPlayer可以自由切换内核;该播放器整体架构:播放器内核(自由切换) + 视频播放器 + 边播边缓存 + 高度定制播放器UI视图层。支持视频简单播放,列表播放,仿抖音滑动播放,自动切换播放,使用案例丰富,拓展性强。 | Java | yangchong211 | 杨充 | Tencent |
VideoView/src/main/java/com/yc/videoview/IFloatWindowImpl.java | Java | package com.yc.videoview;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ObjectAnimator;
import android.animation.PropertyValuesHolder;
import android.animation.TimeInterpolator;
import android.animation.ValueAnimator;
import android.os.Build;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.DecelerateInterpolator;
public class IFloatWindowImpl extends IFloatWindow {
private FloatWindow.Builder mB;
private FloatView mFloatView;
private FloatLifecycle mFloatLifecycle;
private boolean isShow;
private boolean once = true;
private ValueAnimator mAnimator;
private TimeInterpolator mDecelerateInterpolator;
private IFloatWindowImpl() {
}
IFloatWindowImpl(FloatWindow.Builder b) {
mB = b;
//这一步相当于创建系统级的window,通过windowManager添加view并且展示
if (mB.mMoveType == MoveType.fixed) {
if (Build.VERSION.SDK_INT >=Build.VERSION_CODES.N_MR1) {
mFloatView = new FloatPhone(b.mApplicationContext);
} else {
mFloatView = new FloatToast(b.mApplicationContext);
}
} else {
mFloatView = new FloatPhone(b.mApplicationContext);
initTouchEvent();
}
mFloatView.setSize(mB.mWidth, mB.mHeight);
mFloatView.setGravity(mB.gravity, mB.xOffset, mB.yOffset);
mFloatView.setView(mB.mView);
mFloatLifecycle = new FloatLifecycle(mB.mApplicationContext, mB.mShow, mB.mActivities, new LifecycleListener() {
@Override
public void onShow() {
show();
}
@Override
public void onHide() {
hide();
}
@Override
public void onPostHide() {
postHide();
}
});
}
@Override
public void show() {
if (once) {
mFloatView.init();
once = false;
isShow = true;
} else {
if (isShow) {
return;
}
getView().setVisibility(View.VISIBLE);
isShow = true;
}
}
@Override
public void hide() {
if (once || !isShow) return;
getView().setVisibility(View.INVISIBLE);
isShow = false;
}
@Override
void dismiss() {
mFloatView.dismiss();
isShow = false;
}
@Override
public void updateX(int x) {
checkMoveType();
mB.xOffset = x;
mFloatView.updateX(x);
}
@Override
public void updateY(int y) {
checkMoveType();
mB.yOffset = y;
mFloatView.updateY(y);
}
@Override
public void updateX(int screenType, float ratio) {
checkMoveType();
mB.xOffset = (int) ((screenType == WindowScreen.WIDTH ?
WindowUtil.getScreenWidth(mB.mApplicationContext) :
WindowUtil.getScreenHeight(mB.mApplicationContext)) * ratio);
mFloatView.updateX(mB.xOffset);
}
@Override
public void updateY(int screenType, float ratio) {
checkMoveType();
mB.yOffset = (int) ((screenType == WindowScreen.WIDTH ?
WindowUtil.getScreenWidth(mB.mApplicationContext) :
WindowUtil.getScreenHeight(mB.mApplicationContext)) * ratio);
mFloatView.updateY(mB.yOffset);
}
@Override
public int getX() {
return mFloatView.getX();
}
@Override
public int getY() {
return mFloatView.getY();
}
@Override
public View getView() {
return mB.mView;
}
void postHide() {
if (once || !isShow) {
return;
}
getView().post(new Runnable() {
@Override
public void run() {
getView().setVisibility(View.INVISIBLE);
}
});
isShow = false;
}
private void checkMoveType() {
if (mB.mMoveType == MoveType.fixed) {
throw new IllegalArgumentException("FloatWindow of this tag is not allowed to move!");
}
}
private void initTouchEvent() {
switch (mB.mMoveType) {
case MoveType.free:
break;
default:
getView().setOnTouchListener(onTouchListener);
break;
}
}
private View.OnTouchListener onTouchListener = new View.OnTouchListener() {
float lastX, lastY, changeX, changeY;
int newX, newY;
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
lastX = event.getRawX();
lastY = event.getRawY();
cancelAnimator();
break;
case MotionEvent.ACTION_MOVE:
changeX = event.getRawX() - lastX;
changeY = event.getRawY() - lastY;
newX = (int) (mFloatView.getX() + changeX);
newY = (int) (mFloatView.getY() + changeY);
mFloatView.updateXY(newX, newY);
lastX = event.getRawX();
lastY = event.getRawY();
break;
case MotionEvent.ACTION_UP:
switch (mB.mMoveType) {
case MoveType.slide:
int startX = mFloatView.getX();
int endX = (startX * 2 + v.getWidth() >
WindowUtil.getScreenWidth(mB.mApplicationContext)) ?
WindowUtil.getScreenWidth(mB.mApplicationContext) - v.getWidth() : 0;
mAnimator = ObjectAnimator.ofInt(startX, endX);
mAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
int x = (int) animation.getAnimatedValue();
mFloatView.updateX(x);
}
});
startAnimator();
break;
case MoveType.back:
PropertyValuesHolder pvhX = PropertyValuesHolder.ofInt("x", mFloatView.getX(), mB.xOffset);
PropertyValuesHolder pvhY = PropertyValuesHolder.ofInt("y", mFloatView.getY(), mB.yOffset);
mAnimator = ObjectAnimator.ofPropertyValuesHolder(pvhX, pvhY);
mAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
int x = (int) animation.getAnimatedValue("x");
int y = (int) animation.getAnimatedValue("y");
mFloatView.updateXY(x, y);
}
});
startAnimator();
break;
default:
break;
}
break;
default:
break;
}
return false;
}
};
/**
* 开启动画
*/
private void startAnimator() {
if (mB.mInterpolator == null) {
if (mDecelerateInterpolator == null) {
mDecelerateInterpolator = new DecelerateInterpolator();
}
mB.mInterpolator = mDecelerateInterpolator;
}
mAnimator.setInterpolator(mB.mInterpolator);
mAnimator.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
mAnimator.removeAllUpdateListeners();
mAnimator.removeAllListeners();
mAnimator = null;
}
});
mAnimator.setDuration(mB.mDuration).start();
}
/**
* 关闭动画
*/
private void cancelAnimator() {
if (mAnimator != null && mAnimator.isRunning()) {
mAnimator.cancel();
}
}
}
| yangchong211/YCVideoPlayer | 2,245 | 🔥🔥🔥 基础封装视频播放器player,可以在ExoPlayer、MediaPlayer原生MediaPlayer可以自由切换内核;该播放器整体架构:播放器内核(自由切换) + 视频播放器 + 边播边缓存 + 高度定制播放器UI视图层。支持视频简单播放,列表播放,仿抖音滑动播放,自动切换播放,使用案例丰富,拓展性强。 | Java | yangchong211 | 杨充 | Tencent |
VideoView/src/main/java/com/yc/videoview/LifecycleListener.java | Java | package com.yc.videoview;
interface LifecycleListener {
void onShow();
void onHide();
void onPostHide();
}
| yangchong211/YCVideoPlayer | 2,245 | 🔥🔥🔥 基础封装视频播放器player,可以在ExoPlayer、MediaPlayer原生MediaPlayer可以自由切换内核;该播放器整体架构:播放器内核(自由切换) + 视频播放器 + 边播边缓存 + 高度定制播放器UI视图层。支持视频简单播放,列表播放,仿抖音滑动播放,自动切换播放,使用案例丰富,拓展性强。 | Java | yangchong211 | 杨充 | Tencent |
VideoView/src/main/java/com/yc/videoview/MoveType.java | Java | package com.yc.videoview;
import androidx.annotation.IntDef;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
public class MoveType {
public static final int fixed = 0;
public static final int free = 1;
public static final int active = 2;
public static final int slide = 3;
public static final int back = 4;
@IntDef({fixed, free, active, slide, back})
@Retention(RetentionPolicy.SOURCE)
@interface MOVE_TYPE {}
}
| yangchong211/YCVideoPlayer | 2,245 | 🔥🔥🔥 基础封装视频播放器player,可以在ExoPlayer、MediaPlayer原生MediaPlayer可以自由切换内核;该播放器整体架构:播放器内核(自由切换) + 视频播放器 + 边播边缓存 + 高度定制播放器UI视图层。支持视频简单播放,列表播放,仿抖音滑动播放,自动切换播放,使用案例丰富,拓展性强。 | Java | yangchong211 | 杨充 | Tencent |
VideoView/src/main/java/com/yc/videoview/PermissionActivity.java | Java | package com.yc.videoview;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import java.util.ArrayList;
import java.util.List;
/**
* <pre>
* @author yangchong
* blog : https://github.com/yangchong211
* time : 2018/2/10
* desc : 用于在内部自动申请权限
* revise:
* </pre>
*/
public class PermissionActivity extends AppCompatActivity {
private static List<PermissionListener> mPermissionListenerList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (Build.VERSION.SDK_INT >= 23){
requestAlertWindowPermission();
}
}
@RequiresApi(api = 23)
private void requestAlertWindowPermission() {
Intent intent = new Intent("android.settings.action.MANAGE_OVERLAY_PERMISSION");
intent.setData(Uri.parse("package:" + getPackageName()));
startActivityForResult(intent, 1);
}
@RequiresApi(api = 23)
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (Build.VERSION.SDK_INT >= 23){
//用23以上编译即可出现canDrawOverlays
if (WindowUtil.hasPermission(this)) {
mPermissionListener.onSuccess();
} else {
mPermissionListener.onFail();
}
}
finish();
}
static synchronized void request(Context context, PermissionListener permissionListener) {
if (mPermissionListenerList == null) {
mPermissionListenerList = new ArrayList<>();
mPermissionListener = new PermissionListener() {
@Override
public void onSuccess() {
for (PermissionListener listener : mPermissionListenerList) {
listener.onSuccess();
}
}
@Override
public void onFail() {
for (PermissionListener listener : mPermissionListenerList) {
listener.onFail();
}
}
};
Intent intent = new Intent(context, PermissionActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
mPermissionListenerList.add(permissionListener);
}
private static PermissionListener mPermissionListener;
public interface PermissionListener {
/**
* 成功
*/
void onSuccess();
/**
* 失败
*/
void onFail();
}
}
| yangchong211/YCVideoPlayer | 2,245 | 🔥🔥🔥 基础封装视频播放器player,可以在ExoPlayer、MediaPlayer原生MediaPlayer可以自由切换内核;该播放器整体架构:播放器内核(自由切换) + 视频播放器 + 边播边缓存 + 高度定制播放器UI视图层。支持视频简单播放,列表播放,仿抖音滑动播放,自动切换播放,使用案例丰富,拓展性强。 | Java | yangchong211 | 杨充 | Tencent |
VideoView/src/main/java/com/yc/videoview/SmallWindowTouch.java | Java | package com.yc.videoview;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.FrameLayout;
/**
* <pre>
* @author yangchong
* blog : https://github.com/yangchong211
* time : 2018/8/29
* desc : 小窗口触摸移动
* revise:
* </pre>
*/
public class SmallWindowTouch implements View.OnTouchListener {
private int mDownX, mDownY;
private int mMarginLeft, mMarginTop;
private int _xDelta, _yDelta;
private View mView;
public SmallWindowTouch(View view, int marginLeft, int marginTop) {
super();
mMarginLeft = marginLeft;
mMarginTop = marginTop;
mView = view;
}
@Override
public boolean onTouch(View view, MotionEvent event) {
final int X = (int) event.getRawX();
final int Y = (int) event.getRawY();
Log.e("onTouch","---X---"+X + "---Y---"+Y);
switch (event.getAction() & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_DOWN:
mDownX = X;
mDownY = Y;
FrameLayout.LayoutParams lParams = (FrameLayout.LayoutParams) mView.getLayoutParams();
_xDelta = X - lParams.leftMargin;
_yDelta = Y - lParams.topMargin;
break;
case MotionEvent.ACTION_UP:
if (Math.abs(mDownY - Y) < 5 && Math.abs(mDownX - X) < 5) {
return false;
} else {
return true;
}
case MotionEvent.ACTION_MOVE:
FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) mView.getLayoutParams();
layoutParams.leftMargin = X - _xDelta;
layoutParams.topMargin = Y - _yDelta;
if (layoutParams.leftMargin >= mMarginLeft) {
layoutParams.leftMargin = mMarginLeft;
}
if (layoutParams.topMargin >= mMarginTop) {
layoutParams.topMargin = mMarginTop;
}
if (layoutParams.leftMargin <= 0) {
layoutParams.leftMargin = 0;
}
if (layoutParams.topMargin <= 0) {
layoutParams.topMargin = 0;
}
mView.setLayoutParams(layoutParams);
break;
default:
break;
}
return false;
}
} | yangchong211/YCVideoPlayer | 2,245 | 🔥🔥🔥 基础封装视频播放器player,可以在ExoPlayer、MediaPlayer原生MediaPlayer可以自由切换内核;该播放器整体架构:播放器内核(自由切换) + 视频播放器 + 边播边缓存 + 高度定制播放器UI视图层。支持视频简单播放,列表播放,仿抖音滑动播放,自动切换播放,使用案例丰富,拓展性强。 | Java | yangchong211 | 杨充 | Tencent |
VideoView/src/main/java/com/yc/videoview/WindowScreen.java | Java | package com.yc.videoview;
import androidx.annotation.IntDef;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
public class WindowScreen {
public static final int WIDTH = 0;
public static final int HEIGHT = 1;
@IntDef({WIDTH, HEIGHT})
@Retention(RetentionPolicy.SOURCE)
@interface screenType {}
}
| yangchong211/YCVideoPlayer | 2,245 | 🔥🔥🔥 基础封装视频播放器player,可以在ExoPlayer、MediaPlayer原生MediaPlayer可以自由切换内核;该播放器整体架构:播放器内核(自由切换) + 视频播放器 + 边播边缓存 + 高度定制播放器UI视图层。支持视频简单播放,列表播放,仿抖音滑动播放,自动切换播放,使用案例丰富,拓展性强。 | Java | yangchong211 | 杨充 | Tencent |
VideoView/src/main/java/com/yc/videoview/WindowUtil.java | Java | package com.yc.videoview;
import android.content.Context;
import android.graphics.Point;
import android.os.Build;
import android.provider.Settings;
import android.view.WindowManager;
import androidx.annotation.RequiresApi;
public final class WindowUtil {
@RequiresApi(api = Build.VERSION_CODES.M)
public static boolean hasPermission(Context context) {
return Settings.canDrawOverlays(context);
}
private static Point sPoint;
static int getScreenWidth(Context context) {
if (sPoint == null) {
sPoint = new Point();
WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
if (wm != null) {
wm.getDefaultDisplay().getSize(sPoint);
}
}
return sPoint.x;
}
static int getScreenHeight(Context context) {
if (sPoint == null) {
sPoint = new Point();
WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
if (wm != null) {
wm.getDefaultDisplay().getSize(sPoint);
}
}
return sPoint.y;
}
}
| yangchong211/YCVideoPlayer | 2,245 | 🔥🔥🔥 基础封装视频播放器player,可以在ExoPlayer、MediaPlayer原生MediaPlayer可以自由切换内核;该播放器整体架构:播放器内核(自由切换) + 视频播放器 + 边播边缓存 + 高度定制播放器UI视图层。支持视频简单播放,列表播放,仿抖音滑动播放,自动切换播放,使用案例丰富,拓展性强。 | Java | yangchong211 | 杨充 | Tencent |
build.gradle | Gradle | // Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
repositories {
google()
jcenter()
maven {
url 'https://maven.google.com/'
name 'Google'
}
maven { url 'https://jitpack.io' }
}
dependencies {
classpath 'com.android.tools.build:gradle:3.2.1'
//添加下面两句,进行配置
classpath 'com.github.dcendents:android-maven-gradle-plugin:2.1'
classpath 'com.jfrog.bintray.gradle:gradle-bintray-plugin:1.8.4'
}
}
allprojects {
repositories {
google()
jcenter()
maven {
url 'https://maven.google.com/'
name 'Google'
}
maven { url 'https://jitpack.io' }
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
| yangchong211/YCVideoPlayer | 2,245 | 🔥🔥🔥 基础封装视频播放器player,可以在ExoPlayer、MediaPlayer原生MediaPlayer可以自由切换内核;该播放器整体架构:播放器内核(自由切换) + 视频播放器 + 边播边缓存 + 高度定制播放器UI视图层。支持视频简单播放,列表播放,仿抖音滑动播放,自动切换播放,使用案例丰富,拓展性强。 | Java | yangchong211 | 杨充 | Tencent |
settings.gradle | Gradle |
//视频弹幕
include ':VideoBarrage'
//视频录频
include ':VideoRecorder'
//视频投屏
include ':VideoScreen'
//视频播放位置记录二级缓存
include ':VideoSqlLite'
//m3u8下载和合成
include ':VideoM3u8'
//音频
include ':MusicPlayer'
//视频悬浮
include ':VideoView'
//视频内核
include ':VideoKernel'
//视频边播边缓存
include ':VideoCache'
//视频播放器
include ':VideoPlayer'
include ':Demo'
include ':VideoTool'
| yangchong211/YCVideoPlayer | 2,245 | 🔥🔥🔥 基础封装视频播放器player,可以在ExoPlayer、MediaPlayer原生MediaPlayer可以自由切换内核;该播放器整体架构:播放器内核(自由切换) + 视频播放器 + 边播边缓存 + 高度定制播放器UI视图层。支持视频简单播放,列表播放,仿抖音滑动播放,自动切换播放,使用案例丰富,拓展性强。 | Java | yangchong211 | 杨充 | Tencent |
httpserver/main.go | Go | package main
import (
"encoding/json"
"fmt"
"github.com/gin-gonic/gin"
"github.com/pingcap/tiflow/cdc/model"
"log"
"net/http"
)
// AddTableReq add table request
type AddTableReq struct {
TableID int64 `json:"table_id"`
}
// RemoveTableReq remove table request
type RemoveTableReq struct {
TableID int64 `json:"table_id"`
}
type PluginRequest struct {
Operation string `json:"operation"`
Data interface{} `json:"data"`
}
var (
sinkAddTable = "sink_add_table"
sinkRemoveTable = "sink_remove_table"
sinkEmitRowChangedEvents = "sink_emit_row_changed_events"
sinkEmitDDLEvent = "sink_emit_ddl_event"
)
func main() {
r := gin.Default()
r.GET("/ping", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
"code": 200,
"message": "pong",
})
})
r.POST("/sink_sync", func(c *gin.Context) {
pr := &PluginRequest{}
if err := c.ShouldBindJSON(pr); err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"code": 400,
"message": err.Error(),
})
return
}
rd, err := json.Marshal(pr.Data)
if err != nil {
log.Printf("marshal failed, error: %v", err)
return
}
switch pr.Operation {
case sinkAddTable:
AddTable(rd)
case sinkRemoveTable:
RemoveTable(rd)
case sinkEmitRowChangedEvents:
EmitRowChangedEvents(rd)
case sinkEmitDDLEvent:
EmitDDLEvent(rd)
default:
log.Printf("unsupport operation")
c.JSON(http.StatusBadRequest, gin.H{
"code": 400,
"message": "unsupport operation",
"cause": fmt.Sprintf("We havn't support operation %v", pr.Operation),
})
return
}
c.JSON(http.StatusOK, gin.H{
"code": 200,
"message": fmt.Sprintf("%v ok", pr.Operation),
})
})
r.Run(":5005")
}
func AddTable(data []byte) {
log.Printf("start execute add table")
atr := &AddTableReq{}
err := json.Unmarshal(data, atr)
if err != nil {
log.Printf("addTable unmarshal failed, error: %v", err)
return
}
log.Printf("req data: %v", atr)
log.Printf("execute add table end")
}
func RemoveTable(data []byte) {
log.Printf("start execute remove table")
rtr := &RemoveTableReq{}
err := json.Unmarshal(data, rtr)
if err != nil {
log.Printf("RemoveTable unmarshal failed, error: %v", err)
return
}
log.Printf("req data: %v", rtr)
log.Printf("execute remove table end")
}
func EmitRowChangedEvents(data []byte) {
log.Printf("start execute row changed events")
rces := []*model.RowChangedEvent{}
err := json.Unmarshal(data, &rces)
if err != nil {
log.Printf("EmitRowChangedEvents unmarshal failed, error: %v", err)
return
}
for i, rce := range rces {
log.Printf("index: %v, table: %v", i, rce.Table)
for j, column := range rce.Columns {
log.Printf("column index: %v, column value: %v", j, column.Value)
}
}
log.Printf("execute row changed events end")
}
func EmitDDLEvent(data []byte) {
log.Printf("start execute ddl event")
ddlEvent := &model.DDLEvent{}
err := json.Unmarshal(data, ddlEvent)
if err != nil {
log.Printf("RemoveTable unmarshal failed, error: %v", err)
return
}
log.Printf("req data: %v", ddlEvent)
log.Printf("execute ddl event end")
}
| yangwenmai/hackathon2022-plugin-server | 1 | PingCAP Hackathon 2022 plugin server(include http and rpc) | Go | yangwenmai | maiyang | |
rpcserver/main.go | Go | package main
import (
"encoding/json"
"fmt"
"github.com/pingcap/tiflow/cdc/model"
"log"
"net"
"net/rpc"
"net/rpc/jsonrpc"
)
var (
sinkAddTable = "sink_add_table"
sinkRemoveTable = "sink_remove_table"
sinkEmitRowChangedEvents = "sink_emit_row_changed_events"
sinkEmitDDLEvent = "sink_emit_ddl_event"
)
type SinkSyncArgs struct {
Operation string `json:"operation"`
Data interface{} `json:"data"`
}
type Response struct {
Code int `json:"code"`
Message string `json:"message"`
}
// AddTableReq add table request
type AddTableReq struct {
TableID int64 `json:"table_id"`
}
// RemoveTableReq remove table request
type RemoveTableReq struct {
TableID int64 `json:"table_id"`
}
type SinkSyncService struct{}
func (t *SinkSyncService) SinkSync(args *SinkSyncArgs, result *Response) error {
*result = Response{Code: 200, Message: fmt.Sprintf("Sink sync data %v", args)}
log.Printf("SinkSync: %v", result)
rd, err := json.Marshal(args.Data)
if err != nil {
log.Printf("marshal failed, error: %v", err)
return err
}
switch args.Operation {
case sinkAddTable:
AddTable(rd)
case sinkRemoveTable:
RemoveTable(rd)
case sinkEmitRowChangedEvents:
EmitRowChangedEvents(rd)
case sinkEmitDDLEvent:
EmitDDLEvent(rd)
default:
log.Printf("unsupport operation")
result.Code = 400
result.Message = "unsupport operation"
}
return nil
}
func main() {
rpcServer := rpc.NewServer()
sss := new(SinkSyncService)
rpcServer.Register(sss)
listener, _ := net.Listen("tcp", "127.0.0.1:5006")
log.Printf("rpc server start")
for {
conn, _ := listener.Accept()
go rpcServer.ServeCodec(jsonrpc.NewServerCodec(conn))
}
}
func AddTable(data []byte) {
log.Printf("start execute add table")
atr := &AddTableReq{}
err := json.Unmarshal(data, atr)
if err != nil {
log.Printf("addTable unmarshal failed, error: %v", err)
return
}
log.Printf("req data: %v", atr)
log.Printf("execute add table end")
}
func RemoveTable(data []byte) {
log.Printf("start execute remove table")
rtr := &RemoveTableReq{}
err := json.Unmarshal(data, rtr)
if err != nil {
log.Printf("RemoveTable unmarshal failed, error: %v", err)
return
}
log.Printf("req data: %v", rtr)
log.Printf("execute remove table end")
}
func EmitRowChangedEvents(data []byte) {
log.Printf("start execute row changed events")
rces := []*model.RowChangedEvent{}
err := json.Unmarshal(data, &rces)
if err != nil {
log.Printf("EmitRowChangedEvents unmarshal failed, error: %v", err)
return
}
for i, rce := range rces {
log.Printf("index: %v, table: %v", i, rce.Table)
for j, column := range rce.Columns {
log.Printf("column index: %v, column value: %v", j, column.Value)
}
}
log.Printf("execute row changed events end")
}
func EmitDDLEvent(data []byte) {
log.Printf("start execute ddl event")
ddlEvent := &model.DDLEvent{}
err := json.Unmarshal(data, ddlEvent)
if err != nil {
log.Printf("RemoveTable unmarshal failed, error: %v", err)
return
}
log.Printf("req data: %v", ddlEvent)
log.Printf("execute ddl event end")
}
| yangwenmai/hackathon2022-plugin-server | 1 | PingCAP Hackathon 2022 plugin server(include http and rpc) | Go | yangwenmai | maiyang | |
s001.go | Go | package s001
// 输入一个递增排序的数组和一个数字 S,在数组中查找两个数,使得他们的和正好是 S,
// 如果有多对数字的和等于 S,输出两个数的乘积最小的。
func FindTwoSum(arr []int, s int) (int, int) {
ret := map[int]int{}
for i := 0; i < len(arr); i++ {
ret[arr[i]] = i
}
mini, minj := len(arr)-1, len(arr)-1
for i := 0; i < len(arr); i++ {
interVal := s - arr[i]
if j, ok := ret[interVal]; ok {
if arr[i]*arr[j] < arr[mini]*arr[minj] {
mini = i
minj = j
}
}
}
return mini, minj
}
| yangwenmai/talkgo-algorithms | 4 | TalkGo 算法之美题解 | Go | yangwenmai | maiyang | |
s001_test.go | Go | package s001
import (
"testing"
"github.com/stretchr/testify/require"
)
func TestFindTwoSum(t *testing.T) {
x1, x2 := FindTwoSum([]int{1, 3, 5, 7, 8, 10, 13}, 15)
require.EqualValues(t, 2, x1)
require.EqualValues(t, 5, x2)
x1, x2 = FindTwoSum([]int{1, 2, 3, 7, 8, 10, 12}, 13)
require.EqualValues(t, 0, x1)
require.EqualValues(t, 6, x2)
x1, x2 = FindTwoSum([]int{0, 2, 3, 10, 11, 44, 55, 66, 77}, 55)
require.EqualValues(t, 0, x1)
require.EqualValues(t, 6, x2)
}
| yangwenmai/talkgo-algorithms | 4 | TalkGo 算法之美题解 | Go | yangwenmai | maiyang | |
s002.go | Go | package s002
import (
"fmt"
)
// 一个有序数组,从随即一位截断,把前段放在后边,如 4 5 6 7 1 2 3 求中位数
func FindMiddleNumber(arr []int) int {
newArr := sort(arr)
if len(newArr)%2 == 0 {
// 偶数
return (newArr[len(newArr)/2-1] + newArr[len(newArr)/2]) / 2
} else {
return newArr[len(newArr)/2]
}
}
func sort(arr []int) []int {
newArr := []int{}
for i := 0; i < len(arr); i++ {
if arr[i] > arr[i+1] {
newArr = append(newArr, arr[i+1:]...)
newArr = append(newArr, arr[:i+1]...)
break
}
}
return newArr
}
| yangwenmai/talkgo-algorithms | 4 | TalkGo 算法之美题解 | Go | yangwenmai | maiyang | |
s002_test.go | Go | package s002
import (
"testing"
"github.com/stretchr/testify/require"
)
func TestFindMiddle(t *testing.T) {
arr := []int{7, 11, 15, 1, 2, 3}
ret := FindMiddleNumber(arr)
require.EqualValues(t, 5, ret)
arr = []int{7, 11, 15, 1, 2, 3, 6}
ret = FindMiddleNumber(arr)
require.EqualValues(t, 6, ret)
}
| yangwenmai/talkgo-algorithms | 4 | TalkGo 算法之美题解 | Go | yangwenmai | maiyang | |
s003.go | Go | package s003
// 给定字符串 S1,S2, 判断字符串 S1 中的字符是否都在字符串 S2 中(S1 长度 N,S2长度 M)
func HasContains(str, substr string) bool {
slen1 := len(str)
slen2 := len(substr)
if slen2 > slen1 {
return false
}
for i := 0; i < slen1; i++ {
tmp := str[i : i+slen2]
if len(tmp) < slen2 {
return false
}
if tmp == substr {
return true
}
}
return false
}
| yangwenmai/talkgo-algorithms | 4 | TalkGo 算法之美题解 | Go | yangwenmai | maiyang | |
s003_test.go | Go | package s003
import (
"testing"
"github.com/stretchr/testify/require"
)
func TestHasContains(t *testing.T) {
s1, s2 := "123", "12"
ret := HasContains(s1, s2)
require.True(t, ret)
s1, s2 = "123", "1234"
ret = HasContains(s1, s2)
require.False(t, ret)
s1, s2 = "123", "123"
ret = HasContains(s1, s2)
require.True(t, ret)
}
// goos: darwin
// goarch: amd64
// BenchmarkHasContains-8 175624195 6.78 ns/op
// PASS
// ok command-line-arguments 2.763s
func BenchmarkHasContains(b *testing.B) {
b.ResetTimer()
for i := 0; i < b.N; i++ {
HasContains("1234", "12")
}
}
| yangwenmai/talkgo-algorithms | 4 | TalkGo 算法之美题解 | Go | yangwenmai | maiyang | |
.storybook/main.ts | TypeScript | import type { StorybookConfig } from "@storybook/svelte-vite";
const config: StorybookConfig = {
stories: ["../src/**/*.stories.@(js|jsx|ts|tsx|svelte)"],
addons: [
"@storybook/addon-links",
"@storybook/sveltekit",
// "storybook-addon-pseudo-states",
// "storybook-addon-mock-date",
{
name: "@storybook/addon-svelte-csf",
options: {
legacyTemplate: false,
},
},
"@storybook/addon-docs",
"@storybook/addon-vitest",
],
framework: "@storybook/svelte-vite",
docs: {},
env: (config) => ({
...config,
VITE_STORYBOOK_PUBLISHABLE_API_KEY:
process.env.VITE_STORYBOOK_PUBLISHABLE_API_KEY || "",
VITE_STORYBOOK_ACCOUNT_ID: process.env.VITE_STORYBOOK_ACCOUNT_ID || "",
VITE_ALLOW_TAX_CALCULATION_FF:
process.env.VITE_ALLOW_TAX_CALCULATION_FF || "false",
}),
};
export default config;
| yannbf/purchases-js-repro | 0 | TypeScript | yannbf | Yann Braga | chromaui | |
.storybook/modes.ts | TypeScript | export const brandingLanguageViewportModes = {
"mobile-en-default": {
name: "Mobile / English / Default",
viewport: "mobile",
brandingName: "None",
locale: "en",
},
"desktop-en-default": {
name: "Desktop / English / Default",
viewport: "desktop",
brandingName: "None",
locale: "en",
},
"embedded-en-default": {
name: "Embedded / English / Default",
viewport: "embedded",
brandingName: "None",
locale: "en",
},
"mobile-fr-igify": {
name: "Mobile / French / Igify",
viewport: "mobile",
brandingName: "Igify",
locale: "fr",
},
"desktop-fr-igify": {
name: "Desktop / French / Igify",
viewport: "desktop",
brandingName: "Igify",
locale: "fr",
},
"embedded-fr-igify": {
name: "Embedded / French / Igify",
viewport: "embedded",
brandingName: "Igify",
locale: "fr",
},
"mobile-ar-dipsea": {
name: "Mobile / Arabic / Dipsea",
viewport: "mobile",
brandingName: "Dipsea",
locale: "ar",
},
"desktop-ar-dipsea": {
name: "Desktop / Arabic / Dipsea",
viewport: "desktop",
brandingName: "Dipsea",
locale: "ar",
},
"embedded-ar-dipsea": {
name: "Embedded / Arabic / Dipsea",
viewport: "embedded",
brandingName: "Dipsea",
locale: "ar",
},
};
export const brandingModes = {
"mobile-en-default": brandingLanguageViewportModes["mobile-en-default"],
"mobile-fr-igify": brandingLanguageViewportModes["mobile-fr-igify"],
"mobile-ar-dipsea": brandingLanguageViewportModes["mobile-ar-dipsea"],
};
export const mobileAndDesktopBrandingModes = {
"mobile-en-default": brandingLanguageViewportModes["mobile-en-default"],
"mobile-fr-igify": brandingLanguageViewportModes["mobile-fr-igify"],
"mobile-ar-dipsea": brandingLanguageViewportModes["mobile-ar-dipsea"],
"desktop-en-default": brandingLanguageViewportModes["desktop-en-default"],
"desktop-fr-igify": brandingLanguageViewportModes["desktop-fr-igify"],
"desktop-ar-dipsea": brandingLanguageViewportModes["desktop-ar-dipsea"],
};
export const allModes = {
...brandingLanguageViewportModes,
};
| yannbf/purchases-js-repro | 0 | TypeScript | yannbf | Yann Braga | chromaui | |
.storybook/preview.ts | TypeScript | import type { Preview } from "@storybook/sveltekit";
import GlobalDecorator from "../src/stories/decorators/global-decorator.svelte";
import { brandingInfos } from "../src/stories/fixtures";
const preview: Preview = {
parameters: {
mockingDate: new Date("2024-10-18T13:24:21Z"),
layout: "fullscreen",
actions: { argTypesRegex: "^on[A-Z].*" },
controls: {
matchers: {
color: /(background|color)$/i,
date: /Date$/i,
},
},
viewport: {
viewports: {
mobile: {
name: "Mobile",
styles: {
width: "375px",
height: "667px",
},
},
desktop: {
name: "Desktop",
styles: {
width: "1440px",
height: "900px",
},
},
embedded: {
name: "Embedded",
styles: {
width: "100vw",
height: "100vh",
},
},
},
},
},
decorators: [
(Story, context) => {
return {
Component: GlobalDecorator,
props: {
globals: context.globals,
children: () => ({
Component: Story,
props: context.args,
}),
},
};
},
],
globalTypes: {
locale: {
description: "Pick an example locale",
toolbar: {
title: "Locale",
icon: "globe",
dynamicTitle: true,
items: [
{
value: "en",
title: "English",
},
{
value: "fr",
title: "French",
},
{
value: "de",
title: "German",
},
{
value: "es",
title: "Spanish",
},
{
value: "it",
title: "Italian",
},
{
value: "ja",
title: "Japanese",
},
{
value: "ca",
title: "Catalan",
},
{
value: "ar",
title: "Arabic",
},
],
},
},
brandingName: {
description: "Pick an example branding",
toolbar: {
title: "Branding",
icon: "paintbrush",
dynamicTitle: true,
items: Object.keys(brandingInfos).map((key) => ({
value: key,
title: key,
})),
},
},
},
initialGlobals: {
locale: "en",
brandingName: "Igify",
},
};
export default preview;
| yannbf/purchases-js-repro | 0 | TypeScript | yannbf | Yann Braga | chromaui | |
.storybook/vitest.setup.ts | TypeScript | import { beforeAll } from "vitest";
import { setProjectAnnotations } from "@storybook/sveltekit";
import * as projectAnnotations from "./preview";
// This is an important step to apply the right configuration when testing your stories.
// More info at: https://storybook.js.org/docs/api/portable-stories/portable-stories-vitest#setprojectannotations
const project = setProjectAnnotations([projectAnnotations]);
beforeAll(project.beforeAll);
| yannbf/purchases-js-repro | 0 | TypeScript | yannbf | Yann Braga | chromaui | |
eslint.config.js | JavaScript | import globals from "globals";
import pluginJs from "@eslint/js";
import tseslint from "typescript-eslint";
/** @type {import('eslint').Linter.Config[]} */
export default [
{ files: ["**/*.{js, ts, svelte}"] },
{ languageOptions: { globals: globals.browser } },
pluginJs.configs.recommended,
...tseslint.configs.recommended,
{
rules: {
"@typescript-eslint/consistent-type-imports": [
"error",
{
prefer: "type-imports",
},
],
},
},
];
| yannbf/purchases-js-repro | 0 | TypeScript | yannbf | Yann Braga | chromaui | |
examples/webbilling-demo/.eslintrc.config.js | JavaScript | import globals from "globals";
import pluginJs from "@eslint/js";
import tseslint from "typescript-eslint";
/** @type {import('eslint').Linter.Config[]} */
export default [
{ files: ["**/*.{js, ts, svelte}"] },
{ languageOptions: { globals: globals.browser } },
pluginJs.configs.recommended,
...tseslint.configs.recommended,
{
rules: {
"@typescript-eslint/consistent-type-imports": [
"error",
{
prefer: "type-imports",
},
],
},
},
];
| yannbf/purchases-js-repro | 0 | TypeScript | yannbf | Yann Braga | chromaui | |
examples/webbilling-demo/index.html | HTML | <!doctype html>
<html lang="en">
<head>
<meta name="robots" content="noindex" />
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Health Check – Web Billing Demo</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>
| yannbf/purchases-js-repro | 0 | TypeScript | yannbf | Yann Braga | chromaui | |
examples/webbilling-demo/playwright-global-setup.ts | TypeScript | // We can use this function to define variables that will only be available
// within the test method
// https://playwright.dev/docs/test-global-setup-teardown
async function globalSetup() {}
export default globalSetup;
| yannbf/purchases-js-repro | 0 | TypeScript | yannbf | Yann Braga | chromaui | |
examples/webbilling-demo/playwright.config.ts | TypeScript | import { fileURLToPath } from "url";
import { dirname, resolve } from "path";
import { defineConfig, devices } from "@playwright/test";
import dotenv from "dotenv";
/**
* Read environment variables from file.
* https://github.com/motdotla/dotenv
*/
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
dotenv.config({
path: resolve(__dirname, ".env"),
});
/**
* See https://playwright.dev/docs/test-configuration.
*/
export default defineConfig({
globalSetup: (await import("path")).resolve("./playwright-global-setup.ts"),
testDir: "./src/tests",
/* Run tests in files in parallel */
fullyParallel: true,
/* Fail the build on CI if you accidentally left test.only in the source code. */
forbidOnly: !!process.env.CI,
/* Retry on CI only */
retries: process.env.CI ? 2 : 0,
/* Opt out of parallel tests on CI. */
workers: process.env.CI ? 4 : undefined,
/* Reporter to use. See https://playwright.dev/docs/test-reporters */
reporter: process.env.CI
? [["junit", { outputFile: "results.xml" }]]
: "list",
/* Shared settings for all the projects below. See https://playwright.dev/docs/api/class-testoptions. */
use: {
/* Base URL to use in actions like `await page.goto('/')`. */
// baseURL: 'http://127.0.0.1:3000',
/* Collect trace when retrying the failed test. See https://playwright.dev/docs/trace-viewer */
trace: "on-first-retry",
...(process.env.CI
? {
headless: true, // Run in headless mode
viewport: { width: 1280, height: 720 }, // Set a smaller viewport
ignoreHTTPSErrors: true, // Ignore HTTPS errors
video: "off", // Disable video recording
screenshot: "off", // Disable screenshots
trace: "off", // Disable tracing
}
: {}),
},
/* Configure projects for major browsers */
projects: [
{
name: "chromium",
use: { ...devices["Desktop Chrome"] },
},
{
name: "firefox",
use: { ...devices["Desktop Firefox"] },
},
{
name: "webkit",
use: { ...devices["Desktop Safari"] },
},
/* Test against mobile viewports. */
// {
// name: 'Mobile Chrome',
// use: { ...devices['Pixel 5'] },
// },
// {
// name: 'Mobile Safari',
// use: { ...devices['iPhone 12'] },
// },
/* Test against branded browsers. */
// {
// name: 'Microsoft Edge',
// use: { ...devices['Desktop Edge'], channel: 'msedge' },
// },
// {
// name: 'Google Chrome',
// use: { ...devices['Desktop Chrome'], channel: 'chrome' },
// },
],
/* Run your local dev server before starting the tests */
// webServer: {
// command: 'npm run start',
// url: 'http://127.0.0.1:3000',
// reuseExistingServer: !process.env.CI,
// },
});
| yannbf/purchases-js-repro | 0 | TypeScript | yannbf | Yann Braga | chromaui | |
examples/webbilling-demo/src/App.css | CSS | :root {
font-family:
-apple-system,
BlinkMacSystemFont,
avenir next,
avenir,
segoe ui,
helvetica neue,
helvetica,
Cantarell,
Ubuntu,
roboto,
noto,
arial,
sans-serif;
line-height: 1.5;
font-weight: 400;
color-scheme: light dark;
color: #000000;
background-color: #ffffff;
font-synthesis: none;
text-rendering: optimizeLegibility;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
-webkit-text-size-adjust: 100%;
--color-green: #b4fab7;
--color-grey-ui-dark: #dfdfdf;
--color-purple: #9c4eff;
--color-shade-1: #d8b9ff;
--color-shade-2: #ffcdc2;
--color-shade-3: #ffc1cc;
}
h1,
h2,
p {
font-weight: 500;
margin: 0px;
}
#root {
width: 100%;
}
a {
color: #646cff;
text-decoration: inherit;
}
a:hover {
color: #535bf2;
}
body {
margin: 0;
}
button.button {
font-family:
-apple-system,
BlinkMacSystemFont,
avenir next,
avenir,
segoe ui,
helvetica neue,
helvetica,
Cantarell,
Ubuntu,
roboto,
noto,
arial,
sans-serif;
display: inline-block;
box-sizing: border-box;
width: 240px;
height: 64px;
font-size: 16px;
line-height: 16px;
padding: auto;
border-radius: 32px;
border: 1px solid transparent;
font-weight: 500;
background-color: var(--color-green);
color: #000000;
cursor: pointer;
transition: border-color 0.25s;
}
button.button:hover {
border-color: #00000080;
}
button.button:focus,
button.button:focus-visible {
outline: 4px auto -webkit-focus-ring-color;
}
.landing {
max-width: 1400px;
margin: auto;
padding-left: 64px;
padding-right: 64px;
box-sizing: border-box;
margin-top: 54px;
display: flex;
}
.landingMain {
margin-top: 170px;
}
.landing h1 {
font-weight: 500;
font-size: 68px;
line-height: 110%;
margin-top: 48px;
margin-bottom: 32px;
}
.landing h2 {
font-size: 24px;
font-weight: 500;
margin-bottom: 48px;
}
.screenshot img {
width: 696px;
}
.login {
width: 778px;
margin: auto;
height: 100vh;
display: flex;
flex-direction: column;
justify-content: center;
}
.login h1 {
font-size: 40px;
line-height: 52px;
margin-bottom: 16px;
}
.login h2 {
font-size: 24px;
line-height: 31px;
margin-bottom: 48px;
}
.login form {
display: flex;
gap: 16px;
}
.login form input {
display: block;
box-sizing: border-box;
border: 4px solid var(--color-grey-ui-dark);
font-size: 24px;
line-height: 24px;
height: 64px;
padding: 16px 20px;
flex: 1;
border-radius: 16px;
}
.notice {
color: var(--color-purple);
font-weight: 500;
margin-top: 48px;
}
.paywall {
max-width: 972px;
padding: 32px;
margin: auto;
}
.paywall h1 {
margin-top: 120px;
margin-bottom: 72px;
font-size: 52px;
line-height: 118.2%;
text-align: center;
}
.paywall h1 em {
font-weight: 500;
font-variant: normal;
font-style: normal;
display: block;
color: var(--color-purple);
}
.packages {
display: flex;
flex-direction: row;
overflow-x: auto;
padding-bottom: 24px;
gap: 16px;
width: 100%;
justify-content: center;
}
.packages .card:nth-child(3n) {
background-color: var(--color-shade-1);
}
.packages .card:nth-child(3n + 1) {
background-color: var(--color-shade-2);
}
.packages .card:nth-child(3n + 2) {
background-color: var(--color-shade-3);
}
.card {
width: 308px;
padding-top: 56px;
padding-bottom: 32px;
display: flex;
flex-direction: column;
border-radius: 24px;
text-align: center;
overflow: hidden;
cursor: pointer;
font-weight: 500;
font-size: 24px;
}
.previousPrice {
text-decoration: line-through;
height: 36px;
}
.currentPrice {
font-size: 40px;
line-height: 40px;
height: 80px;
margin-top: 2px;
margin-bottom: 2px;
display: flex;
flex-wrap: wrap;
justify-content: center;
align-items: center;
}
.packageCTA {
margin-top: 34px;
}
.freeTrial {
background: var(--color-purple);
color: white;
}
.paywall .notice {
text-align: center;
}
.card button.button {
max-width: calc(100% - 32px);
}
.success {
display: flex;
flex-direction: column;
align-items: center;
margin-top: 224px;
margin-left: 32px;
margin-bottom: 32px;
}
.success h1 {
margin-top: 48px;
margin-bottom: 32px;
font-size: 68px;
line-height: 74px;
text-align: center;
}
.success h2 {
font-size: 24px;
line-height: 31px;
margin-bottom: 56px;
text-align: center;
}
.storeButtons {
display: flex;
flex-direction: row;
justify-content: center;
flex-wrap: wrap;
gap: 16px;
}
.storeButtons svg {
width: 270px;
height: 80px;
}
.logoutButton {
display: block;
position: absolute;
right: 32px;
top: 32px;
background-color: var(--color-grey-ui-dark);
border: none;
outline: none;
font-family:
-apple-system,
BlinkMacSystemFont,
avenir next,
avenir,
segoe ui,
helvetica neue,
helvetica,
Cantarell,
Ubuntu,
roboto,
noto,
arial,
sans-serif;
font-weight: 500;
font-size: 12px;
line-height: 12px;
padding: 6px 12px;
border-radius: 12px;
}
@media (max-width: 1300px) {
.landingMain {
margin-top: 64px;
}
.screenshot img {
width: 464px;
}
}
@media (max-width: 1000px) {
.landing {
flex-direction: column;
width: 100%;
padding: 0px;
margin: 0px;
box-sizing: border-box;
}
.landingMain {
margin: 32px;
text-align: center;
}
.landing h1 {
font-size: 32px;
}
.landing h2 {
font-size: 16px;
}
.screenshot {
text-align: center;
max-width: 100%;
}
.screenshot img {
width: 100vw;
max-width: 696px;
}
.login {
box-sizing: border-box;
width: 100%;
max-width: 842px;
padding-left: 32px;
padding-right: 32px;
}
.login form {
flex-direction: column;
align-items: center;
}
.login form input {
width: 100%;
}
.notice {
text-align: center;
}
.success {
margin: 32px;
margin-top: 96px;
}
.success h1 {
font-size: 40px;
line-height: 48px;
margin-top: 32px;
}
.success h2 {
font-size: 20px;
line-height: 24px;
margin-bottom: 32px;
}
.storeButtons svg {
width: 216px;
height: 64px;
}
}
@media (max-width: 600px) {
.paywall h1 {
margin-top: 32px;
margin-bottom: 32px;
font-size: 32px;
}
.paywall h1 em {
display: inline;
}
.packages {
flex-direction: column;
}
.card {
box-sizing: border-box;
width: 100%;
margin-right: 0px;
margin-bottom: 20px;
}
}
| yannbf/purchases-js-repro | 0 | TypeScript | yannbf | Yann Braga | chromaui | |
examples/webbilling-demo/src/App.tsx | TypeScript (TSX) | import {
RouterProvider,
createBrowserRouter,
redirect,
} from "react-router-dom";
import "./App.css";
import WithEntitlement from "./components/WithEntitlement";
import WithoutEntitlement from "./components/WithoutEntitlement";
import LoginPage from "./pages/login";
import LandingPage from "./pages/landingPage";
import PaywallPage from "./pages/paywall";
import SuccessPage from "./pages/success";
import { loadPurchases } from "./util/PurchasesLoader";
import RCPaywallPage from "./pages/rc_paywall";
const router = createBrowserRouter([
{
path: "/",
element: <LandingPage />,
},
{
path: "/login",
element: <LoginPage />,
},
{
path: "/logout",
loader: () => {
throw redirect("/");
},
},
{
path: "/paywall/:app_user_id",
loader: loadPurchases,
element: (
<WithoutEntitlement>
<PaywallPage />
</WithoutEntitlement>
),
},
{
path: "/rc_paywall/:app_user_id",
loader: loadPurchases,
element: (
<WithoutEntitlement>
<RCPaywallPage />
</WithoutEntitlement>
),
},
{
path: "/success/:app_user_id",
loader: loadPurchases,
element: (
<WithEntitlement>
<SuccessPage />
</WithEntitlement>
),
},
]);
const App = () => <RouterProvider router={router} />;
export default App;
| yannbf/purchases-js-repro | 0 | TypeScript | yannbf | Yann Braga | chromaui | |
examples/webbilling-demo/src/Loader/index.tsx | TypeScript (TSX) | import React, { useEffect, useState } from "react";
import cat from "./nyan-cat.gif";
const randomSentences = [
"Asking ChatGPT to feed our crypto-cats",
"Cleaning the cat litter in the meta-verse",
"Preparing the automated laser pointers",
"Uselessly calculating 1000 Fibonacci numbers",
];
const getRandomSentence = () => {
return randomSentences[Math.floor(Math.random() * randomSentences.length)];
};
const Loader: React.FC = () => {
const [sentence, setSentence] = useState(getRandomSentence());
useEffect(() => {
setTimeout(() => {
setSentence(getRandomSentence());
}, 3000);
}, []);
return (
<div
className={"card"}
style={{ background: "#014379", maxWidth: "300px", padding: "0px" }}
>
<div style={{ height: "50px", background: "black" }}>
<h4 style={{ marginTop: "0", paddingTop: "10px" }}>Loading...</h4>
</div>
<img src={cat} style={{ maxWidth: "300px" }} alt={"Loading..."} />
<div style={{ height: "70px", background: "black" }}>
<h4 style={{ marginTop: "0", paddingTop: "10px" }}>{sentence}</h4>
</div>
</div>
);
};
export default Loader;
export const FullPageLoader: React.FC = () => {
return (
<div
style={{
background: "rgba(0,0,0,0.6)",
zIndex: 999,
position: "fixed",
top: 0,
left: 0,
width: "100%",
height: "100%",
}}
>
<div
style={{
display: "flex",
alignItems: "center",
justifyContent: "center",
width: "100%",
height: "100%",
margin: "auto",
}}
>
<Loader />
</div>
</div>
);
};
| yannbf/purchases-js-repro | 0 | TypeScript | yannbf | Yann Braga | chromaui | |
examples/webbilling-demo/src/components/AppLogo.tsx | TypeScript (TSX) | const AppLogo = () => (
<svg
width="120"
height="120"
viewBox="0 0 120 120"
fill="none"
xmlns="http://www.w3.org/2000/svg"
>
<rect width="120" height="120" rx="24" fill="black" />
<path
d="M8 24C8 15.1634 15.1634 8 24 8H32C36.4183 8 40 11.5817 40 16V32C40 36.4183 36.4183 40 32 40H16C11.5817 40 8 36.4183 8 32V24Z"
fill="#B4FAB7"
/>
<rect x="8" y="44" width="32" height="32" rx="8" fill="#D8B9FF" />
<path
d="M8 88C8 83.5817 11.5817 80 16 80H32C36.4183 80 40 83.5817 40 88V104C40 108.418 36.4183 112 32 112H24C15.1634 112 8 104.837 8 96V88Z"
fill="#FFDFBA"
/>
<rect x="44" y="8" width="32" height="32" rx="8" fill="#DFDFDF" />
<rect x="44" y="44" width="32" height="32" rx="8" fill="#B5FFE4" />
<rect x="44" y="80" width="32" height="32" rx="8" fill="#C3F1FF" />
<path
d="M80 16C80 11.5817 83.5817 8 88 8H96C104.837 8 112 15.1634 112 24V32C112 36.4183 108.418 40 104 40H88C83.5817 40 80 36.4183 80 32V16Z"
fill="#FFCDC2"
/>
<rect x="80" y="44" width="32" height="32" rx="8" fill="#FFC1CC" />
<g clipPath="url(#clip0_2327_4342)">
<path
d="M104.5 90C101.89 90.7 98.83 91 96 91C93.17 91 90.11 90.7 87.5 90L87 92C88.86 92.5 91 92.83 93 93V106H95V100H97V106H99V93C101 92.83 103.14 92.5 105 92L104.5 90ZM96 90C97.1 90 98 89.1 98 88C98 86.9 97.1 86 96 86C94.9 86 94 86.9 94 88C94 89.1 94.9 90 96 90Z"
fill="white"
/>
</g>
<defs>
<clipPath id="clip0_2327_4342">
<rect
width="24"
height="24"
fill="white"
transform="translate(84 84)"
/>
</clipPath>
</defs>
</svg>
);
export default AppLogo;
| yannbf/purchases-js-repro | 0 | TypeScript | yannbf | Yann Braga | chromaui | |
examples/webbilling-demo/src/components/AppStoreButton.tsx | TypeScript (TSX) | const AppStoreButton = () => (
<svg
width="270"
height="80"
viewBox="0 0 270 80"
fill="none"
xmlns="http://www.w3.org/2000/svg"
>
<g clipPath="url(#clip0_2356_9736)">
<path
d="M248.499 0.00026H21.5133C20.6859 0.00026 19.8684 0.00026 19.0432 0.00426C18.3524 0.00826 17.6672 0.01988 16.9698 0.02966C15.4547 0.0454636 13.9431 0.163613 12.4483 0.38308C10.9556 0.607325 9.50963 1.03009 8.15934 1.63708C6.81069 2.2492 5.57839 3.0446 4.50715 3.9944C3.43028 4.94153 2.53263 6.03629 1.84871 7.23658C1.16291 8.43448 0.687365 9.71814 0.438515 11.0432C0.187299 12.3666 0.0521173 13.7053 0.0341832 15.0472C0.0132446 15.6604 0.0110334 16.2757 0 16.8889V63.1175C0.0110334 63.7385 0.0132446 64.3401 0.0341832 64.9613C0.0521228 66.3031 0.187304 67.6417 0.438515 68.9651C0.686678 70.2909 1.16225 71.5753 1.84871 72.7737C2.53232 73.9701 3.4301 75.0604 4.50715 76.0023C5.57433 76.9563 6.80742 77.7522 8.15934 78.3597C9.50962 78.9683 10.9554 79.3936 12.4483 79.6213C13.9434 79.839 15.4548 79.9572 16.9698 79.9749C17.6672 79.9885 18.3524 79.9963 19.0432 79.9963C19.8684 80.0003 20.6859 80.0003 21.5133 80.0003H248.499C249.31 80.0003 250.134 80.0003 250.945 79.9963C251.632 79.9963 252.337 79.9885 253.025 79.9749C254.537 79.9581 256.045 79.8399 257.537 79.6213C259.035 79.392 260.486 78.9668 261.843 78.3597C263.194 77.7519 264.426 76.956 265.492 76.0023C266.566 75.0567 267.466 73.9672 268.158 72.7737C268.839 71.5744 269.31 70.2901 269.555 68.9651C269.806 67.6415 269.946 66.3032 269.974 64.9613C269.982 64.3401 269.982 63.7385 269.982 63.1175C270 62.3909 270 61.6683 270 60.9299V19.0725C270 18.3401 270 17.6135 269.982 16.8889C269.982 16.2757 269.982 15.6604 269.974 15.0471C269.946 13.7051 269.806 12.3667 269.555 11.0431C269.31 9.71882 268.839 8.43527 268.158 7.2365C266.765 4.83065 264.557 2.87231 261.843 1.6369C260.486 1.03139 259.035 0.608741 257.537 0.3829C256.046 0.162466 254.537 0.0442755 253.025 0.02938C252.337 0.01962 251.632 0.0079 250.945 0.004C250.134 0 249.31 0.00026 248.499 0.00026Z"
fill="#A6A6A6"
/>
<path
d="M19.0541 78.25C18.3667 78.25 17.6958 78.2422 17.0138 78.2286C15.6008 78.2123 14.1912 78.1032 12.7964 77.9024C11.4958 77.7039 10.236 77.3345 9.05828 76.8066C7.89141 76.283 6.82713 75.5965 5.90621 74.7734C4.97196 73.9599 4.19415 73.0165 3.60362 71.9804C3.00657 70.9376 2.59338 69.8198 2.37844 68.666C2.14632 67.4262 2.02073 66.1726 2.00276 64.916C1.98845 64.4942 1.96973 63.0898 1.96973 63.0898V16.8887C1.96973 16.8887 1.98967 15.5059 2.00287 15.0996C2.02008 13.845 2.14493 12.5933 2.37636 11.3555C2.5917 10.1985 3.00521 9.0775 3.60258 8.03126C4.19095 6.99589 4.96443 6.05172 5.89305 5.23536C6.82063 4.41124 7.88832 3.72121 9.05718 3.19042C10.2321 2.66419 11.4897 2.29747 12.7876 2.10254C14.187 1.89967 15.6015 1.78999 17.0193 1.77442L19.0553 1.75H250.934L252.994 1.7754C254.399 1.7902 255.8 1.8989 257.187 2.10058C258.498 2.29795 259.769 2.66723 260.957 3.19628C263.299 4.26597 265.204 5.95833 266.406 8.03614C266.994 9.07516 267.401 10.187 267.614 11.334C267.848 12.582 267.979 13.8435 268.006 15.1084C268.012 15.6748 268.012 16.2832 268.012 16.8887C268.03 17.6387 268.03 18.3525 268.03 19.0723V60.9296C268.03 61.6562 268.03 62.3652 268.012 63.08C268.012 63.7304 268.012 64.3262 268.004 64.9394C267.977 66.1818 267.848 67.4207 267.618 68.6464C267.407 69.8085 266.996 70.935 266.4 71.9864C265.805 73.0112 265.031 73.9465 264.108 74.7578C263.186 75.5854 262.12 76.2759 260.951 76.8028C259.765 77.3348 258.497 77.7055 257.187 77.9024C255.792 78.1043 254.383 78.2134 252.97 78.2286C252.309 78.2422 251.617 78.25 250.945 78.25L248.499 78.254L19.0541 78.25Z"
fill="black"
/>
<path
d="M64.5377 40.6026C64.5592 38.9333 65.0027 37.2965 65.8267 35.8446C66.6508 34.3927 67.8287 33.1728 69.2509 32.2985C68.3474 31.0082 67.1555 29.9463 65.7698 29.1972C64.3842 28.4481 62.8429 28.0324 61.2685 27.9831C57.9101 27.6306 54.6542 29.9928 52.9427 29.9928C51.1982 29.9928 48.5632 28.0181 45.7257 28.0765C43.8904 28.1358 42.1017 28.6695 40.5339 29.6256C38.9662 30.5817 37.6728 31.9277 36.7799 33.5323C32.9119 40.2291 35.7971 50.0712 39.5023 55.4844C41.3561 58.1351 43.5227 61.096 46.3576 60.991C49.1317 60.876 50.1678 59.222 53.5164 59.222C56.8339 59.222 57.8059 60.991 60.6984 60.9243C63.6751 60.8759 65.5506 58.2618 67.3394 55.586C68.6713 53.6973 69.6963 51.6098 70.3762 49.401C68.6468 48.6695 67.171 47.4451 66.1327 45.8805C65.0945 44.316 64.5398 42.4804 64.5377 40.6026Z"
fill="white"
/>
<path
d="M59.0744 24.4226C60.6975 22.4742 61.4971 19.9699 61.3035 17.4414C58.8238 17.7018 56.5333 18.887 54.8883 20.7606C54.084 21.676 53.468 22.7408 53.0755 23.8944C52.683 25.0479 52.5217 26.2675 52.6009 27.4834C53.8412 27.4962 55.0682 27.2274 56.1895 26.6972C57.3108 26.167 58.2972 25.3893 59.0744 24.4226Z"
fill="white"
/>
<path
d="M99.6045 54.2794H90.1377L87.8643 60.9922H83.8545L92.8213 36.1562H96.9873L105.954 60.9922H101.876L99.6045 54.2794ZM91.1182 51.1817H98.6222L94.9229 40.2872H94.8194L91.1182 51.1817Z"
fill="white"
/>
<path
d="M125.319 51.9389C125.319 57.5659 122.308 61.1811 117.763 61.1811C116.611 61.2413 115.466 60.9761 114.459 60.4158C113.451 59.8555 112.622 59.0229 112.065 58.0131H111.979V66.9818H108.263V42.8842H111.86V45.8959H111.929C112.511 44.891 113.354 44.0626 114.369 43.4989C115.385 42.9352 116.534 42.6573 117.694 42.6947C122.29 42.6948 125.319 46.3276 125.319 51.9389ZM121.499 51.9389C121.499 48.2729 119.605 45.8627 116.714 45.8627C113.874 45.8627 111.964 48.3237 111.964 51.9389C111.964 55.5873 113.874 58.0307 116.714 58.0307C119.605 58.0307 121.499 55.6381 121.499 51.9389Z"
fill="white"
/>
<path
d="M145.249 51.9389C145.249 57.5658 142.237 61.1811 137.692 61.1811C136.541 61.2413 135.396 60.9761 134.389 60.4158C133.381 59.8555 132.552 59.0228 131.995 58.0131H131.909V66.9818H128.192V42.8842H131.79V45.8959H131.858C132.44 44.891 133.284 44.0626 134.299 43.4989C135.314 42.9352 136.463 42.6573 137.624 42.6947C142.22 42.6947 145.249 46.3275 145.249 51.9389ZM141.429 51.9389C141.429 48.2729 139.534 45.8627 136.644 45.8627C133.804 45.8627 131.894 48.3236 131.894 51.9389C131.894 55.5873 133.804 58.0307 136.644 58.0307C139.534 58.0307 141.429 55.6381 141.429 51.9389Z"
fill="white"
/>
<path
d="M158.421 54.0724C158.696 56.5353 161.089 58.1524 164.358 58.1524C167.491 58.1524 169.745 56.5352 169.745 54.3145C169.745 52.3867 168.386 51.2325 165.167 50.4414L161.948 49.666C157.388 48.5645 155.271 46.4316 155.271 42.9707C155.271 38.6855 159.005 35.7422 164.308 35.7422C169.556 35.7422 173.153 38.6855 173.274 42.9707H169.522C169.298 40.4922 167.249 38.9961 164.255 38.9961C161.261 38.9961 159.212 40.5098 159.212 42.7129C159.212 44.4688 160.521 45.502 163.722 46.2929L166.458 46.9648C171.554 48.1699 173.671 50.2168 173.671 53.8495C173.671 58.496 169.97 61.4062 164.083 61.4062C158.575 61.4062 154.856 58.5644 154.616 54.0722L158.421 54.0724Z"
fill="white"
/>
<path
d="M181.692 38.5996V42.8848H185.136V45.8281H181.692V55.8105C181.692 57.3613 182.382 58.084 183.895 58.084C184.304 58.0769 184.712 58.0482 185.118 57.998V60.9238C184.438 61.0509 183.746 61.1085 183.054 61.0956C179.388 61.0956 177.958 59.7187 177.958 56.207V45.8281H175.325V42.8848H177.958V38.5996H181.692Z"
fill="white"
/>
<path
d="M187.13 51.9394C187.13 46.2422 190.485 42.6621 195.718 42.6621C200.968 42.6621 204.308 46.2421 204.308 51.9394C204.308 57.6523 200.985 61.2168 195.718 61.2168C190.452 61.2168 187.13 57.6523 187.13 51.9394ZM200.52 51.9394C200.52 48.0312 198.729 45.7246 195.718 45.7246C192.706 45.7246 190.917 48.0488 190.917 51.9394C190.917 55.8633 192.706 58.1523 195.718 58.1523C198.729 58.1523 200.52 55.8633 200.52 51.9394Z"
fill="white"
/>
<path
d="M207.372 42.884H210.917V45.966H211.003C211.243 45.0035 211.807 44.1528 212.6 43.557C213.393 42.9613 214.367 42.6567 215.358 42.6946C215.787 42.6931 216.214 42.7396 216.632 42.8332V46.3098C216.091 46.1446 215.527 46.0687 214.962 46.0852C214.422 46.0633 213.884 46.1585 213.384 46.3643C212.884 46.57 212.435 46.8815 212.067 47.2773C211.699 47.6731 211.421 48.1438 211.252 48.6571C211.083 49.1705 211.028 49.7143 211.089 50.2512V60.9914H207.372L207.372 42.884Z"
fill="white"
/>
<path
d="M233.769 55.6738C233.269 58.9609 230.067 61.2168 225.972 61.2168C220.704 61.2168 217.435 57.6875 217.435 52.0254C217.435 46.3457 220.722 42.6621 225.815 42.6621C230.825 42.6621 233.976 46.1035 233.976 51.5937V52.8672H221.187V53.0918C221.128 53.7582 221.211 54.4295 221.431 55.0612C221.652 55.6929 222.004 56.2705 222.465 56.7555C222.925 57.2406 223.484 57.6222 224.103 57.8748C224.723 58.1274 225.389 58.2453 226.058 58.2207C226.936 58.303 227.817 58.0996 228.571 57.6407C229.324 57.1818 229.909 56.492 230.239 55.6738L233.769 55.6738ZM221.204 50.2695H230.257C230.29 49.6703 230.199 49.0707 229.99 48.5083C229.781 47.9459 229.457 47.4328 229.04 47.0013C228.623 46.5697 228.121 46.2291 227.567 46.0006C227.012 45.7722 226.415 45.6609 225.815 45.6738C225.21 45.6702 224.61 45.7865 224.05 46.016C223.49 46.2455 222.981 46.5836 222.552 47.0109C222.123 47.4381 221.784 47.9461 221.552 48.5054C221.321 49.0647 221.203 49.6643 221.204 50.2695Z"
fill="white"
/>
<path
d="M90.6523 17.4608C91.4316 17.4049 92.2135 17.5226 92.9417 17.8055C93.6699 18.0883 94.3263 18.5293 94.8635 19.0966C95.4006 19.6638 95.8052 20.3432 96.048 21.0857C96.2908 21.8283 96.3658 22.6155 96.2676 23.3905C96.2676 27.203 94.207 29.3945 90.6523 29.3945H86.3418V17.4608H90.6523ZM88.1953 27.7068H90.4453C91.0021 27.7401 91.5593 27.6488 92.0764 27.4396C92.5935 27.2303 93.0574 26.9084 93.4344 26.4973C93.8114 26.0862 94.0919 25.5962 94.2557 25.0629C94.4194 24.5297 94.4622 23.9667 94.3808 23.4148C94.4563 22.8651 94.4092 22.3056 94.2429 21.7763C94.0767 21.2469 93.7954 20.7609 93.4193 20.3531C93.0432 19.9452 92.5815 19.6256 92.0673 19.4171C91.5532 19.2087 90.9993 19.1165 90.4453 19.1472H88.1953V27.7068Z"
fill="white"
/>
<path
d="M98.3614 24.8876C98.3048 24.2958 98.3725 23.6986 98.5602 23.1345C98.7478 22.5704 99.0514 22.0517 99.4512 21.6117C99.8511 21.1717 100.339 20.8202 100.882 20.5797C101.426 20.3391 102.014 20.2148 102.608 20.2148C103.203 20.2148 103.791 20.3391 104.335 20.5797C104.878 20.8202 105.366 21.1717 105.766 21.6117C106.166 22.0517 106.469 22.5704 106.657 23.1345C106.844 23.6986 106.912 24.2958 106.856 24.8876C106.913 25.48 106.846 26.078 106.659 26.6431C106.472 27.2081 106.169 27.7277 105.769 28.1686C105.369 28.6094 104.881 28.9617 104.337 29.2027C103.792 29.4438 103.204 29.5683 102.608 29.5683C102.013 29.5683 101.425 29.4438 100.88 29.2027C100.336 28.9617 99.8483 28.6094 99.4483 28.1686C99.0483 27.7277 98.745 27.2081 98.5578 26.6431C98.3706 26.078 98.3037 25.48 98.3614 24.8876ZM105.027 24.8876C105.027 22.9355 104.15 21.7939 102.611 21.7939C101.066 21.7939 100.197 22.9355 100.197 24.8876C100.197 26.8554 101.067 27.9882 102.611 27.9882C104.15 27.9882 105.027 26.8476 105.027 24.8876Z"
fill="white"
/>
<path
d="M118.146 29.3945H116.303L114.441 22.7617H114.301L112.447 29.3945H110.621L108.139 20.3887H109.941L111.555 27.2607H111.688L113.539 20.3887H115.244L117.096 27.2607H117.236L118.842 20.3887H120.619L118.146 29.3945Z"
fill="white"
/>
<path
d="M122.707 20.3878H124.418V21.8184H124.551C124.776 21.3046 125.156 20.8739 125.638 20.5862C126.12 20.2986 126.679 20.1685 127.238 20.2139C127.676 20.181 128.116 20.2471 128.526 20.4073C128.935 20.5675 129.303 20.8177 129.602 21.1393C129.902 21.461 130.125 21.846 130.255 22.2656C130.385 22.6852 130.42 23.1288 130.355 23.5635V29.3935H128.578V24.0099C128.578 22.5626 127.949 21.8429 126.635 21.8429C126.337 21.829 126.04 21.8796 125.764 21.9913C125.488 22.103 125.239 22.273 125.035 22.4898C124.831 22.7065 124.676 22.9649 124.581 23.2472C124.486 23.5294 124.453 23.8289 124.484 24.1251V29.3936H122.707L122.707 20.3878Z"
fill="white"
/>
<path d="M133.188 16.873H134.965V29.3945H133.188V16.873Z" fill="white" />
<path
d="M137.436 24.8878C137.379 24.2959 137.447 23.6987 137.634 23.1346C137.822 22.5704 138.126 22.0517 138.526 21.6117C138.926 21.1718 139.413 20.8202 139.957 20.5797C140.501 20.3391 141.089 20.2148 141.683 20.2148C142.278 20.2148 142.866 20.3391 143.409 20.5797C143.953 20.8202 144.441 21.1718 144.841 21.6117C145.241 22.0517 145.544 22.5704 145.732 23.1346C145.92 23.6987 145.987 24.2959 145.931 24.8878C145.988 25.4802 145.921 26.0782 145.734 26.6433C145.547 27.2083 145.243 27.7279 144.843 28.1687C144.443 28.6096 143.956 28.9618 143.411 29.2029C142.867 29.4439 142.278 29.5685 141.683 29.5685C141.088 29.5685 140.499 29.4439 139.955 29.2029C139.411 28.9618 138.923 28.6096 138.523 28.1687C138.123 27.7279 137.819 27.2083 137.632 26.6433C137.445 26.0782 137.378 25.4802 137.436 24.8878ZM144.102 24.8878C144.102 22.9356 143.225 21.794 141.686 21.794C140.141 21.794 139.272 22.9356 139.272 24.8878C139.272 26.8556 140.141 27.9884 141.686 27.9884C143.225 27.9883 144.102 26.8477 144.102 24.8878Z"
fill="white"
/>
<path
d="M147.802 26.8476C147.802 25.2265 149.009 24.292 151.151 24.1592L153.591 24.0185V23.2412C153.591 22.29 152.962 21.7529 151.747 21.7529C150.755 21.7529 150.067 22.1172 149.87 22.7539H148.149C148.331 21.207 149.786 20.2148 151.829 20.2148C154.087 20.2148 155.36 21.3388 155.36 23.2412V29.3945H153.649V28.1289H153.509C153.223 28.5829 152.823 28.953 152.347 29.2014C151.872 29.4498 151.339 29.5677 150.804 29.5429C150.426 29.5822 150.044 29.5419 149.682 29.4245C149.32 29.3071 148.988 29.1152 148.705 28.8613C148.422 28.6074 148.195 28.297 148.04 27.9502C147.884 27.6033 147.803 27.2277 147.802 26.8476ZM153.591 26.0781V25.3252L151.392 25.4658C150.151 25.5488 149.589 25.9707 149.589 26.7646C149.589 27.5752 150.292 28.0468 151.259 28.0468C151.542 28.0755 151.828 28.0469 152.1 27.9627C152.372 27.8786 152.625 27.7405 152.842 27.5568C153.06 27.3732 153.238 27.1476 153.367 26.8935C153.495 26.6395 153.572 26.3622 153.591 26.0781Z"
fill="white"
/>
<path
d="M157.696 24.8877C157.696 22.042 159.159 20.2393 161.435 20.2393C161.997 20.2134 162.556 20.3482 163.045 20.6279C163.534 20.9077 163.933 21.3209 164.196 21.8193H164.329V16.873H166.106V29.3945H164.403V27.9717H164.263C163.979 28.4666 163.566 28.8747 163.068 29.1517C162.569 29.4286 162.004 29.564 161.435 29.5429C159.144 29.543 157.696 27.7403 157.696 24.8877ZM159.532 24.8877C159.532 26.7979 160.433 27.9473 161.939 27.9473C163.437 27.9473 164.362 26.7813 164.362 24.8955C164.362 23.0186 163.427 21.836 161.939 21.836C160.442 21.836 159.532 22.9932 159.532 24.8877Z"
fill="white"
/>
<path
d="M173.46 24.8876C173.403 24.2958 173.471 23.6986 173.659 23.1345C173.846 22.5704 174.15 22.0517 174.55 21.6117C174.95 21.1717 175.437 20.8202 175.981 20.5797C176.525 20.3391 177.113 20.2148 177.707 20.2148C178.302 20.2148 178.89 20.3391 179.433 20.5797C179.977 20.8202 180.464 21.1717 180.864 21.6117C181.264 22.0517 181.568 22.5704 181.755 23.1345C181.943 23.6986 182.011 24.2958 181.954 24.8876C182.012 25.48 181.945 26.078 181.758 26.6431C181.571 27.2081 181.267 27.7277 180.867 28.1686C180.467 28.6094 179.979 28.9617 179.435 29.2027C178.891 29.4438 178.302 29.5683 177.707 29.5683C177.112 29.5683 176.523 29.4438 175.979 29.2027C175.435 28.9617 174.947 28.6094 174.547 28.1686C174.147 27.7277 173.844 27.2081 173.656 26.6431C173.469 26.078 173.402 25.48 173.46 24.8876ZM180.126 24.8876C180.126 22.9355 179.249 21.7939 177.71 21.7939C176.165 21.7939 175.296 22.9355 175.296 24.8876C175.296 26.8554 176.165 27.9882 177.71 27.9882C179.249 27.9882 180.126 26.8476 180.126 24.8876Z"
fill="white"
/>
<path
d="M184.339 20.3878H186.05V21.8184H186.183C186.408 21.3046 186.788 20.8739 187.27 20.5862C187.751 20.2986 188.311 20.1685 188.87 20.2139C189.308 20.181 189.748 20.2471 190.158 20.4073C190.567 20.5675 190.935 20.8177 191.234 21.1393C191.533 21.461 191.757 21.846 191.887 22.2656C192.017 22.6852 192.052 23.1288 191.987 23.5635V29.3935H190.21V24.0099C190.21 22.5626 189.581 21.8429 188.267 21.8429C187.969 21.829 187.672 21.8796 187.396 21.9913C187.12 22.103 186.871 22.273 186.667 22.4898C186.463 22.7065 186.308 22.9649 186.213 23.2472C186.118 23.5294 186.085 23.8289 186.116 24.1251V29.3936H184.339V20.3878Z"
fill="white"
/>
<path
d="M202.03 18.1465V20.4297H203.981V21.9268H202.03V26.5576C202.03 27.501 202.419 27.9141 203.304 27.9141C203.53 27.9133 203.757 27.8996 203.981 27.873V29.3535C203.662 29.4106 203.339 29.441 203.015 29.4443C201.038 29.4443 200.251 28.749 200.251 27.0127V21.9267H198.821V20.4296H200.251V18.1465H202.03Z"
fill="white"
/>
<path
d="M206.409 16.873H208.171V21.8359H208.312C208.548 21.3173 208.938 20.8841 209.43 20.5954C209.921 20.3067 210.489 20.1766 211.058 20.2227C211.493 20.1989 211.929 20.2717 212.334 20.4358C212.738 20.5999 213.102 20.8512 213.398 21.1719C213.694 21.4926 213.916 21.8747 214.048 22.291C214.179 22.7072 214.217 23.1474 214.159 23.5801V29.3945H212.38V24.0185C212.38 22.5801 211.71 21.8515 210.454 21.8515C210.149 21.8265 209.841 21.8685 209.554 21.9746C209.266 22.0807 209.005 22.2484 208.789 22.4658C208.573 22.6833 208.408 22.9454 208.303 23.2336C208.199 23.5219 208.159 23.8294 208.187 24.1347V29.3945H206.409L206.409 16.873Z"
fill="white"
/>
<path
d="M224.523 26.963C224.281 27.7861 223.758 28.4981 223.044 28.9744C222.331 29.4507 221.473 29.661 220.62 29.5685C220.027 29.5842 219.437 29.4705 218.892 29.2355C218.347 29.0004 217.86 28.6496 217.464 28.2073C217.068 27.765 216.773 27.2419 216.6 26.6743C216.427 26.1066 216.379 25.508 216.46 24.9201C216.381 24.3303 216.43 23.7304 216.603 23.1611C216.776 22.5918 217.069 22.0662 217.463 21.6201C217.856 21.1739 218.341 20.8176 218.885 20.5752C219.428 20.3327 220.017 20.2099 220.612 20.215C223.118 20.215 224.63 21.927 224.63 24.755V25.3752H218.271V25.4748C218.243 25.8053 218.284 26.1379 218.393 26.4514C218.501 26.7649 218.673 27.0523 218.899 27.2953C219.125 27.5382 219.399 27.7312 219.704 27.862C220.009 27.9928 220.337 28.0585 220.669 28.0548C221.094 28.1058 221.525 28.0293 221.906 27.8348C222.288 27.6404 222.603 27.3369 222.812 26.963L224.523 26.963ZM218.271 24.0607H222.819C222.842 23.7584 222.801 23.4548 222.699 23.1694C222.597 22.884 222.436 22.623 222.228 22.4033C222.019 22.1836 221.766 22.01 221.487 21.8936C221.207 21.7773 220.906 21.7207 220.603 21.7277C220.295 21.7238 219.99 21.7815 219.705 21.8974C219.421 22.0133 219.162 22.185 218.945 22.4025C218.727 22.6199 218.556 22.8786 218.44 23.1634C218.324 23.4482 218.267 23.7533 218.271 24.0607Z"
fill="white"
/>
</g>
<defs>
<clipPath id="clip0_2356_9736">
<rect width="270" height="80" fill="white" />
</clipPath>
</defs>
</svg>
);
export default AppStoreButton;
| yannbf/purchases-js-repro | 0 | TypeScript | yannbf | Yann Braga | chromaui | |
examples/webbilling-demo/src/components/Button.tsx | TypeScript (TSX) | import React from "react";
const Button: React.FC<{ caption: string; onClick: () => void }> = ({
caption,
onClick,
}) => {
return (
<button className="button" onClick={onClick}>
{caption}
</button>
);
};
export default Button;
| yannbf/purchases-js-repro | 0 | TypeScript | yannbf | Yann Braga | chromaui | |
examples/webbilling-demo/src/components/IChildrenProps.ts | TypeScript | import type React from "react";
interface IChildrenProps {
/**
* The inner content.
*/
children?: React.JSX.Element[] | React.JSX.Element | any; // eslint-disable-line @typescript-eslint/no-explicit-any
}
export default IChildrenProps;
| yannbf/purchases-js-repro | 0 | TypeScript | yannbf | Yann Braga | chromaui | |
examples/webbilling-demo/src/components/LogoutButton.tsx | TypeScript (TSX) | import { useNavigate } from "react-router-dom";
const LogoutButton = () => {
const navigate = useNavigate();
return (
<button className="logoutButton" onClick={() => navigate("/logout")}>
Logout
</button>
);
};
export default LogoutButton;
| yannbf/purchases-js-repro | 0 | TypeScript | yannbf | Yann Braga | chromaui | |
examples/webbilling-demo/src/components/PlayStoreButton.tsx | TypeScript (TSX) | const PlayStoreButton = () => (
<svg
width="270"
height="80"
viewBox="0 0 270 80"
fill="none"
xmlns="http://www.w3.org/2000/svg"
>
<g clipPath="url(#clip0_2359_9784)">
<path
d="M260 80H10C4.5 80 0 75.5 0 70V10C0 4.5 4.5 -1.19209e-06 10 -1.19209e-06H260C265.5 -1.19209e-06 270 4.5 270 10V70C270 75.5 265.5 80 260 80Z"
fill="#100F0D"
/>
<path
d="M260 -1.19209e-06H10C4.5 -1.19209e-06 0 4.5 0 10V70C0 75.5 4.5 80 10 80H260C265.5 80 270 75.5 270 70V10C270 4.5 265.5 -1.19209e-06 260 -1.19209e-06ZM260 1.5992C264.632 1.5992 268.4 5.368 268.4 10V70C268.4 74.632 264.632 78.4008 260 78.4008H10C5.36796 78.4008 1.60078 74.632 1.60078 70V10C1.60078 5.368 5.36796 1.5992 10 1.5992H260Z"
fill="#A2A2A1"
/>
<path
d="M94.7637 19.5762H88.9277V21.0293H93.2871C93.1699 22.2012 92.7012 23.1152 91.9277 23.7949C91.1309 24.4512 90.123 24.8027 88.9277 24.8027C87.6387 24.8027 86.5137 24.334 85.623 23.4434C84.7324 22.5059 84.2871 21.3809 84.2871 19.998C84.2871 18.6152 84.7324 17.4902 85.623 16.5527C86.5137 15.6621 87.6387 15.2168 88.9277 15.2168C89.6074 15.2168 90.2402 15.334 90.8262 15.5684C91.4121 15.8262 91.8809 16.1777 92.2559 16.623L93.3574 15.5215C92.8652 14.959 92.2324 14.5137 91.4355 14.209C90.6387 13.8809 89.8184 13.7402 88.9277 13.7402C87.1934 13.7402 85.7168 14.3262 84.5215 15.5449C83.3027 16.7402 82.6934 18.2402 82.6934 19.998C82.6934 21.7559 83.3027 23.2559 84.5215 24.4512C85.7168 25.6699 87.1934 26.2559 88.9277 26.2559C90.7559 26.2559 92.2324 25.6699 93.334 24.498C94.3418 23.4902 94.834 22.1543 94.834 20.4902C94.834 20.209 94.8105 19.9043 94.7637 19.5762ZM97.0371 13.998V25.998H104.045V24.5215H98.584V20.7246H103.506V19.2715H98.584V15.4746H104.045V13.998H97.0371ZM113.906 15.4746V13.998H105.656V15.4746H109.008V25.998H110.555V15.4746H113.906ZM121.412 13.998H119.865V25.998H121.412V13.998ZM131.607 15.4746V13.998H123.357V15.4746H126.709V25.998H128.256V15.4746H131.607ZM147.211 15.5684C146.016 14.3262 144.562 13.7402 142.828 13.7402C141.07 13.7402 139.617 14.3262 138.422 15.5449C137.227 16.7402 136.641 18.2168 136.641 19.998C136.641 21.7793 137.227 23.2559 138.422 24.4512C139.617 25.6699 141.07 26.2559 142.828 26.2559C144.539 26.2559 146.016 25.6699 147.211 24.4512C148.406 23.2559 148.992 21.7793 148.992 19.998C148.992 18.2402 148.406 16.7402 147.211 15.5684ZM139.523 16.5527C140.414 15.6621 141.516 15.2168 142.828 15.2168C144.117 15.2168 145.219 15.6621 146.086 16.5527C146.977 17.4434 147.398 18.6152 147.398 19.998C147.398 21.3809 146.977 22.5527 146.086 23.4434C145.219 24.334 144.117 24.8027 142.828 24.8027C141.516 24.8027 140.414 24.334 139.523 23.4434C138.656 22.5293 138.234 21.3809 138.234 19.998C138.234 18.6152 138.656 17.4668 139.523 16.5527ZM152.684 18.5215L152.613 16.2012H152.684L158.801 25.998H160.395V13.998H158.848V21.0293L158.918 23.3262H158.848L153.035 13.998H151.137V25.998H152.684V18.5215Z"
fill="white"
/>
<path
d="M94.7351 19.5913H88.9289V21.0289H93.2789C93.1631 22.2007 92.6945 23.1225 91.9069 23.7913C91.1195 24.4601 90.1163 24.7945 88.9289 24.7945C87.6225 24.7945 86.5163 24.3445 85.6131 23.4413C84.7257 22.5195 84.2757 21.3819 84.2757 20.0101C84.2757 18.6351 84.7257 17.4975 85.6131 16.5789C86.5163 15.6725 87.6225 15.2225 88.9289 15.2225C89.5975 15.2225 90.2319 15.3381 90.8195 15.5913C91.4039 15.8413 91.8725 16.1913 92.2413 16.6445L93.3445 15.5413C92.8445 14.9725 92.2069 14.5351 91.4225 14.2163C90.6351 13.9007 89.8131 13.7507 88.9289 13.7507C87.1881 13.7507 85.7131 14.3507 84.5101 15.5569C83.3039 16.7631 82.7007 18.2507 82.7007 20.0101C82.7007 21.7663 83.3039 23.2569 84.5101 24.4601C85.7131 25.6663 87.1881 26.2695 88.9289 26.2695C90.7507 26.2695 92.2069 25.6819 93.3289 24.4945C94.3163 23.5069 94.8195 22.1695 94.8195 20.4945C94.8195 20.2101 94.7851 19.9069 94.7351 19.5913ZM97.0483 14.0163V26.0007H104.042V24.5289H98.5859V20.7289H103.508V19.2881H98.5859V15.4913H104.042V14.0163H97.0483ZM113.897 15.4913V14.0163H105.663V15.4913H109.01V26.0007H110.547V15.4913H113.897ZM121.412 14.0163H119.874V26.0007H121.412V14.0163ZM131.597 15.4913V14.0163H123.362V15.4913H126.709V26.0007H128.247V15.4913H131.597ZM147.194 15.5725C146.006 14.3507 144.55 13.7507 142.809 13.7507C141.069 13.7507 139.612 14.3507 138.425 15.5569C137.237 16.7445 136.65 18.2351 136.65 20.0101C136.65 21.7819 137.237 23.2725 138.425 24.4601C139.612 25.6663 141.069 26.2695 142.809 26.2695C144.534 26.2695 146.006 25.6663 147.194 24.4601C148.384 23.2725 148.969 21.7819 148.969 20.0101C148.969 18.2507 148.384 16.7631 147.194 15.5725ZM139.528 16.5789C140.415 15.6725 141.503 15.2225 142.809 15.2225C144.115 15.2225 145.203 15.6725 146.075 16.5789C146.959 17.4663 147.397 18.6195 147.397 20.0101C147.397 21.3975 146.959 22.5539 146.075 23.4413C145.203 24.3445 144.115 24.7945 142.809 24.7945C141.503 24.7945 140.415 24.3445 139.528 23.4413C138.659 22.5351 138.225 21.3975 138.225 20.0101C138.225 18.6195 138.659 17.4819 139.528 16.5789ZM152.687 18.5351L152.622 16.2257H152.687L158.781 26.0007H160.387V14.0163H158.847V21.0289L158.915 23.3381H158.847L153.022 14.0163H151.15V26.0007H152.687V18.5351Z"
stroke="white"
stroke-width="0.266667"
stroke-miterlimit="10"
/>
<path
d="M213.872 60H217.604V34.9968H213.872V60ZM247.486 44.004L243.208 54.8438H243.08L238.64 44.004H234.62L241.28 59.154L237.482 67.582H241.374L251.636 44.004H247.486ZM226.32 57.1602C225.1 57.1602 223.394 56.5484 223.394 55.0368C223.394 53.107 225.518 52.3672 227.35 52.3672C228.99 52.3672 229.764 52.7204 230.76 53.2032C230.47 55.5196 228.476 57.1602 226.32 57.1602ZM226.772 43.457C224.07 43.457 221.272 44.6476 220.114 47.2852L223.426 48.668C224.134 47.2852 225.452 46.8352 226.836 46.8352C228.766 46.8352 230.728 47.9922 230.76 50.0516V50.3086C230.084 49.9226 228.636 49.3438 226.868 49.3438C223.296 49.3438 219.662 51.3054 219.662 54.9726C219.662 58.318 222.59 60.4734 225.87 60.4734C228.378 60.4734 229.764 59.3476 230.63 58.0282H230.76V59.9594H234.364V50.3726C234.364 45.9336 231.048 43.457 226.772 43.457ZM203.708 47.0476H198.4V38.4774H203.708C206.498 38.4774 208.082 40.7868 208.082 42.7624C208.082 44.7 206.498 47.0476 203.708 47.0476ZM203.612 34.9968H194.67V60H198.4V50.5274H203.612C207.748 50.5274 211.814 47.5336 211.814 42.7624C211.814 37.9922 207.748 34.9968 203.612 34.9968ZM154.849 57.1648C152.271 57.1648 150.113 55.0054 150.113 52.0422C150.113 49.0446 152.271 46.8546 154.849 46.8546C157.395 46.8546 159.392 49.0446 159.392 52.0422C159.392 55.0054 157.395 57.1648 154.849 57.1648ZM159.134 45.404H159.005C158.168 44.4054 156.556 43.5032 154.527 43.5032C150.273 43.5032 146.375 47.2414 146.375 52.0422C146.375 56.8102 150.273 60.5156 154.527 60.5156C156.556 60.5156 158.168 59.6132 159.005 58.5828H159.134V59.8062C159.134 63.0617 157.395 64.8008 154.591 64.8008C152.305 64.8008 150.887 63.1578 150.306 61.7727L147.052 63.1258C147.986 65.3805 150.466 68.1523 154.591 68.1523C158.974 68.1523 162.68 65.5742 162.68 59.2906V44.0188H159.134V45.404ZM165.258 60H168.994V34.9968H165.258V60ZM174.504 51.7516C174.408 48.4648 177.051 46.7898 178.951 46.7898C180.434 46.7898 181.689 47.5312 182.109 48.5938L174.504 51.7516ZM186.103 48.9156C185.395 47.0156 183.236 43.5032 178.822 43.5032C174.439 43.5032 170.798 46.9508 170.798 52.0094C170.798 56.7782 174.408 60.5156 179.24 60.5156C183.138 60.5156 185.395 58.132 186.33 56.746L183.43 54.8124C182.463 56.2304 181.142 57.1648 179.24 57.1648C177.34 57.1648 175.986 56.2946 175.117 54.5868L186.49 49.8828L186.103 48.9156ZM95.4876 46.1132V49.7218H104.123C103.865 51.7516 103.188 53.2336 102.157 54.2648C100.9 55.521 98.9344 56.907 95.4876 56.907C90.171 56.907 86.0148 52.6218 86.0148 47.3054C86.0148 41.989 90.171 37.7032 95.4876 37.7032C98.3554 37.7032 100.449 38.8312 101.996 40.2812L104.542 37.7352C102.383 35.6734 99.5156 34.0946 95.4876 34.0946C88.2046 34.0946 82.0828 40.0234 82.0828 47.3054C82.0828 54.5868 88.2046 60.5156 95.4876 60.5156C99.418 60.5156 102.383 59.2266 104.702 56.8102C107.087 54.4258 107.828 51.075 107.828 48.368C107.828 47.5312 107.763 46.7578 107.634 46.1132H95.4876ZM117.645 57.1648C115.067 57.1648 112.844 55.0382 112.844 52.0094C112.844 48.9484 115.067 46.8546 117.645 46.8546C120.223 46.8546 122.446 48.9484 122.446 52.0094C122.446 55.0382 120.223 57.1648 117.645 57.1648ZM117.645 43.5032C112.94 43.5032 109.106 47.0796 109.106 52.0094C109.106 56.907 112.94 60.5156 117.645 60.5156C122.349 60.5156 126.184 56.907 126.184 52.0094C126.184 47.0796 122.349 43.5032 117.645 43.5032ZM136.271 57.1648C133.695 57.1648 131.47 55.0382 131.47 52.0094C131.47 48.9484 133.695 46.8546 136.271 46.8546C138.849 46.8546 141.072 48.9484 141.072 52.0094C141.072 55.0382 138.849 57.1648 136.271 57.1648ZM136.271 43.5032C131.567 43.5032 127.734 47.0796 127.734 52.0094C127.734 56.907 131.567 60.5156 136.271 60.5156C140.977 60.5156 144.81 56.907 144.81 52.0094C144.81 47.0796 140.977 43.5032 136.271 43.5032Z"
fill="white"
/>
<path
d="M41.4344 38.8484L20.1414 61.4484C20.1422 61.4531 20.1438 61.457 20.1446 61.4617C20.7976 63.9156 23.039 65.7227 25.6992 65.7227C26.7626 65.7227 27.761 65.4352 28.6172 64.9305L28.6852 64.8906L52.6532 51.0602L41.4344 38.8484Z"
fill="#EB3131"
/>
<path
d="M62.9765 35.0008L62.9561 34.9868L52.6085 28.9882L40.9507 39.3618L52.6491 51.0586L62.9421 45.1196C64.7467 44.1454 65.9717 42.243 65.9717 40.0492C65.9717 37.8712 64.7631 35.9782 62.9765 35.0008Z"
fill="#F6B60B"
/>
<path
d="M20.1406 18.5554C20.0126 19.0274 19.9453 19.5218 19.9453 20.0352V59.9704C19.9453 60.4828 20.0118 60.9789 20.1414 61.4492L42.1672 39.4274L20.1406 18.5554Z"
fill="#5778C5"
/>
<path
d="M41.5914 40.002L52.6126 28.984L28.6718 15.1036C27.8016 14.5824 26.786 14.2816 25.6992 14.2816C23.039 14.2816 20.7946 16.0918 20.1414 18.5488C20.1406 18.5512 20.1406 18.5528 20.1406 18.555L41.5914 40.002Z"
fill="#3BAD49"
/>
</g>
<defs>
<clipPath id="clip0_2359_9784">
<rect width="270" height="80" fill="white" />
</clipPath>
</defs>
</svg>
);
export default PlayStoreButton;
| yannbf/purchases-js-repro | 0 | TypeScript | yannbf | Yann Braga | chromaui | |
examples/webbilling-demo/src/components/WithEntitlement.tsx | TypeScript (TSX) | import type { PropsWithChildren } from "react";
import React, { useEffect, useState } from "react";
import { usePurchasesLoaderData } from "../util/PurchasesLoader";
import { useNavigate } from "react-router-dom";
const WithEntitlement: React.FC<PropsWithChildren> = ({ children }) => {
const { customerInfo, purchases } = usePurchasesLoaderData();
const [isLoading, setLoading] = useState<boolean>(true);
const navigate = useNavigate();
useEffect(() => {
if (Object.keys(customerInfo.entitlements.active).length === 0) {
navigate(`/paywall/${purchases.getAppUserId()}`);
} else {
setLoading(false);
}
}, [customerInfo, purchases, navigate]);
return customerInfo && !isLoading ? <>{children}</> : null;
};
export default WithEntitlement;
| yannbf/purchases-js-repro | 0 | TypeScript | yannbf | Yann Braga | chromaui | |
examples/webbilling-demo/src/components/WithoutEntitlement.tsx | TypeScript (TSX) | import type { PropsWithChildren } from "react";
import React, { useEffect, useState } from "react";
import { usePurchasesLoaderData } from "../util/PurchasesLoader";
import { useNavigate } from "react-router-dom";
const WithoutEntitlement: React.FC<PropsWithChildren> = ({ children }) => {
const { customerInfo, purchases } = usePurchasesLoaderData();
const [isLoading, setLoading] = useState<boolean>(true);
const navigate = useNavigate();
useEffect(() => {
if (Object.keys(customerInfo.entitlements.active).length > 0) {
navigate(`/success/${purchases.getAppUserId()}`);
} else {
setLoading(false);
}
}, [customerInfo, purchases, navigate]);
return customerInfo && !isLoading ? <>{children}</> : null;
};
export default WithoutEntitlement;
| yannbf/purchases-js-repro | 0 | TypeScript | yannbf | Yann Braga | chromaui | |
examples/webbilling-demo/src/main.tsx | TypeScript (TSX) | import React from "react";
import ReactDOM from "react-dom/client";
import App from "./App.tsx";
ReactDOM.createRoot(document.getElementById("root")!).render(
<React.StrictMode>
<App />
</React.StrictMode>,
);
| yannbf/purchases-js-repro | 0 | TypeScript | yannbf | Yann Braga | chromaui | |
examples/webbilling-demo/src/pages/landingPage/index.tsx | TypeScript (TSX) | import React from "react";
import Button from "../../components/Button";
import { useNavigate } from "react-router-dom";
import AppLogo from "../../components/AppLogo";
const LandingPage: React.FC = () => {
const navigate = useNavigate();
return (
<div className="landing">
<div className="landingMain">
<div className="appLogo">
<AppLogo />
</div>
<h1>Get Smarter with Health Check</h1>
<h2>Try our Web Billing Demo Subscription Flow Today.</h2>
<Button caption="Subscribe now" onClick={() => navigate("/login")} />
</div>
<div className="screenshot">
<img src="/screenshot.png" alt="Screenshot of the app" />
</div>
</div>
);
};
export default LandingPage;
| yannbf/purchases-js-repro | 0 | TypeScript | yannbf | Yann Braga | chromaui | |
examples/webbilling-demo/src/pages/login/index.tsx | TypeScript (TSX) | import React from "react";
import Button from "../../components/Button";
import { useNavigate } from "react-router-dom";
import { Purchases } from "@revenuecat/purchases-js";
const LoginPage: React.FC = () => {
const navigate = useNavigate();
const navigateToAppUserIDPaywall = (appUserId?: string) => {
if (appUserId) {
navigate(`/paywall/${encodeURIComponent(appUserId)}`);
}
};
return (
<div className="login">
<h1>Hello! What’s your user ID?</h1>
<h2>Please enter a unique user ID to continue.</h2>
<form onSubmit={(event) => event.preventDefault()}>
<input type="text" id="app-user-id" placeholder="Your app user ID" />
<Button
caption="Continue"
onClick={() => {
const appUserId = (
document.getElementById("app-user-id") as HTMLInputElement | null
)?.value;
navigateToAppUserIDPaywall(appUserId);
}}
/>
<Button
caption="Skip"
onClick={() => {
navigateToAppUserIDPaywall(
Purchases.generateRevenueCatAnonymousAppUserId(),
);
}}
/>
</form>
<p className="notice">
In a non-demo app, you would allow customers to sign up / log in here.
</p>
</div>
);
};
export default LoginPage;
| yannbf/purchases-js-repro | 0 | TypeScript | yannbf | Yann Braga | chromaui | |
examples/webbilling-demo/src/pages/paywall/index.tsx | TypeScript (TSX) | import type { Offering, Package } from "@revenuecat/purchases-js";
import { PurchasesError } from "@revenuecat/purchases-js";
import React from "react";
import { useNavigate, useSearchParams } from "react-router-dom";
import { usePurchasesLoaderData } from "../../util/PurchasesLoader";
import Button from "../../components/Button";
import LogoutButton from "../../components/LogoutButton";
interface IPackageCardProps {
pkg: Package;
offering: Offering;
onClick: () => void;
}
const priceLabels: Record<string, string> = {
P3M: "quarter",
P1M: "mo",
P1Y: "yr",
P2M: "2mo",
P1D: "day",
PT1H: "hr",
P1W: "wk",
};
const trialLabels: Record<string, string> = {
P3D: "3 days",
P1W: "1 week",
P2W: "2 weeks",
P1M: "1 month",
P2M: "2 months",
P3M: "3 months",
P6M: "6 months",
P1Y: "1 year",
};
export const PackageCard: React.FC<IPackageCardProps> = ({
pkg,
offering,
onClick,
}) => {
const originalPriceByProduct: Record<string, string> | null =
(offering.metadata?.original_price_by_product as Record<string, string>) ??
null;
const option = pkg.webBillingProduct.defaultSubscriptionOption;
const price = option ? option.base.price : pkg.webBillingProduct.currentPrice;
const originalPrice = originalPriceByProduct
? originalPriceByProduct[pkg.webBillingProduct.identifier]
: null;
const trial = option?.trial;
return (
<div className="card">
{trial && (
<div className="freeTrial">
{trial.periodDuration &&
(trialLabels[trial.periodDuration] || trial.periodDuration)}{" "}
free trial
</div>
)}
{price && (
<>
{!trial && originalPrice && (
<div className="previousPrice">{originalPrice}</div>
)}
<div className="currentPrice">
<div>{`${price.formattedPrice}`}</div>
{pkg.webBillingProduct.normalPeriodDuration && (
<div>
/
{priceLabels[pkg.webBillingProduct.normalPeriodDuration] ||
pkg.webBillingProduct.normalPeriodDuration}
</div>
)}
</div>
<div className="productName">{pkg.webBillingProduct.displayName}</div>
<div className="packageCTA">
<Button
caption={option?.trial ? "Start Free Trial" : "Choose plan"}
onClick={onClick}
/>
</div>
</>
)}
</div>
);
};
const PaywallPage: React.FC = () => {
const navigate = useNavigate();
const { purchases, offering } = usePurchasesLoaderData();
const [searchParams] = useSearchParams();
const lang = searchParams.get("lang");
const email = searchParams.get("email");
if (!offering) {
console.error("No offering found");
return <>No offering found!</>;
}
const packages: Package[] = offering?.availablePackages || [];
if (packages.length == 0) {
console.error("No packages found in current offering.");
}
const onPackageCardClicked = async (pkg: Package) => {
if (!pkg.webBillingProduct) {
return;
}
const option = pkg.webBillingProduct.defaultSubscriptionOption;
console.log(`Purchasing with option ${option?.id}`);
// How do we complete the purchase?
try {
const { customerInfo, redemptionInfo } = await purchases.purchase({
rcPackage: pkg,
purchaseOption: option,
selectedLocale: lang || navigator.language,
customerEmail: email || undefined,
});
console.log(`CustomerInfo after purchase: ${customerInfo}`);
console.log(
`RedemptionInfo after purchase: ${JSON.stringify(redemptionInfo)}`,
);
let queryParamRedemptionInfoUrl = "";
if (redemptionInfo && redemptionInfo.redeemUrl) {
queryParamRedemptionInfoUrl = `?redeem_url=${redemptionInfo.redeemUrl}`;
}
navigate(
`/success/${purchases.getAppUserId()}${queryParamRedemptionInfoUrl}`,
);
} catch (e) {
if (e instanceof PurchasesError) {
console.log(`Error performing purchase: ${e}`);
} else {
console.error(`Unknown error: ${e}`);
}
}
};
return (
<>
<LogoutButton />
<div className="paywall">
<h1>
Subscribe today and <em>save up to 25%!</em>
</h1>
<div className="packages">
{packages.map((pkg) =>
pkg.webBillingProduct !== null ? (
<PackageCard
key={pkg.identifier}
pkg={pkg}
offering={offering}
onClick={() => onPackageCardClicked(pkg)}
/>
) : null,
)}
</div>
<div className="notice">
This is only a demo web paywall. No payment will be actually
processed.
</div>
</div>
</>
);
};
export default PaywallPage;
| yannbf/purchases-js-repro | 0 | TypeScript | yannbf | Yann Braga | chromaui | |
examples/webbilling-demo/src/pages/rc_paywall/index.tsx | TypeScript (TSX) | import type { PurchaseResult } from "@revenuecat/purchases-js";
import { Purchases } from "@revenuecat/purchases-js";
import React, { useEffect } from "react";
import { usePurchasesLoaderData } from "../../util/PurchasesLoader";
import { useNavigate, useSearchParams } from "react-router-dom";
const RCPaywallPage: React.FC = () => {
const { offering } = usePurchasesLoaderData();
const navigate = useNavigate();
const [searchParams] = useSearchParams();
const lang = searchParams.get("lang");
useEffect(() => {
const target = document.getElementById("paywall");
if (!offering || target?.innerHTML !== "") {
return;
}
const purchases = Purchases.getSharedInstance();
purchases
// @ts-expect-error This method is marked as internal for now but it's public.
.renderPaywall({
offering: offering,
htmlTarget: document.getElementById("paywall") || undefined,
selectedLocale: lang || undefined,
})
.then((purchaseResult: PurchaseResult) => {
const { customerInfo, redemptionInfo } = purchaseResult;
console.log(`CustomerInfo after purchase: ${customerInfo}`);
console.log(
`RedemptionInfo after purchase: ${JSON.stringify(redemptionInfo)}`,
);
let queryParamRedemptionInfoUrl = "";
if (redemptionInfo && redemptionInfo.redeemUrl) {
queryParamRedemptionInfoUrl = `?redeem_url=${redemptionInfo.redeemUrl}`;
}
navigate(
`/success/${purchases.getAppUserId()}${queryParamRedemptionInfoUrl}`,
);
})
.catch((err: Error) => console.log(`Error: ${err}`));
}, [offering, navigate, lang]);
if (!offering) {
console.error("No offering found");
return <>No offering found!</>;
}
return (
<>
<div id="paywall"></div>
</>
);
};
export default RCPaywallPage;
| yannbf/purchases-js-repro | 0 | TypeScript | yannbf | Yann Braga | chromaui | |
examples/webbilling-demo/src/pages/success/index.tsx | TypeScript (TSX) | import React from "react";
import AppStoreButton from "../../components/AppStoreButton";
import PlayStoreButton from "../../components/PlayStoreButton";
import AppLogo from "../../components/AppLogo";
import LogoutButton from "../../components/LogoutButton";
const SuccessPage: React.FC = () => {
const queryString = window.location.search;
const urlParams = new URLSearchParams(queryString);
const redeemUrlParam = urlParams.get("redeem_url");
return (
<>
<LogoutButton />
<div className="success">
<AppLogo />
<h1>Enjoy your premium experience.</h1>
<h2>
Now log in to the app to start using your new premium subscription.
</h2>
<div className="storeButtons">
<AppStoreButton />
<PlayStoreButton />
</div>
{redeemUrlParam && (
<>
<h5 className="description">
You are currently using an anonymous user. To save your
subscription across devices, please download the app and tap on
this link from your device.
</h5>
<a href={redeemUrlParam}>
<button className="button">Redeem</button>
</a>
</>
)}
</div>
</>
);
};
export default SuccessPage;
| yannbf/purchases-js-repro | 0 | TypeScript | yannbf | Yann Braga | chromaui | |
examples/webbilling-demo/src/tests/main.test.ts | TypeScript | import type { Browser, Page, Response, Locator } from "@playwright/test";
import test, { expect } from "@playwright/test";
const _LOCAL_URL = "http://localhost:3001/";
const CARD_SELECTOR = "div.card";
const PACKAGE_SELECTOR = "button.rc-pw-package";
const RC_PAYWALL_TEST_OFFERING_ID = "rc_paywalls_e2e_test_2";
const RC_PAYWALL_TEST_OFFERING_ID_WITH_VARIABLES =
"rc_paywalls_e2e_test_variables_2";
const waitForCheckoutStartRequest = (page: Page) => {
return page.waitForRequest(
(request) =>
request.url().includes("checkout/start") && request.method() === "POST",
);
};
test.describe("Main", () => {
test("Get offerings displays packages", async ({ browser, browserName }) => {
const userId = getUserId(browserName);
const page = await setupTest(browser, userId);
// Gets all elements that match the selector
const packageCards = await getAllElementsByLocator(page, CARD_SELECTOR);
const EXPECTED_VALUES = [
/30[,.]00/,
/19[,.]99/,
/15[,.]00/,
/99[,.]99/,
/2[,.]99/,
];
await Promise.all(
packageCards.map(
async (card, index) =>
await expect(card).toHaveText(EXPECTED_VALUES[index]),
),
);
});
test("Get offerings can filter by offering ID", async ({
browser,
browserName,
}) => {
const userId = getUserId(browserName);
const offeringId = "default_download";
const page = await setupTest(browser, userId, { offeringId });
const packageCards = await getAllElementsByLocator(page, CARD_SELECTOR);
const EXPECTED_VALUES = [/30[,.]00/, /15[,.]00/, /19[,.]99/];
expect(packageCards.length).toBe(3);
await Promise.all(
packageCards.map(
async (card, index) =>
await expect(card).toHaveText(EXPECTED_VALUES[index]),
),
);
});
test("Can purchase a subscription product", async ({
browser,
browserName,
}) => {
const userId = `${getUserId(browserName)}_subscription`;
const page = await setupTest(browser, userId);
// Gets all elements that match the selector
const packageCards = await getAllElementsByLocator(page, CARD_SELECTOR);
const singleCard = packageCards[1];
await performPurchase(page, singleCard, userId);
});
test("Displays handled form submission errors", async ({
browser,
browserName,
}) => {
const userId = `${getUserId(browserName)}_subscription`;
const page = await setupTest(browser, userId);
// Gets all elements that match the selector
const packageCards = await getAllElementsByLocator(page, CARD_SELECTOR);
const singleCard = packageCards[1];
await startPurchaseFlow(singleCard);
await enterEmailAndContinue(page, userId);
// Try with an invalid card declined server side
await enterCreditCardDetailsAndContinue(page, "4000 0000 0000 0002");
const stripeFrame = page.frameLocator(
"iframe[title='Secure payment input frame']",
);
const errorText = stripeFrame.getByText("Your card was declined.");
await expect(errorText).toBeVisible({ timeout: 10000 });
});
test("Displays unhandled form submission errors", async ({
browser,
browserName,
}) => {
const userId = `${getUserId(browserName)}_subscription`;
const page = await setupTest(browser, userId);
// Gets all elements that match the selector
const packageCards = await getAllElementsByLocator(page, CARD_SELECTOR);
const singleCard = packageCards[1];
await startPurchaseFlow(singleCard);
await enterEmailAndContinue(page, userId);
// Try with an invalid card declined server side
await enterCreditCardDetailsAndContinue(page, "4000003800000446");
const stripe3DSFrame = page.frameLocator(
"iframe[src*='https://js.stripe.com/v3/three-ds-2-challenge']",
);
const cancelButton = stripe3DSFrame.getByText("Cancel");
await expect(cancelButton).toBeVisible({
timeout: 10000,
});
await cancelButton.click();
const errorText = page.getByText(
"We are unable to authenticate your payment method. Please choose a different payment method and try again.",
);
await expect(errorText).toBeVisible({ timeout: 10000 });
});
test("Propagates UTM params to metadata when purchasing", async ({
browser,
browserName,
}) => {
const userId = `${getUserId(browserName)}_subscription`;
const utm_params = {
utm_source: "utm-source",
utm_medium: "utm-medium",
utm_campaign: "utm-campaign",
utm_term: "utm-term",
utm_content: "utm-content",
};
const page = await setupTest(browser, userId, { ...utm_params });
// Gets all elements that match the selector
const packageCards = await getAllElementsByLocator(page, CARD_SELECTOR);
const singleCard = packageCards[1];
const requestPromise = waitForCheckoutStartRequest(page);
await performPurchase(page, singleCard, userId);
const request = await requestPromise;
expect(request.postDataJSON()).toHaveProperty("metadata");
const metadata = request.postDataJSON().metadata;
expect(metadata).toStrictEqual(utm_params);
});
test("Does not propagate UTM params to metadata when purchasing if the developer opts out", async ({
browser,
browserName,
}) => {
const userId = `${getUserId(browserName)}_subscription`;
const utm_params = {
utm_source: "utm-source",
utm_medium: "utm-medium",
utm_campaign: "utm-campaign",
utm_term: "utm-term",
utm_content: "utm-content",
};
const page = await setupTest(browser, userId, {
...utm_params,
optOutOfAutoUTM: true,
});
// Gets all elements that match the selector
const packageCards = await getAllElementsByLocator(page, CARD_SELECTOR);
const singleCard = packageCards[1];
const requestPromise = waitForCheckoutStartRequest(page);
await performPurchase(page, singleCard, userId);
const request = await requestPromise;
expect(request.postDataJSON()).toHaveProperty("metadata");
const metadata = request.postDataJSON().metadata;
expect(metadata).toStrictEqual({});
});
test("Can render an RC Paywall", async ({ browser, browserName }) => {
const userId = `${getUserId(browserName)}_subscription`;
const page = await setupTest(browser, userId, {
offeringId: RC_PAYWALL_TEST_OFFERING_ID,
useRcPaywall: true,
});
const title = page.getByText("E2E Tests for Purchases JS");
await expect(title).toBeVisible();
});
test("Can render an RC Paywall using variables", async ({
browser,
browserName,
}) => {
const userId = `${getUserId(browserName)}_subscription`;
const page = await setupTest(browser, userId, {
offeringId: RC_PAYWALL_TEST_OFFERING_ID_WITH_VARIABLES,
useRcPaywall: true,
});
// Gets all packages
const packageCards = await getAllElementsByLocator(page, PACKAGE_SELECTOR);
// Get the purchase button as a Locator
const purchaseButton = (
await getAllElementsByLocator(page, "button.rc-pw-purchase-button")
)[0];
await expect(purchaseButton).toContainText(
"PURCHASE FOR $1.25/1wk($5.00/mo)",
);
await packageCards[1].click();
await expect(purchaseButton).toContainText("PURCHASE FOR $30.00");
await packageCards[2].click();
await expect(purchaseButton).toContainText(
"PURCHASE FOR $19.99/1yr($1.67/mo)",
);
});
test("Can purchase a subscription product for RC Paywall", async ({
browser,
browserName,
}) => {
const userId = `${getUserId(browserName)}_subscription`;
const page = await setupTest(browser, userId, {
offeringId: RC_PAYWALL_TEST_OFFERING_ID_WITH_VARIABLES,
useRcPaywall: true,
});
const title = page.getByText("E2E Tests for Purchases JS");
await expect(title).toBeVisible();
// Gets all packages
const packageCards = await getAllElementsByLocator(page, PACKAGE_SELECTOR);
const singleCard = packageCards[0];
// Pick the first package
await singleCard.click();
// Get the purchase button as a Locator
const purchaseButton = (
await getAllElementsByLocator(page, "button.rc-pw-purchase-button")
)[0];
await expect(purchaseButton).toBeVisible();
// Target the parent element of the purchase button since the function targets the button itself
await performPurchase(page, purchaseButton.locator(".."), userId);
});
test("Can purchase a consumable product", async ({
browser,
browserName,
}) => {
const userId = `${getUserId(browserName)}_consumable`;
const page = await setupTest(browser, userId);
// Gets all elements that match the selector
const packageCards = await getAllElementsByLocator(
page,
CARD_SELECTOR,
"E2E Consumable",
);
expect(packageCards.length).toEqual(1);
const singleCard = packageCards[0];
await performPurchase(page, singleCard, userId);
});
test("Can purchase a non consumable product", async ({
browser,
browserName,
}) => {
const userId = `${getUserId(browserName)}_non_consumable`;
const page = await setupTest(browser, userId);
// Gets all elements that match the selector
const packageCards = await getAllElementsByLocator(
page,
CARD_SELECTOR,
"E2E NonConsumable",
);
expect(packageCards.length).toEqual(1);
const singleCard = packageCards[0];
await performPurchase(page, singleCard, userId);
});
test("Displays error when unknown backend error", async ({
browser,
browserName,
}) => {
const userId = `${getUserId(browserName)}_already_purchased`;
const page = await setupTest(browser, userId);
// Gets all elements that match the selector
const packageCards = await getAllElementsByLocator(page, CARD_SELECTOR);
const singleCard = packageCards[1];
// Perform purchase
const cardButton = singleCard.getByRole("button");
await cardButton.click();
await page.route("*/**/checkout/start", async (route) => {
await route.fulfill({
body: '{ "code": 7110, "message": "Test error message"}',
status: 400,
});
});
await enterEmailAndContinue(page, userId);
// Confirm error page has shown.
const errorTitleText = page.getByText("Something went wrong");
await expect(errorTitleText).toBeVisible();
const errorMessageText = page.getByText(
"Purchase not started due to an error. Error code: 7110",
);
await expect(errorMessageText).toBeVisible();
});
[
["es", "¿Cuál es tu correo electrónico?"],
["it", "Qual è la tua email?"],
["en", "What's your email?"],
["fr", "Quelle est votre adresse e-mail?"],
["de", "Wie lautet Ihre E-Mail-Adresse?"],
].forEach(([lang, title]) => {
test(`Shows the purchase flow in ${lang}`, async ({
browser,
browserName,
}) => {
const userId = `${getUserId(browserName)}_${lang}_language`;
const page = await setupTest(browser, userId, { lang });
// Gets all elements that match the selector
const packageCards = await getAllElementsByLocator(page, CARD_SELECTOR);
const singleCard = packageCards[1];
await startPurchaseFlow(singleCard);
await expect(page.getByText(title)).toBeVisible();
});
});
[
["es", "¿Cuál es tu correo electrónico?"],
["it", "Qual è la tua email?"],
["en", "What's your email?"],
["fr", "Quelle est votre adresse e-mail?"],
["de", "Wie lautet Ihre E-Mail-Adresse?"],
].forEach(([lang, title]) => {
test(`Shows the purchase flow in ${lang} when purchasing from paywalls`, async ({
browser,
browserName,
}) => {
const userId = `${getUserId(browserName)}_${lang}_language`;
const page = await setupTest(browser, userId, {
lang,
offeringId: RC_PAYWALL_TEST_OFFERING_ID,
useRcPaywall: true,
});
// Gets all packages
const packageCards = await getAllElementsByLocator(
page,
PACKAGE_SELECTOR,
);
const singleCard = packageCards[0];
// Pick the first package
await singleCard.click();
// Get the purchase button as a Locator
const purchaseButton = (
await getAllElementsByLocator(page, "button.rc-pw-purchase-button")
)[0];
await expect(purchaseButton).toBeVisible();
await purchaseButton.click();
await expect(page.getByText(title)).toBeVisible();
});
});
test("Tracks events", async ({ browser, browserName }) => {
const userId = `${getUserId(browserName)}_subscription`;
const page = await browser.newPage();
const waitForTrackEventPromise = page.waitForResponse(
successfulEventTrackingResponseMatcher((event) => {
try {
expect(event?.id).toBeDefined();
expect(event?.timestamp_ms).toBeDefined();
expect(event?.type).toBe("web_billing");
expect(event?.event_name).toBe("sdk_initialized");
expect(event?.app_user_id).toBe(userId);
const context = event?.context;
expect(context).toBeInstanceOf(Object);
expect(context.library_name).toEqual("purchases-js");
expect(typeof context.library_version).toBe("string");
expect(typeof context.locale).toBe("string");
expect(typeof context.user_agent).toBe("string");
expect(typeof context.time_zone).toBe("string");
expect(typeof context.screen_width).toBe("number");
expect(typeof context.screen_height).toBe("number");
expect(context.utm_source).toBeNull();
expect(context.utm_medium).toBeNull();
expect(context.utm_campaign).toBeNull();
expect(context.utm_content).toBeNull();
expect(context.utm_term).toBeNull();
expect(context.page_referrer).toBe("");
expect(typeof context.page_url).toBe("string");
expect(context.page_title).toBe("Health Check – Web Billing Demo");
expect(context.source).toBe("sdk");
const properties = event?.properties;
expect(typeof properties.trace_id).toBe("string");
return true;
} catch (error) {
console.error("Event validation failed:", error);
return false;
}
}),
{ timeout: 3_000 },
);
await navigateToUrl(page, userId);
await waitForTrackEventPromise;
});
});
function successfulEventTrackingResponseMatcher(
// eslint-disable-next-line @typescript-eslint/no-explicit-any
eventMatcher: (event: any) => boolean,
) {
return async (response: Response) => {
if (
response.url() !== "https://e.revenue.cat/v1/events" ||
response.status() !== 200
) {
return false;
}
const json = response.request().postDataJSON();
const sdk_initialized_events = (json?.events || []).filter(eventMatcher);
return sdk_initialized_events.length === 1;
};
}
async function startPurchaseFlow(card: Locator) {
// Perform purchase
const cardButton = card.getByRole("button");
await cardButton.click();
}
async function performPurchase(page: Page, card: Locator, userId: string) {
await startPurchaseFlow(card);
await enterEmailAndContinue(page, userId);
await enterCreditCardDetailsAndContinue(page, "4242 4242 4242 4242");
// Confirm success page has shown.
const successText = page.getByText("Payment complete");
await expect(successText).toBeVisible({ timeout: 10000 });
}
const getUserId = (browserName: string) =>
`rc_billing_demo_test_${Date.now()}_${browserName}`;
async function setupTest(
browser: Browser,
userId: string,
queryString?: {
offeringId?: string;
useRcPaywall?: boolean;
lang?: string;
utm_source?: string;
utm_medium?: string;
utm_campaign?: string;
utm_term?: string;
utm_content?: string;
optOutOfAutoUTM?: boolean;
},
) {
const page = await browser.newPage();
await navigateToUrl(page, userId, queryString);
return page;
}
async function getAllElementsByLocator(
page: Page,
locator: string,
containsText?: string,
) {
await page.waitForSelector(locator);
let locatorResult = page.locator(locator);
if (containsText !== undefined) {
locatorResult = locatorResult.filter({ hasText: containsText });
}
return await locatorResult.all();
}
async function enterEmailAndContinue(
page: Page,
userId: string,
): Promise<void> {
const email = `${userId}@revenuecat.com`;
await typeTextInPageSelector(page, email);
await page.getByRole("button", { name: "Continue" }).click();
}
async function enterCreditCardDetailsAndContinue(
page: Page,
cardNumber: string,
): Promise<void> {
// Checmout modal
const checkoutTitle = page.getByText("Secure Checkout");
await expect(checkoutTitle).toBeVisible();
const stripeFrame = page.frameLocator(
"iframe[title='Secure payment input frame']",
);
const numberInput = stripeFrame.getByPlaceholder("1234 1234 1234");
await numberInput.fill(cardNumber);
const expirationYear = (new Date().getFullYear() % 100) + 3;
await stripeFrame.getByPlaceholder("MM / YY").fill(`01 / ${expirationYear}`);
await stripeFrame.getByLabel("Security Code").fill("123");
await stripeFrame.getByLabel("Country").selectOption("US");
await stripeFrame.getByPlaceholder("12345").fill("12345");
await page.getByTestId("PayButton").click();
}
async function navigateToUrl(
page: Page,
userId: string,
queryString?: {
offeringId?: string;
useRcPaywall?: boolean;
lang?: string;
utm_source?: string;
utm_medium?: string;
utm_campaign?: string;
utm_term?: string;
utm_content?: string;
optOutOfAutoUTM?: boolean;
},
): Promise<void> {
const baseUrl =
(import.meta.env?.VITE_RC_BILLING_DEMO_URL as string | undefined) ??
_LOCAL_URL;
const {
offeringId,
useRcPaywall,
lang,
utm_source,
utm_campaign,
utm_term,
utm_content,
utm_medium,
optOutOfAutoUTM,
} = queryString ?? {};
const params = new URLSearchParams();
if (offeringId) {
params.append("offeringId", offeringId);
}
if (lang) {
params.append("lang", lang);
}
if (utm_source) {
params.append("utm_source", utm_source);
}
if (utm_content) {
params.append("utm_content", utm_content);
}
if (utm_term) {
params.append("utm_term", utm_term);
}
if (utm_medium) {
params.append("utm_medium", utm_medium);
}
if (utm_campaign) {
params.append("utm_campaign", utm_campaign);
}
if (optOutOfAutoUTM) {
params.append("optOutOfAutoUTM", optOutOfAutoUTM.toString());
}
const url = `${baseUrl}${useRcPaywall ? "rc_paywall" : "paywall"}/${encodeURIComponent(userId)}?${params.toString()}`;
await page.goto(url);
}
async function typeTextInPageSelector(page: Page, text: string): Promise<void> {
// Fill email
const emailTitle = page.getByText("What's your email?");
await expect(emailTitle).toBeVisible();
await page.getByPlaceholder("john@appleseed.com").click();
await page.getByPlaceholder("john@appleseed.com").fill(text);
}
| yannbf/purchases-js-repro | 0 | TypeScript | yannbf | Yann Braga | chromaui | |
examples/webbilling-demo/src/util/PurchasesLoader.ts | TypeScript | import type { CustomerInfo, Offering } from "@revenuecat/purchases-js";
import { LogLevel, Purchases } from "@revenuecat/purchases-js";
import type { LoaderFunction } from "react-router-dom";
import { redirect, useLoaderData } from "react-router-dom";
const apiKey = import.meta.env.VITE_RC_API_KEY as string;
type IPurchasesLoaderData = {
purchases: Purchases;
customerInfo: CustomerInfo;
offering: Offering;
};
const loadPurchases: LoaderFunction<IPurchasesLoaderData> = async ({
params,
request,
}) => {
const appUserId = params["app_user_id"];
const searchParams = new URL(request.url).searchParams;
const currency = searchParams.get("currency");
const offeringId = searchParams.get("offeringId");
const optOutOfAutoUTM =
searchParams.get("optOutOfAutoUTM") === "true" || false;
if (!appUserId) {
throw redirect("/");
}
Purchases.setLogLevel(LogLevel.Verbose);
try {
if (!Purchases.isConfigured()) {
Purchases.configure(
apiKey,
appUserId,
{},
{ autoCollectUTMAsMetadata: !optOutOfAutoUTM },
);
} else {
await Purchases.getSharedInstance().changeUser(appUserId);
}
const purchases = Purchases.getSharedInstance();
const [customerInfo, offerings] = await Promise.all([
purchases.getCustomerInfo(),
purchases.getOfferings({
currency: currency || undefined,
offeringIdentifier: offeringId || undefined,
}),
]);
const offering = offeringId
? offerings.all[offeringId] || null // Return the specified offering
: offerings.current || null; // Default to the current offering
return {
purchases,
customerInfo,
offering,
};
} catch (error) {
console.error(error);
throw redirect("/");
}
};
const usePurchasesLoaderData: () => IPurchasesLoaderData = () =>
useLoaderData() as IPurchasesLoaderData;
export { loadPurchases, usePurchasesLoaderData };
| yannbf/purchases-js-repro | 0 | TypeScript | yannbf | Yann Braga | chromaui | |
examples/webbilling-demo/src/vite-env.d.ts | TypeScript | /// <reference types="vite/client" />
| yannbf/purchases-js-repro | 0 | TypeScript | yannbf | Yann Braga | chromaui | |
examples/webbilling-demo/vite.config.ts | TypeScript | import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
// https://vitejs.dev/config/
export default defineConfig({
plugins: [react()],
server: {
port: 3001,
},
});
| yannbf/purchases-js-repro | 0 | TypeScript | yannbf | Yann Braga | chromaui | |
global.d.ts | TypeScript | declare module "*.svelte" {
export { SvelteComponentDev as default } from "svelte/internal";
}
declare global {}
| yannbf/purchases-js-repro | 0 | TypeScript | yannbf | Yann Braga | chromaui | |
scripts/docs/index.html | HTML | <!-- This file is used to redirect visitors to the latest version of the docs -->
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="refresh" content="0; url=https://revenuecat.github.io/purchases-js-docs/1.0.5/" />
</head>
<body>
</body>
</html>
| yannbf/purchases-js-repro | 0 | TypeScript | yannbf | Yann Braga | chromaui | |
scripts/translate_locales.py | Python | import json
import os
import requests
import sys
def get_api_key():
api_key = os.getenv("GEMINI_API_KEY", None)
if api_key is None:
raise ValueError("Env var GEMINI_API_KEY is not set")
return api_key
def load_keys_context(directory):
"""Load the keys context file if it exists."""
context_file_path = os.path.join(directory, "keys_context.json")
if not os.path.exists(context_file_path):
# Try looking in the localization directory
context_file_path = os.path.join(directory, "..", "keys_context.json")
if not os.path.exists(context_file_path):
return {}
try:
with open(context_file_path, "r", encoding="utf-8") as f:
return json.load(f)
except json.JSONDecodeError:
print(
f"Warning: keys_context.json contains invalid JSON. Proceeding without context."
)
return {}
def translate_text(text, target_language, keys_context=None):
headers = {
"Authorization": f"Bearer {get_api_key()}",
"Content-Type": "application/json",
}
# Create a system prompt that includes context for each key if available
system_prompt = f"Translate the following JSON into the language with the ISO 639-1 code {target_language.upper()}. "
system_prompt += 'Return a valid JSON object using double quotes (`"`) for keys and string values. '
system_prompt += (
"Do *not* wrap the JSON in any formatting markers like ```json or ```. "
)
system_prompt += "Maintain the context of a subscription app payment flow. "
system_prompt += (
"Keep the JSON keys and variables between braces {{{{ and }}}} unchanged. "
)
system_prompt += (
"Do *not* prepend or append any explanatory text to the JSON output. "
)
system_prompt += "The response should be **valid JSON** that can be parsed using `json.loads()`. "
# Add context information if available
if keys_context:
system_prompt += "\n\nHere is additional context for some of the keys to help with translation:\n"
for key, context in keys_context.items():
if (
key in text
): # Only include context for keys that are in the text to translate
system_prompt += f"- {key}: {context}\n"
data = {
"model": "gemini-2.0-flash",
"messages": [
{
"role": "system",
"content": system_prompt,
},
{"role": "user", "content": text},
],
"max_tokens": 8192,
"temperature": 0.3,
}
try:
response = requests.post(
"https://generativelanguage.googleapis.com/v1beta/chat/completions",
headers=headers,
json=data,
timeout=120,
)
response.raise_for_status()
result = response.json()
translated_text = (
result.get("choices", [{}])[0].get("message", {}).get("content", "")
)
# Remove the ```json and ``` from the beginning and end of the translated text if they still exist
translated_text = translated_text.strip("```json").strip("```")
if not translated_text:
raise ValueError(
f"Unexpected response format: {json.dumps(result, indent=2)}"
)
return translated_text
except requests.exceptions.RequestException as e:
print(f"Error during translation: {e}")
return None
except (KeyError, IndexError, ValueError) as e:
print(f"Error parsing Gemini response: {e}. Response: {response.text}")
return None
def process_json_files(directory, target_language, keys_to_update=None):
en_data = None
for filename in os.listdir(directory):
if filename == "en.json":
filepath = os.path.join(directory, filename)
with open(filepath, "r", encoding="utf-8") as f:
en_data = json.load(f)
break
if en_data is None:
print("en.json not found in the directory.")
return
keys_context = load_keys_context(os.path.dirname(directory))
if keys_context:
print(f"Loaded context for {len(keys_context)} keys")
else:
print("No keys context found or loaded")
# If keys_to_update is provided, filter the English data to only include those keys
if keys_to_update:
filtered_en_data = {k: v for k, v in en_data.items() if k in keys_to_update}
if not filtered_en_data:
print("None of the specified keys found in en.json.")
return
en_data_to_translate = filtered_en_data
else:
en_data_to_translate = en_data
if target_language is not None:
process_json_file(
en_data_to_translate,
directory,
f"{target_language}.json",
target_language,
keys_to_update,
keys_context,
)
return
for filename in os.listdir(directory):
if (
filename.endswith(".json")
and filename != "en.json"
and filename != "keys_context.json"
):
target_language = filename[:-5]
process_json_file(
en_data_to_translate,
directory,
filename,
target_language,
keys_to_update,
keys_context,
)
def process_json_file(
en_data_to_translate,
directory,
filename,
target_language,
keys_to_update=None,
keys_context=None,
):
filepath = os.path.join(directory, filename)
existing_data = {}
# Load existing translation file if it exists
if os.path.exists(filepath):
try:
with open(filepath, "r", encoding="utf-8") as f:
existing_data = json.load(f)
except json.JSONDecodeError:
print(f"Warning: {filename} contains invalid JSON. Creating a new file.")
print(f"Translating JSON file {filename}...")
translated_values = translate_text(
json.dumps(en_data_to_translate, ensure_ascii=False),
target_language,
keys_context,
)
if not translated_values:
print(f"Translation failed for {filename}. Skipping.")
return
try:
translated_data = json.loads(translated_values)
except json.JSONDecodeError as e:
print(f"Error: Could not parse translated JSON for {filename}: {e}")
print(f"Raw translated text: {translated_values[:200]}...")
return
# If we're only updating specific keys, merge with existing data
if keys_to_update:
# Update only the specified keys in the existing data
for key in keys_to_update:
if key in translated_data:
existing_data[key] = translated_data[key]
output_data = existing_data
else:
output_data = translated_data
with open(filepath, "w", encoding="utf-8") as f:
json.dump(output_data, f, indent=2, ensure_ascii=False)
print(f"Updated {filename}")
if __name__ == "__main__":
directory_path = sys.argv[1] if len(sys.argv) > 1 else "."
target_language = sys.argv[2] if len(sys.argv) > 2 else None
# Parse target languages
target_languages = None
if target_language == "all":
target_language = None
elif target_language and "," in target_language:
target_languages = target_language.split(",")
print(f"Translating to languages: {', '.join(target_languages)}")
target_language = None
# Parse keys to update if provided
keys_to_update = None
if len(sys.argv) > 3:
keys_to_update = set(sys.argv[3].split(","))
print(f"Only updating keys: {', '.join(keys_to_update)}")
# Allow specifying keys_to_update as the third argument when no target language is specified
elif len(sys.argv) == 3 and (
target_language == "all"
or
# Check if the argument doesn't look like a language code (typically 2-3 chars)
(target_language and (len(target_language) > 3 or "," in target_language))
):
keys_to_update = set(target_language.split(","))
target_language = None
print(f"Only updating keys: {', '.join(keys_to_update)}")
if target_languages:
for lang in target_languages:
print(f"\nProcessing language: {lang}")
process_json_files(directory_path, lang, keys_to_update)
else:
process_json_files(directory_path, target_language, keys_to_update)
| yannbf/purchases-js-repro | 0 | TypeScript | yannbf | Yann Braga | chromaui | |
src/behavioural-events/event.ts | TypeScript | import { camelToUnderscore } from "../helpers/camel-to-underscore";
import { v4 as uuidv4 } from "uuid";
export type EventData = {
eventName: string;
traceId: string;
appUserId: string;
properties: EventProperties;
context: EventContext;
};
type EventContextSingleValue = string | number | boolean;
type EventContextValue =
| null
| EventContextSingleValue
| Array<EventContextValue>;
export type EventContext = {
[key: string]: EventContextValue;
};
type EventPropertySingleValue = string | number | boolean;
type EventPropertyValue =
| null
| EventPropertySingleValue
| Array<EventPropertyValue>;
export interface EventProperties {
[key: string]: EventPropertyValue;
}
type EventPayload = {
id: string;
timestamp_ms: number;
type: string;
event_name: string;
app_user_id: string;
context: EventContext;
properties: EventProperties;
};
export class Event {
EVENT_TYPE = "web_billing";
public readonly id: string;
public readonly timestampMs: number;
public readonly data: EventData;
public constructor(data: EventData) {
this.id = uuidv4();
this.timestampMs = Date.now();
this.data = data;
}
public toJSON(): EventPayload {
return camelToUnderscore({
id: this.id,
timestampMs: this.timestampMs,
type: this.EVENT_TYPE,
eventName: this.data.eventName,
appUserId: this.data.appUserId,
context: {
...this.data.context,
},
properties: {
...this.data.properties,
traceId: this.data.traceId,
},
}) as EventPayload;
}
}
| yannbf/purchases-js-repro | 0 | TypeScript | yannbf | Yann Braga | chromaui | |
src/behavioural-events/events-tracker.ts | TypeScript | import { v4 as uuid } from "uuid";
import { RC_ANALYTICS_ENDPOINT } from "../helpers/constants";
import { HttpMethods } from "msw";
import { getHeaders } from "../networking/http-client";
import { FlushManager } from "./flush-manager";
import { Logger } from "../helpers/logger";
import { type EventProperties, Event } from "./event";
import type { SDKEvent } from "./sdk-events";
import {
buildEventContext,
type SDKEventContextSource,
} from "./sdk-event-context";
const MIN_INTERVAL_RETRY = 2_000;
const MAX_INTERVAL_RETRY = 5 * 60_000;
const JITTER_PERCENT = 0.1;
export interface TrackEventProps {
eventName: string;
source: SDKEventContextSource;
properties?: EventProperties;
}
export interface EventsTrackerProps {
apiKey: string;
appUserId: string;
silent?: boolean;
}
export interface IEventsTracker {
getTraceId(): string;
updateUser(appUserId: string): Promise<void>;
trackSDKEvent(props: SDKEvent): void;
trackExternalEvent(props: TrackEventProps): void;
dispose(): void;
}
export default class EventsTracker implements IEventsTracker {
private readonly apiKey: string;
private readonly eventsQueue: Array<Event> = [];
private readonly eventsUrl: string;
private readonly flushManager: FlushManager;
private readonly traceId: string = uuid();
private appUserId: string;
private readonly isSilent: boolean;
constructor(props: EventsTrackerProps) {
this.apiKey = props.apiKey;
this.eventsUrl = `${RC_ANALYTICS_ENDPOINT}/v1/events`;
this.appUserId = props.appUserId;
this.isSilent = props.silent || false;
this.flushManager = new FlushManager(
MIN_INTERVAL_RETRY,
MAX_INTERVAL_RETRY,
JITTER_PERCENT,
this.flushEvents.bind(this),
);
}
public async updateUser(appUserId: string) {
this.appUserId = appUserId;
}
public getTraceId() {
return this.traceId;
}
public trackSDKEvent(props: SDKEvent): void {
this.trackEvent({ ...props, source: "sdk" });
}
public trackExternalEvent(props: TrackEventProps): void {
this.trackEvent({ ...props });
}
private trackEvent(props: TrackEventProps) {
if (this.isSilent) {
Logger.verboseLog("Skipping event tracking, the EventsTracker is silent");
return;
}
try {
const event = new Event({
eventName: props.eventName,
traceId: this.traceId,
appUserId: this.appUserId,
context: buildEventContext(props.source),
properties: props.properties || {},
});
this.eventsQueue.push(event);
this.flushManager.tryFlush();
} catch {
Logger.errorLog(`Error while tracking event ${props.eventName}`);
}
}
public dispose() {
this.flushManager.stop();
}
private flushEvents(): Promise<void> {
if (this.eventsQueue.length === 0) {
return Promise.resolve();
}
const eventsToFlush = [...this.eventsQueue];
return fetch(this.eventsUrl, {
method: HttpMethods.POST,
headers: getHeaders(this.apiKey),
body: JSON.stringify({ events: eventsToFlush }),
})
.then((response) => {
if (response.status === 200 || response.status === 201) {
this.eventsQueue.splice(0, eventsToFlush.length);
return;
} else {
Logger.debugLog("Events failed to flush due to server error");
throw new Error("Events failed to flush due to server error");
}
})
.catch((error) => {
Logger.debugLog("Error while flushing events");
throw error;
});
}
}
| yannbf/purchases-js-repro | 0 | TypeScript | yannbf | Yann Braga | chromaui | |
src/behavioural-events/flush-manager.ts | TypeScript | import { Logger } from "../helpers/logger";
export class FlushManager {
private readonly initialDelay: number;
private readonly maxDelay: number;
private readonly jitterPercent: number;
private readonly callback: () => Promise<void>;
private currentDelay: number;
private timeoutId: ReturnType<typeof setTimeout> | undefined = undefined;
private executingCallback: boolean = false;
constructor(
initialDelay: number,
maxDelay: number,
jitterPercent: number,
callback: () => Promise<void>,
) {
this.initialDelay = initialDelay;
this.currentDelay = initialDelay;
this.maxDelay = maxDelay;
this.jitterPercent = jitterPercent;
this.callback = callback;
}
public tryFlush() {
if (this.backingOff()) {
Logger.debugLog(`Backing off, not flushing`);
return;
}
this.clearTimeout();
this.executeCallbackWithRetries();
}
public stop() {
this.clearTimeout();
}
public schedule(delay?: number) {
if (this.timeoutId !== undefined) {
return;
}
const delayWithJitter = this.addJitter(delay || this.currentDelay);
this.timeoutId = setTimeout(() => {
this.timeoutId = undefined;
this.executeCallbackWithRetries();
}, delayWithJitter);
}
private backoff() {
const delay = this.currentDelay;
const newDelay = Math.min(this.currentDelay * 2, this.maxDelay);
Logger.debugLog(`Backing next off to ${delay}ms delay`);
this.clearTimeout();
this.currentDelay = newDelay;
this.schedule(delay);
}
private reset() {
if (this.currentDelay !== this.initialDelay) {
this.clearTimeout();
this.currentDelay = this.initialDelay;
}
}
private async executeCallbackWithRetries() {
if (this.executingCallback) {
Logger.debugLog("Callback already running, rescheduling");
this.schedule();
return;
}
this.executingCallback = true;
try {
await this.callback();
this.reset();
} catch {
this.backoff();
} finally {
this.executingCallback = false;
}
}
private backingOff() {
return this.currentDelay > this.initialDelay;
}
private clearTimeout() {
clearTimeout(this.timeoutId);
this.timeoutId = undefined;
}
private addJitter(interval: number): number {
const jitter = interval * this.jitterPercent;
const min = interval - jitter;
const max = interval + jitter;
return Math.floor(Math.random() * (max - min + 1) + min);
}
}
| yannbf/purchases-js-repro | 0 | TypeScript | yannbf | Yann Braga | chromaui | |
src/behavioural-events/sdk-event-context.ts | TypeScript | import { VERSION } from "../helpers/constants";
import { type EventContext } from "./event";
export type SDKEventContextSource = "sdk" | "wpl" | string;
export interface SDKEventContext {
libraryName: string;
libraryVersion: string;
locale: string;
userAgent: string;
timeZone: string;
screenWidth: number;
screenHeight: number;
utmSource: string | null;
utmMedium: string | null;
utmCampaign: string | null;
utmContent: string | null;
utmTerm: string | null;
pageReferrer: string;
pageUrl: string;
pageTitle: string;
source: SDKEventContextSource;
}
export function buildEventContext(
source: SDKEventContextSource,
): SDKEventContext & EventContext {
const urlParams = new URLSearchParams(window.location.search);
return {
libraryName: "purchases-js",
libraryVersion: VERSION,
locale: navigator.language,
userAgent: navigator.userAgent,
timeZone: Intl.DateTimeFormat().resolvedOptions().timeZone,
screenWidth: screen.width,
screenHeight: screen.height,
utmSource: urlParams.get("utm_source") ?? null,
utmMedium: urlParams.get("utm_medium") ?? null,
utmCampaign: urlParams.get("utm_campaign") ?? null,
utmContent: urlParams.get("utm_content") ?? null,
utmTerm: urlParams.get("utm_term") ?? null,
pageReferrer: document.referrer,
pageUrl: `${window.location.origin}${window.location.pathname}`,
pageTitle: document.title,
source: source,
};
}
| yannbf/purchases-js-repro | 0 | TypeScript | yannbf | Yann Braga | chromaui | |
src/behavioural-events/sdk-event-helpers.ts | TypeScript | import type {
CheckoutFlowErrorEvent,
CheckoutSessionFinishedEvent,
CheckoutSessionClosedEvent,
CheckoutSessionErroredEvent,
CheckoutPurchaseSuccessfulDismissEvent,
CheckoutPaymentFormGatewayErrorEvent,
CheckoutPaymentFormSubmitEvent,
} from "./sdk-events";
import {
SDKEventName,
type CheckoutBillingFormErrorEvent,
type CheckoutSessionStartEvent,
} from "./sdk-events";
import type { Package } from "../entities/offerings";
import type { PurchaseOption } from "../entities/offerings";
import type { RedemptionInfo } from "../entities/redemption-info";
import type { BrandingAppearance } from "../entities/branding";
export function createCheckoutFlowErrorEvent({
errorCode,
errorMessage,
}: {
errorCode: string | null;
errorMessage: string;
}): CheckoutFlowErrorEvent {
return {
eventName: SDKEventName.CheckoutFlowError,
properties: {
errorCode,
errorMessage,
},
};
}
export function createCheckoutBillingFormErrorEvent({
errorCode,
errorMessage,
}: {
errorCode: string | null;
errorMessage: string;
}): CheckoutBillingFormErrorEvent {
return {
eventName: SDKEventName.CheckoutBillingFormError,
properties: {
errorCode: errorCode,
errorMessage: errorMessage,
},
};
}
export function createCheckoutSessionStartEvent({
appearance,
rcPackage,
purchaseOptionToUse,
customerEmail,
}: {
appearance: BrandingAppearance | null | undefined;
rcPackage: Package;
purchaseOptionToUse: PurchaseOption;
customerEmail: string | undefined;
}): CheckoutSessionStartEvent {
return {
eventName: SDKEventName.CheckoutSessionStart,
properties: {
customizationColorButtonsPrimary:
appearance?.color_buttons_primary ?? null,
customizationColorAccent: appearance?.color_accent ?? null,
customizationColorError: appearance?.color_error ?? null,
customizationColorProductInfoBg:
appearance?.color_product_info_bg ?? null,
customizationColorFormBg: appearance?.color_form_bg ?? null,
customizationColorPageBg: appearance?.color_page_bg ?? null,
customizationFont: appearance?.font ?? null,
customizationShapes: appearance?.shapes ?? null,
customizationShowProductDescription:
appearance?.show_product_description ?? null,
productInterval: rcPackage.webBillingProduct.normalPeriodDuration,
productPrice: rcPackage.webBillingProduct.currentPrice.amountMicros,
productCurrency: rcPackage.webBillingProduct.currentPrice.currency,
selectedProductId: rcPackage.webBillingProduct.identifier,
selectedPackageId: rcPackage.identifier,
selectedPurchaseOption: purchaseOptionToUse.id,
customerEmailProvidedByDeveloper: Boolean(customerEmail),
},
};
}
export function createCheckoutSessionEndFinishedEvent({
redemptionInfo,
}: {
redemptionInfo: RedemptionInfo | null;
}): CheckoutSessionFinishedEvent {
return {
eventName: SDKEventName.CheckoutSessionEnd,
properties: {
outcome: "finished",
withRedemptionInfo: Boolean(redemptionInfo),
},
};
}
export function createCheckoutSessionEndClosedEvent(): CheckoutSessionClosedEvent {
return {
eventName: SDKEventName.CheckoutSessionEnd,
properties: {
outcome: "closed",
},
};
}
export function createCheckoutSessionEndErroredEvent({
errorCode,
errorMessage,
}: {
errorCode: string | null;
errorMessage: string;
}): CheckoutSessionErroredEvent {
return {
eventName: SDKEventName.CheckoutSessionEnd,
properties: {
outcome: "errored",
errorCode: errorCode,
errorMessage: errorMessage,
},
};
}
export function createCheckoutPaymentFormSubmitEvent({
selectedPaymentMethod,
}: {
selectedPaymentMethod: string | null;
}): CheckoutPaymentFormSubmitEvent {
return {
eventName: SDKEventName.CheckoutPaymentFormSubmit,
properties: {
selectedPaymentMethod: selectedPaymentMethod ?? null,
},
};
}
export function createCheckoutPaymentGatewayErrorEvent({
errorCode,
errorMessage,
}: {
errorCode: string | null;
errorMessage: string;
}): CheckoutPaymentFormGatewayErrorEvent {
return {
eventName: SDKEventName.CheckoutPaymentFormGatewayError,
properties: {
errorCode: errorCode,
errorMessage: errorMessage,
},
};
}
export function createCheckoutPurchaseSuccessfulDismissEvent(
uiElement: "go_back_to_app" | "close",
): CheckoutPurchaseSuccessfulDismissEvent {
return {
eventName: SDKEventName.CheckoutPurchaseSuccessfulDismiss,
properties: {
ui_element: uiElement,
},
};
}
| yannbf/purchases-js-repro | 0 | TypeScript | yannbf | Yann Braga | chromaui | |
src/behavioural-events/sdk-events.ts | TypeScript | import { type EventProperties } from "./event";
export type SDKEvent =
| SDKInitializedEvent
| CheckoutSessionStartEvent
| CheckoutSessionFinishedEvent
| CheckoutSessionClosedEvent
| CheckoutFlowErrorEvent
| CheckoutSessionErroredEvent
| CheckoutBillingFormImpressionEvent
| CheckoutBillingFormDismissEvent
| CheckoutBillingFormSubmitEvent
| CheckoutBillingFormSuccessEvent
| CheckoutBillingFormErrorEvent
| CheckoutPaymentFormImpressionEvent
| CheckoutPaymentFormDismissEvent
| CheckoutPaymentFormSubmitEvent
| CheckoutPaymentFormGatewayErrorEvent
| CheckoutPurchaseSuccessfulImpressionEvent
| CheckoutPurchaseSuccessfulDismissEvent;
export enum SDKEventName {
SDKInitialized = "sdk_initialized",
CheckoutSessionStart = "checkout_session_start",
CheckoutSessionEnd = "checkout_session_end",
CheckoutFlowError = "checkout_flow_error",
CheckoutBillingFormImpression = "checkout_billing_form_impression",
CheckoutBillingFormDismiss = "checkout_billing_form_dismiss",
CheckoutBillingFormSubmit = "checkout_billing_form_submit",
CheckoutBillingFormSuccess = "checkout_billing_form_success",
CheckoutBillingFormError = "checkout_billing_form_error",
CheckoutPaymentFormImpression = "checkout_payment_form_impression",
CheckoutPaymentFormDismiss = "checkout_payment_form_dismiss",
CheckoutPaymentFormSubmit = "checkout_payment_form_submit",
CheckoutPaymentFormGatewayError = "checkout_payment_form_gateway_error",
CheckoutPurchaseSuccessfulImpression = "checkout_purchase_successful_impression",
CheckoutPurchaseSuccessfulDismiss = "checkout_purchase_successful_dismiss",
}
interface ISDKEvent {
eventName: SDKEventName;
properties?: EventProperties;
}
export interface SDKInitializedEvent extends ISDKEvent {
eventName: SDKEventName.SDKInitialized;
}
export interface CheckoutSessionStartEvent extends ISDKEvent {
eventName: SDKEventName.CheckoutSessionStart;
properties: {
customizationColorButtonsPrimary: string | null;
customizationColorAccent: string | null;
customizationColorError: string | null;
customizationColorProductInfoBg: string | null;
customizationColorFormBg: string | null;
customizationColorPageBg: string | null;
customizationFont: string | null;
customizationShapes: string | null;
customizationShowProductDescription: boolean | null;
productInterval: string | null;
productPrice: number;
productCurrency: string;
selectedProductId: string;
selectedPackageId: string;
selectedPurchaseOption: string;
customerEmailProvidedByDeveloper: boolean;
};
}
export interface CheckoutSessionFinishedEvent extends ISDKEvent {
eventName: SDKEventName.CheckoutSessionEnd;
properties: {
outcome: "finished";
withRedemptionInfo: boolean;
};
}
export interface CheckoutSessionClosedEvent extends ISDKEvent {
eventName: SDKEventName.CheckoutSessionEnd;
properties: {
outcome: "closed";
};
}
export interface CheckoutSessionErroredEvent extends ISDKEvent {
eventName: SDKEventName.CheckoutSessionEnd;
properties: {
outcome: "errored";
errorCode: string | null;
errorMessage: string;
};
}
export interface CheckoutFlowErrorEvent extends ISDKEvent {
eventName: SDKEventName.CheckoutFlowError;
properties: {
errorCode: string | null;
errorMessage: string;
};
}
export interface CheckoutBillingFormImpressionEvent extends ISDKEvent {
eventName: SDKEventName.CheckoutBillingFormImpression;
}
export interface CheckoutBillingFormDismissEvent extends ISDKEvent {
eventName: SDKEventName.CheckoutBillingFormDismiss;
}
export interface CheckoutBillingFormSubmitEvent extends ISDKEvent {
eventName: SDKEventName.CheckoutBillingFormSubmit;
}
export interface CheckoutBillingFormSuccessEvent extends ISDKEvent {
eventName: SDKEventName.CheckoutBillingFormSuccess;
}
export interface CheckoutBillingFormErrorEvent extends ISDKEvent {
eventName: SDKEventName.CheckoutBillingFormError;
properties: {
errorCode: string | null;
errorMessage: string;
};
}
export interface CheckoutPaymentFormImpressionEvent extends ISDKEvent {
eventName: SDKEventName.CheckoutPaymentFormImpression;
}
export interface CheckoutPaymentFormDismissEvent extends ISDKEvent {
eventName: SDKEventName.CheckoutPaymentFormDismiss;
}
export interface CheckoutPaymentFormGatewayErrorEvent extends ISDKEvent {
eventName: SDKEventName.CheckoutPaymentFormGatewayError;
properties: {
errorCode: string | null;
errorMessage: string;
};
}
export interface CheckoutPaymentFormSubmitEvent extends ISDKEvent {
eventName: SDKEventName.CheckoutPaymentFormSubmit;
properties: {
selectedPaymentMethod: string | null;
};
}
export interface CheckoutPurchaseSuccessfulImpressionEvent extends ISDKEvent {
eventName: SDKEventName.CheckoutPurchaseSuccessfulImpression;
}
export interface CheckoutPurchaseSuccessfulDismissEvent extends ISDKEvent {
eventName: SDKEventName.CheckoutPurchaseSuccessfulDismiss;
properties: {
ui_element: "go_back_to_app" | "close";
};
}
| yannbf/purchases-js-repro | 0 | TypeScript | yannbf | Yann Braga | chromaui | |
src/entities/branding.ts | TypeScript | /**
* @public
* `BrandingAppearance` defines the appearance settings
* of an app's branding configuration.
*/
export interface BrandingAppearance {
color_buttons_primary: string;
color_accent: string;
color_error: string;
color_product_info_bg: string;
color_form_bg: string;
color_page_bg: string;
font: string;
shapes: "default" | "rectangle" | "rounded" | "pill";
show_product_description: boolean;
}
| yannbf/purchases-js-repro | 0 | TypeScript | yannbf | Yann Braga | chromaui | |
src/entities/customer-info.ts | TypeScript | import {
type NonSubscriptionResponse,
type SubscriberEntitlementResponse,
type SubscriberResponse,
type SubscriberSubscriptionResponse,
} from "../networking/responses/subscriber-response";
import { ErrorCode, PurchasesError } from "./errors";
/**
* The store where the user originally subscribed.
* @public
*/
export type Store =
| "app_store"
| "mac_app_store"
| "play_store"
| "amazon"
| "stripe"
| "rc_billing"
| "promotional"
| "unknown";
/**
* Supported period types for an entitlement.
* - "normal" If the entitlement is not under an introductory or trial period.
* - "intro" If the entitlement is under an introductory period.
* - "trial" If the entitlement is under a trial period.
* - "prepaid" If the entitlement is a prepaid entitlement. Only for Google Play subscriptions.
* @public
*/
export type PeriodType = "normal" | "intro" | "trial" | "prepaid";
/**
* This object gives you access to all the information about the status
* of a user's entitlements.
* @public
*/
export interface EntitlementInfo {
/**
* The entitlement identifier configured in the RevenueCat dashboard.
*/
readonly identifier: string;
/**
* True if the user has access to the entitlement.
*/
readonly isActive: boolean;
/**
* True if the underlying subscription is set to renew at the end of the
* billing period (expirationDate). Will always be True if entitlement is
* for lifetime access.
*/
readonly willRenew: boolean;
/**
* The store where this entitlement was unlocked from.
*/
readonly store: Store;
/**
* The latest purchase or renewal date for the entitlement.
*/
readonly latestPurchaseDate: Date;
/**
* The first date this entitlement was purchased.
*/
readonly originalPurchaseDate: Date;
/**
* The expiration date for the entitlement, can be `null` for lifetime
* access. If the {@link EntitlementInfo.periodType} is `trial`, this is the trial
* expiration date.
*/
readonly expirationDate: Date | null;
/**
* The product identifier that unlocked this entitlement.
*/
readonly productIdentifier: string;
/**
* The date an unsubscribe was detected. Can be `null`.
* Note: Entitlement may still be active even if user has unsubscribed.
* Check the {@link EntitlementInfo.isActive} property.
*/
readonly unsubscribeDetectedAt: Date | null;
/**
* The date a billing issue was detected. Can be `null` if there is
* no billing issue or an issue has been resolved. Note: Entitlement may
* still be active even if there is a billing issue.
* Check the `isActive` property.
*/
readonly billingIssueDetectedAt: Date | null;
/**
* False if this entitlement is unlocked via a production purchase.
*/
readonly isSandbox: boolean;
/**
* The last period type this entitlement was in.
*/
readonly periodType: PeriodType;
}
/**
* Contains all the entitlements associated to the user.
* @public
*/
export interface EntitlementInfos {
/**
* Map of all {@link EntitlementInfo} objects (active and inactive) keyed by
* entitlement identifier.
*/
readonly all: { [entitlementId: string]: EntitlementInfo };
/**
* Dictionary of active {@link EntitlementInfo} keyed by entitlement identifier.
*/
readonly active: { [entitlementId: string]: EntitlementInfo };
}
/**
* Type containing all information regarding the customer.
* @public
*/
export interface CustomerInfo {
/**
* Entitlements attached to this customer info.
*/
readonly entitlements: EntitlementInfos;
/**
* Map of productIds to expiration dates.
*/
readonly allExpirationDatesByProduct: {
[productIdentifier: string]: Date | null;
};
/**
* Map of productIds to purchase dates.
*/
readonly allPurchaseDatesByProduct: {
[productIdentifier: string]: Date | null;
};
/**
* Set of active subscription product identifiers.
*/
readonly activeSubscriptions: Set<string>;
/**
* URL to manage the active subscription of the user.
* If this user has an active Web Billing subscription, a link to the management page.
* If this user has an active iOS subscription, this will point to the App Store.
* If the user has an active Play Store subscription it will point there.
* If there are no active subscriptions it will be null.
*/
readonly managementURL: string | null;
/**
* Date when this info was requested.
*/
readonly requestDate: Date;
/**
* The date this user was first seen in RevenueCat.
*/
readonly firstSeenDate: Date;
/**
* The purchase date for the version of the application when the user bought the app.
* Use this for grandfathering users when migrating to subscriptions. This can be null.
*/
readonly originalPurchaseDate: Date | null;
/**
* The original App User Id recorded for this user.
*/
readonly originalAppUserId: string;
}
function isActive(
entitlementInfoResponse: SubscriberEntitlementResponse,
): boolean {
if (entitlementInfoResponse.expires_date == null) return true;
const expirationDate = new Date(entitlementInfoResponse.expires_date);
const currentDate = new Date();
return expirationDate > currentDate;
}
function toEntitlementInfo(
entitlementIdentifier: string,
entitlementInfoResponse: SubscriberEntitlementResponse,
subscriptions: { [productId: string]: SubscriberSubscriptionResponse },
latestNonSubscriptionPurchaseByProduct: {
[key: string]: NonSubscriptionResponse;
},
): EntitlementInfo {
const productIdentifier = entitlementInfoResponse.product_identifier;
if (productIdentifier in subscriptions) {
return toSubscriptionEntitlementInfo(
entitlementIdentifier,
entitlementInfoResponse,
subscriptions[productIdentifier],
);
} else if (productIdentifier in latestNonSubscriptionPurchaseByProduct) {
return toNonSubscriptionEntitlementInfo(
entitlementIdentifier,
entitlementInfoResponse,
latestNonSubscriptionPurchaseByProduct[productIdentifier],
);
}
throw new PurchasesError(
ErrorCode.CustomerInfoError,
"Could not find entitlement product in subscriptions or non-subscriptions.",
);
}
function toSubscriptionEntitlementInfo(
entitlementIdentifier: string,
entitlementInfoResponse: SubscriberEntitlementResponse,
subscriptionResponse: SubscriberSubscriptionResponse | null,
): EntitlementInfo {
return {
identifier: entitlementIdentifier,
isActive: isActive(entitlementInfoResponse),
willRenew: getWillRenew(entitlementInfoResponse, subscriptionResponse),
store: subscriptionResponse?.store ?? "unknown",
latestPurchaseDate: new Date(entitlementInfoResponse.purchase_date),
originalPurchaseDate: new Date(entitlementInfoResponse.purchase_date),
expirationDate: toDateIfNotNull(entitlementInfoResponse.expires_date),
productIdentifier: entitlementInfoResponse.product_identifier,
unsubscribeDetectedAt: toDateIfNotNull(
subscriptionResponse?.unsubscribe_detected_at,
),
billingIssueDetectedAt: toDateIfNotNull(
subscriptionResponse?.billing_issues_detected_at,
),
isSandbox: subscriptionResponse?.is_sandbox ?? false,
periodType: subscriptionResponse?.period_type ?? "normal",
};
}
function toNonSubscriptionEntitlementInfo(
entitlementIdentifier: string,
entitlementInfoResponse: SubscriberEntitlementResponse,
nonSubscriptionResponse: NonSubscriptionResponse,
): EntitlementInfo {
return {
identifier: entitlementIdentifier,
isActive: true,
willRenew: false,
store: nonSubscriptionResponse.store,
latestPurchaseDate: new Date(entitlementInfoResponse.purchase_date),
originalPurchaseDate: new Date(
nonSubscriptionResponse.original_purchase_date,
),
expirationDate: null,
productIdentifier: entitlementInfoResponse.product_identifier,
unsubscribeDetectedAt: null,
billingIssueDetectedAt: null,
isSandbox: nonSubscriptionResponse.is_sandbox,
periodType: "normal",
};
}
function toEntitlementInfos(
entitlementsResponse: {
[entitlementId: string]: SubscriberEntitlementResponse;
},
subscriptions: { [productId: string]: SubscriberSubscriptionResponse },
latestNonSubscriptionPurchaseByProduct: {
[key: string]: NonSubscriptionResponse;
},
): EntitlementInfos {
const allEntitlementInfo: { [entitlementId: string]: EntitlementInfo } = {};
const activeEntitlementInfo: { [entitlementId: string]: EntitlementInfo } =
{};
for (const key in entitlementsResponse) {
const entitlementInfo = toEntitlementInfo(
key,
entitlementsResponse[key],
subscriptions,
latestNonSubscriptionPurchaseByProduct,
);
allEntitlementInfo[key] = entitlementInfo;
if (entitlementInfo.isActive) {
activeEntitlementInfo[key] = entitlementInfo;
}
}
return {
all: allEntitlementInfo,
active: activeEntitlementInfo,
};
}
function toDateIfNotNull(value: string | undefined | null): Date | null {
if (value == null) return null;
return new Date(value);
}
export function toCustomerInfo(
customerInfoResponse: SubscriberResponse,
): CustomerInfo {
const expirationDatesByProductId =
getExpirationDatesByProductId(customerInfoResponse);
const subscriberResponse = customerInfoResponse.subscriber;
const latestNonSubscriptionPurchaseByProduct =
getLatestNonSubscriptionPurchaseByProduct(
subscriberResponse.non_subscriptions,
);
return {
entitlements: toEntitlementInfos(
subscriberResponse.entitlements,
subscriberResponse.subscriptions,
latestNonSubscriptionPurchaseByProduct,
),
allExpirationDatesByProduct: expirationDatesByProductId,
allPurchaseDatesByProduct: getPurchaseDatesByProductId(
customerInfoResponse,
latestNonSubscriptionPurchaseByProduct,
),
activeSubscriptions: getActiveSubscriptions(expirationDatesByProductId),
managementURL: subscriberResponse.management_url,
requestDate: new Date(customerInfoResponse.request_date),
firstSeenDate: new Date(subscriberResponse.first_seen),
originalPurchaseDate: toDateIfNotNull(
subscriberResponse.original_purchase_date,
),
originalAppUserId: customerInfoResponse.subscriber.original_app_user_id,
};
}
function getWillRenew(
entitlementInfoResponse: SubscriberEntitlementResponse,
subscriptionResponse: SubscriberSubscriptionResponse | null,
) {
if (subscriptionResponse == null) return false;
const isPromo = subscriptionResponse.store == "promotional";
const isLifetime = entitlementInfoResponse.expires_date == null;
const hasUnsubscribed = subscriptionResponse.unsubscribe_detected_at != null;
const hasBillingIssues =
subscriptionResponse.billing_issues_detected_at != null;
return !(isPromo || isLifetime || hasUnsubscribed || hasBillingIssues);
}
function getPurchaseDatesByProductId(
customerInfoResponse: SubscriberResponse,
latestNonSubscriptionPurchaseByProduct: {
[key: string]: NonSubscriptionResponse;
},
): { [productId: string]: Date | null } {
const purchaseDatesByProduct: { [productId: string]: Date | null } = {};
for (const subscriptionId in customerInfoResponse.subscriber.subscriptions) {
const subscription =
customerInfoResponse.subscriber.subscriptions[subscriptionId];
purchaseDatesByProduct[subscriptionId] = new Date(
subscription.purchase_date,
);
}
for (const productId in latestNonSubscriptionPurchaseByProduct) {
const purchaseDate =
latestNonSubscriptionPurchaseByProduct[productId].purchase_date;
if (purchaseDate == null) {
purchaseDatesByProduct[productId] = null;
} else {
purchaseDatesByProduct[productId] = new Date(purchaseDate);
}
}
return purchaseDatesByProduct;
}
function getExpirationDatesByProductId(
customerInfoResponse: SubscriberResponse,
): { [productId: string]: Date | null } {
const expirationDatesByProduct: { [productId: string]: Date | null } = {};
for (const subscriptionId in customerInfoResponse.subscriber.subscriptions) {
const subscription =
customerInfoResponse.subscriber.subscriptions[subscriptionId];
if (subscription.expires_date == null) {
expirationDatesByProduct[subscriptionId] = null;
} else {
expirationDatesByProduct[subscriptionId] = new Date(
subscription.expires_date,
);
}
}
return expirationDatesByProduct;
}
function getActiveSubscriptions(expirationDatesByProductId: {
[productId: string]: Date | null;
}): Set<string> {
const activeSubscriptions: Set<string> = new Set();
const currentDate = new Date();
for (const productId in expirationDatesByProductId) {
const expirationDate = expirationDatesByProductId[productId];
if (expirationDate == null) {
activeSubscriptions.add(productId);
} else if (expirationDate > currentDate) {
activeSubscriptions.add(productId);
}
}
return activeSubscriptions;
}
function getLatestNonSubscriptionPurchaseByProduct(nonSubscriptions: {
[key: string]: NonSubscriptionResponse[];
}): { [key: string]: NonSubscriptionResponse } {
const latestNonSubscriptionPurchaseByProduct: {
[key: string]: NonSubscriptionResponse;
} = {};
for (const key in nonSubscriptions) {
if (nonSubscriptions[key].length === 0) continue;
const numberPurchases = nonSubscriptions[key].length;
latestNonSubscriptionPurchaseByProduct[key] =
nonSubscriptions[key][numberPurchases - 1];
}
return latestNonSubscriptionPurchaseByProduct;
}
| yannbf/purchases-js-repro | 0 | TypeScript | yannbf | Yann Braga | chromaui | |
src/entities/errors.ts | TypeScript | import {
type PurchaseFlowError,
PurchaseFlowErrorCode,
} from "../helpers/purchase-operation-helper";
/**
* Error codes for the Purchases SDK.
* @public
*/
export enum ErrorCode {
UnknownError = 0,
UserCancelledError = 1,
StoreProblemError = 2,
PurchaseNotAllowedError = 3,
PurchaseInvalidError = 4,
ProductNotAvailableForPurchaseError = 5,
ProductAlreadyPurchasedError = 6,
ReceiptAlreadyInUseError = 7,
InvalidReceiptError = 8,
MissingReceiptFileError = 9,
NetworkError = 10,
InvalidCredentialsError = 11,
UnexpectedBackendResponseError = 12,
InvalidAppUserIdError = 14,
OperationAlreadyInProgressError = 15,
UnknownBackendError = 16,
InvalidAppleSubscriptionKeyError = 17,
IneligibleError = 18,
InsufficientPermissionsError = 19,
PaymentPendingError = 20,
InvalidSubscriberAttributesError = 21,
LogOutWithAnonymousUserError = 22,
ConfigurationError = 23,
UnsupportedError = 24,
EmptySubscriberAttributesError = 25,
CustomerInfoError = 28,
SignatureVerificationError = 36,
InvalidEmailError = 38,
}
export class ErrorCodeUtils {
static getPublicMessage(errorCode: ErrorCode): string {
switch (errorCode) {
case ErrorCode.UnknownError:
return "Unknown error.";
case ErrorCode.UserCancelledError:
return "Purchase was cancelled.";
case ErrorCode.StoreProblemError:
return "There was a problem with the store.";
case ErrorCode.PurchaseNotAllowedError:
return "The device or user is not allowed to make the purchase.";
case ErrorCode.PurchaseInvalidError:
return "One or more of the arguments provided are invalid.";
case ErrorCode.ProductNotAvailableForPurchaseError:
return "The product is not available for purchase.";
case ErrorCode.ProductAlreadyPurchasedError:
return "This product is already active for the user.";
case ErrorCode.ReceiptAlreadyInUseError:
return "There is already another active subscriber using the same receipt.";
case ErrorCode.InvalidReceiptError:
return "The receipt is not valid.";
case ErrorCode.MissingReceiptFileError:
return "The receipt is missing.";
case ErrorCode.NetworkError:
return "Error performing request. Please check your network connection and try again.";
case ErrorCode.InvalidCredentialsError:
return "There was a credentials issue. Check the underlying error for more details.";
case ErrorCode.UnexpectedBackendResponseError:
return "Received unexpected response from the backend.";
case ErrorCode.InvalidAppUserIdError:
return "The app user id is not valid.";
case ErrorCode.OperationAlreadyInProgressError:
return "The operation is already in progress.";
case ErrorCode.UnknownBackendError:
return "There was an unknown backend error.";
case ErrorCode.InvalidAppleSubscriptionKeyError:
return (
"Apple Subscription Key is invalid or not present. " +
"In order to provide subscription offers, you must first generate a subscription key. " +
"Please see https://docs.revenuecat.com/docs/ios-subscription-offers for more info."
);
case ErrorCode.IneligibleError:
return "The User is ineligible for that action.";
case ErrorCode.InsufficientPermissionsError:
return "App does not have sufficient permissions to make purchases.";
case ErrorCode.PaymentPendingError:
return "The payment is pending.";
case ErrorCode.InvalidSubscriberAttributesError:
return "One or more of the attributes sent could not be saved.";
case ErrorCode.LogOutWithAnonymousUserError:
return "Called logOut but the current user is anonymous.";
case ErrorCode.ConfigurationError:
return "There is an issue with your configuration. Check the underlying error for more details.";
case ErrorCode.UnsupportedError:
return (
"There was a problem with the operation. Looks like we doesn't support " +
"that yet. Check the underlying error for more details."
);
case ErrorCode.EmptySubscriberAttributesError:
return "A request for subscriber attributes returned none.";
case ErrorCode.CustomerInfoError:
return "There was a problem related to the customer info.";
case ErrorCode.SignatureVerificationError:
return "Request failed signature verification. Please see https://rev.cat/trusted-entitlements for more info.";
case ErrorCode.InvalidEmailError:
return "Email is not valid. Please provide a valid email address.";
}
}
static getErrorCodeForBackendErrorCode(
backendErrorCode: BackendErrorCode,
): ErrorCode {
switch (backendErrorCode) {
case BackendErrorCode.BackendStoreProblem:
case BackendErrorCode.BackendPaymentGatewayGenericError:
return ErrorCode.StoreProblemError;
case BackendErrorCode.BackendCannotTransferPurchase:
return ErrorCode.ReceiptAlreadyInUseError;
case BackendErrorCode.BackendInvalidReceiptToken:
return ErrorCode.InvalidReceiptError;
case BackendErrorCode.BackendInvalidPlayStoreCredentials:
case BackendErrorCode.BackendInvalidAuthToken:
case BackendErrorCode.BackendInvalidAPIKey:
return ErrorCode.InvalidCredentialsError;
case BackendErrorCode.BackendInvalidPaymentModeOrIntroPriceNotProvided:
case BackendErrorCode.BackendProductIdForGoogleReceiptNotProvided:
case BackendErrorCode.BackendOfferNotFound:
case BackendErrorCode.BackendInvalidOperationSession:
case BackendErrorCode.BackendPurchaseCannotBeCompleted:
return ErrorCode.PurchaseInvalidError;
case BackendErrorCode.BackendAlreadySubscribedError:
return ErrorCode.ProductAlreadyPurchasedError;
case BackendErrorCode.BackendEmptyAppUserId:
return ErrorCode.InvalidAppUserIdError;
case BackendErrorCode.BackendPlayStoreQuotaExceeded:
return ErrorCode.StoreProblemError;
case BackendErrorCode.BackendPlayStoreInvalidPackageName:
case BackendErrorCode.BackendInvalidPlatform:
return ErrorCode.ConfigurationError;
case BackendErrorCode.BackendPlayStoreGenericError:
return ErrorCode.StoreProblemError;
case BackendErrorCode.BackendUserIneligibleForPromoOffer:
return ErrorCode.IneligibleError;
case BackendErrorCode.BackendInvalidSubscriberAttributes:
case BackendErrorCode.BackendInvalidSubscriberAttributesBody:
return ErrorCode.InvalidSubscriberAttributesError;
case BackendErrorCode.BackendInvalidAppStoreSharedSecret:
case BackendErrorCode.BackendInvalidAppleSubscriptionKey:
case BackendErrorCode.BackendBadRequest:
case BackendErrorCode.BackendInternalServerError:
return ErrorCode.UnexpectedBackendResponseError;
case BackendErrorCode.BackendProductIDsMalformed:
return ErrorCode.UnsupportedError;
case BackendErrorCode.BackendInvalidEmail:
case BackendErrorCode.BackendNoMXRecordsFound:
case BackendErrorCode.BackendEmailIsRequired:
return ErrorCode.InvalidEmailError;
}
}
static convertCodeToBackendErrorCode(code: number): BackendErrorCode | null {
if (code in BackendErrorCode) {
return code as BackendErrorCode;
} else {
return null;
}
}
static convertPurchaseFlowErrorCodeToErrorCode(
code: PurchaseFlowErrorCode,
): ErrorCode {
switch (code) {
case PurchaseFlowErrorCode.ErrorSettingUpPurchase:
return ErrorCode.StoreProblemError;
case PurchaseFlowErrorCode.ErrorChargingPayment:
return ErrorCode.PaymentPendingError;
case PurchaseFlowErrorCode.NetworkError:
return ErrorCode.NetworkError;
case PurchaseFlowErrorCode.MissingEmailError:
return ErrorCode.PurchaseInvalidError;
case PurchaseFlowErrorCode.UnknownError:
return ErrorCode.UnknownError;
case PurchaseFlowErrorCode.AlreadyPurchasedError:
return ErrorCode.ProductAlreadyPurchasedError;
}
}
}
export enum BackendErrorCode {
BackendInvalidPlatform = 7000,
BackendInvalidEmail = 7012,
BackendStoreProblem = 7101,
BackendCannotTransferPurchase = 7102,
BackendInvalidReceiptToken = 7103,
BackendInvalidAppStoreSharedSecret = 7104,
BackendInvalidPaymentModeOrIntroPriceNotProvided = 7105,
BackendProductIdForGoogleReceiptNotProvided = 7106,
BackendInvalidPlayStoreCredentials = 7107,
BackendInternalServerError = 7110,
BackendEmptyAppUserId = 7220,
BackendInvalidAuthToken = 7224,
BackendInvalidAPIKey = 7225,
BackendBadRequest = 7226,
BackendPlayStoreQuotaExceeded = 7229,
BackendPlayStoreInvalidPackageName = 7230,
BackendPlayStoreGenericError = 7231,
BackendUserIneligibleForPromoOffer = 7232,
BackendInvalidAppleSubscriptionKey = 7234,
BackendInvalidSubscriberAttributes = 7263,
BackendInvalidSubscriberAttributesBody = 7264,
BackendProductIDsMalformed = 7662,
BackendAlreadySubscribedError = 7772,
BackendPaymentGatewayGenericError = 7773,
BackendOfferNotFound = 7814,
BackendNoMXRecordsFound = 7834,
BackendInvalidOperationSession = 7877,
BackendPurchaseCannotBeCompleted = 7878,
BackendEmailIsRequired = 7879,
}
/**
* Extra information that is available in certain types of errors.
* @public
*/
export interface PurchasesErrorExtra {
/**
* If this is a request error, the HTTP status code of the response.
*/
readonly statusCode?: number;
/**
* If this is a RevenueCat backend error, the error code from the servers.
*/
readonly backendErrorCode?: number;
}
/**
* Error class for Purchases SDK. You should handle these errors and react
* accordingly in your app.
* @public
*/
export class PurchasesError extends Error {
/** @internal */
static getForBackendError(
backendErrorCode: BackendErrorCode,
backendErrorMessage: string | null,
): PurchasesError {
const errorCode =
ErrorCodeUtils.getErrorCodeForBackendErrorCode(backendErrorCode);
return new PurchasesError(
errorCode,
ErrorCodeUtils.getPublicMessage(errorCode),
backendErrorMessage,
{ backendErrorCode: backendErrorCode },
);
}
/** @internal */
static getForPurchasesFlowError(
purchasesFlowError: PurchaseFlowError,
): PurchasesError {
return new PurchasesError(
ErrorCodeUtils.convertPurchaseFlowErrorCodeToErrorCode(
purchasesFlowError.errorCode,
),
purchasesFlowError.message,
purchasesFlowError.underlyingErrorMessage,
);
}
constructor(
/**
* Error code for the error. This is useful to appropriately react to
* different error situations.
*/
public readonly errorCode: ErrorCode,
/**
* Message for the error. This is useful for debugging and logging.
*/
message?: string,
/**
* Underlying error message. This provides more details on the error and
* can be useful for debugging and logging.
*/
public readonly underlyingErrorMessage?: string | null,
/**
* Contains extra information that is available in certain types of errors.
*/
public readonly extra?: PurchasesErrorExtra,
) {
super(message);
}
toString = (): string => {
return `PurchasesError(code: ${ErrorCode[this.errorCode]}, message: ${this.message})`;
};
}
/**
* Error indicating that the SDK was accessed before it was initialized.
* @public
*/
export class UninitializedPurchasesError extends Error {
constructor() {
super("Purchases must be configured before calling getInstance");
}
}
| yannbf/purchases-js-repro | 0 | TypeScript | yannbf | Yann Braga | chromaui | |
src/entities/flags-config.ts | TypeScript | /**
* Flags used to enable or disable certain features in the sdk.
* @public
*/
export interface FlagsConfig {
/**
* If set to true, the SDK will automatically collect UTM parameters and store them as at the time of purchase.
* @defaultValue true
*/
autoCollectUTMAsMetadata?: boolean;
/**
* If set to true, the SDK will automatically collect analytics events.
* @defaultValue true
*/
collectAnalyticsEvents?: boolean;
}
export const defaultFlagsConfig: FlagsConfig = {
autoCollectUTMAsMetadata: true,
collectAnalyticsEvents: true,
};
| yannbf/purchases-js-repro | 0 | TypeScript | yannbf | Yann Braga | chromaui | |
src/entities/get-offerings-params.ts | TypeScript | /**
* Keywords for identifying specific offerings in the {@link Purchases.getOfferings} method.
* @public
*/
export enum OfferingKeyword {
/**
* The current offering.
*/
Current = "current",
}
/**
* Parameters for the {@link Purchases.getOfferings} method.
* @public
*/
export interface GetOfferingsParams {
/**
* The currency code in ISO 4217 to fetch the offerings for.
* If not specified, the default currency will be used.
*/
readonly currency?: string;
/**
* The identifier of the offering to fetch.
* Can be a string identifier or one of the predefined keywords.
*/
readonly offeringIdentifier?: string | OfferingKeyword;
}
| yannbf/purchases-js-repro | 0 | TypeScript | yannbf | Yann Braga | chromaui | |
src/entities/http-config.ts | TypeScript | /**
* Parameters used to customise the http requests executed by purchases-js.
* @public
*/
export interface HttpConfig {
/**
* Additional headers to include in all HTTP requests.
*/
additionalHeaders?: Record<string, string>;
/**
* Set this property to your proxy URL *only* if you've received a proxy
* key value from your RevenueCat contact. This value should never end with
* a trailing slash.
*/
proxyURL?: string;
}
export const defaultHttpConfig = {} as HttpConfig;
| yannbf/purchases-js-repro | 0 | TypeScript | yannbf | Yann Braga | chromaui | |
src/entities/log-level.ts | TypeScript | /**
* Possible levels to log in the console.
* @public
*/
export enum LogLevel {
/**
* No logs will be shown in the console.
*/
Silent = 0,
/**
* Only errors will be shown in the console.
*/
Error = 1,
/**
* Only warnings and errors will be shown in the console.
*/
Warn = 2,
/**
* Only info, warnings, and errors will be shown in the console.
*/
Info = 3,
/**
* Debug, info, warnings, and errors will be shown in the console.
*/
Debug = 4,
/**
* All logs will be shown in the console.
*/
Verbose = 5,
}
| yannbf/purchases-js-repro | 0 | TypeScript | yannbf | Yann Braga | chromaui | |
src/entities/offerings.ts | TypeScript | import {
type OfferingResponse,
type PackageResponse,
type TargetingResponse,
} from "../networking/responses/offerings-response";
import type {
NonSubscriptionOptionResponse,
PriceResponse,
PricingPhaseResponse,
ProductResponse,
SubscriptionOptionResponse,
} from "../networking/responses/products-response";
import { notEmpty } from "../helpers/type-helper";
import { formatPrice } from "../helpers/price-labels";
import { Logger } from "../helpers/logger";
import { parseISODuration, type Period } from "../helpers/duration-helper";
import type { PaywallData } from "@revenuecat/purchases-ui-js";
/**
* Enumeration of all possible Package types.
* @public
*/
export enum PackageType {
/**
* A package that was defined with an unrecognized RC identifier.
*/
Unknown = "unknown",
/**
* A package that was defined with a custom identifier.
*/
Custom = "custom",
/**
* A package configured with the predefined lifetime identifier.
*/
Lifetime = "$rc_lifetime",
/**
* A package configured with the predefined annual identifier.
*/
Annual = "$rc_annual",
/**
* A package configured with the predefined six month identifier.
*/
SixMonth = "$rc_six_month",
/**
* A package configured with the predefined three month identifier.
*/
ThreeMonth = "$rc_three_month",
/**
* A package configured with the predefined two month identifier.
*/
TwoMonth = "$rc_two_month",
/**
* A package configured with the predefined monthly identifier.
*/
Monthly = "$rc_monthly",
/**
* A package configured with the predefined weekly identifier.
*/
Weekly = "$rc_weekly",
}
/**
* Possible product types
* @public
*/
export enum ProductType {
/**
* A product that is an auto-renewing subscription.
*/
Subscription = "subscription",
/**
* A product that does not renew and can be consumed to be purchased again.
*/
Consumable = "consumable",
/**
* A product that does not renew and can only be purchased once.
*/
NonConsumable = "non_consumable",
}
/**
* Price information for a product.
* @public
*/
export interface Price {
/**
* Price in cents of the currency.
* @deprecated - Use {@link Price.amountMicros} instead.
*/
readonly amount: number;
/**
* Price in micro-units of the currency. For example, $9.99 is represented as 9990000.
*/
readonly amountMicros: number;
/**
* Returns ISO 4217 currency code for price.
* For example, if price is specified in British pounds sterling,
* currency is "GBP".
* If currency code cannot be determined, currency symbol is returned.
*/
readonly currency: string;
/**
* Formatted price string including price and currency.
*/
readonly formattedPrice: string;
}
/**
* Represents the price and duration information for a phase of the purchase option.
* @public
*/
export interface PricingPhase {
/**
* The duration of the phase in ISO 8601 format.
*/
readonly periodDuration: string | null;
/**
* The duration of the phase as a {@link Period}.
*/
readonly period: Period | null;
/**
* The price for the purchase option.
* Null in case of trials.
*/
readonly price: Price | null;
/**
* The number of cycles this option's price repeats.
* I.e. 2 subscription cycles, 0 if not applicable.
*/
readonly cycleCount: number;
}
/**
* Represents a possible option to purchase a product.
* @public
*/
export interface PurchaseOption {
/**
* The unique id for a purchase option
*/
readonly id: string;
/**
* The public price id for this subscription option.
*/
readonly priceId: string;
}
/**
* Represents a possible option to purchase a subscription product.
* @public
*/
export interface SubscriptionOption extends PurchaseOption {
/**
* The base phase for a SubscriptionOption, represents
* the price that the customer will be charged after all the discounts have
* been consumed and the period at which it will renew.
*/
readonly base: PricingPhase;
/**
* The trial information for this subscription option if available.
*/
readonly trial: PricingPhase | null;
}
/**
* Represents a possible option to purchase a non-subscription product.
* @public
*/
export interface NonSubscriptionOption extends PurchaseOption {
/**
* The base price for the product.
*/
readonly basePrice: Price;
}
/**
* Contains information about the targeting context used to obtain an object.
* @public
*/
export interface TargetingContext {
/**
* The rule id from the targeting used to obtain this object.
*/
readonly ruleId: string;
/**
* The revision of the targeting used to obtain this object.
*/
readonly revision: number;
}
/**
* Contains data about the context in which an offering was presented.
* @public
*/
export interface PresentedOfferingContext {
/**
* The identifier of the offering used to obtain this object.
*/
readonly offeringIdentifier: string;
/**
* The targeting context used to obtain this object.
*/
readonly targetingContext: TargetingContext | null;
/**
* If obtained this information from a placement,
* the identifier of the placement.
*/
readonly placementIdentifier: string | null;
}
/**
* Represents product's listing details.
* @public
*/
export interface Product {
/**
* The product ID.
*/
readonly identifier: string;
/**
* Name of the product.
* @deprecated - Use {@link Product.title} instead.
*/
readonly displayName: string;
/**
* The title of the product as configured in the RevenueCat dashboard.
*/
readonly title: string;
/**
* The description of the product as configured in the RevenueCat dashboard.
*/
readonly description: string | null;
/**
* Price of the product. This will match the default option's base phase price
* in subscriptions or the price in non-subscriptions.
*/
readonly currentPrice: Price;
/**
* The type of product.
*/
readonly productType: ProductType;
/**
* The period duration for a subscription product. This will match the default
* option's base phase period duration. Null for non-subscriptions.
*/
readonly normalPeriodDuration: string | null;
/**
* The offering ID used to obtain this product.
* @deprecated - Use {@link Product.presentedOfferingContext} instead.
*/
readonly presentedOfferingIdentifier: string;
/**
* The context from which this product was obtained.
*/
readonly presentedOfferingContext: PresentedOfferingContext;
/**
* The default purchase option for this product.
*/
readonly defaultPurchaseOption: PurchaseOption;
/**
* The default subscription option for this product.
* Null if no subscription options are available like in the case of consumables and non-consumables.
*/
readonly defaultSubscriptionOption: SubscriptionOption | null;
/**
* A dictionary with all the possible subscription options available for this
* product. Each key contains the key to be used when executing a purchase.
* Will be empty for non-subscriptions
*
* If retrieved through getOfferings the offers are only the ones the customer is
* entitled to.
*/
readonly subscriptionOptions: {
[optionId: string]: SubscriptionOption;
};
/**
* The default non-subscription option for this product.
* Null in the case of subscriptions.
*/
readonly defaultNonSubscriptionOption: NonSubscriptionOption | null;
}
/**
* Contains information about the product available for the user to purchase.
* For more info see https://docs.revenuecat.com/docs/entitlements
* @public
*/
export interface Package {
/**
* Unique identifier for this package. Can be one a predefined package type or a custom one.
*/
readonly identifier: string;
/**
* The {@link Product} assigned to this package.
* @deprecated - Use {@link Package.webBillingProduct} instead.
*/
readonly rcBillingProduct: Product;
/**
* The {@link Product} assigned to this package.
*/
readonly webBillingProduct: Product;
/**
* The type of package.
*/
readonly packageType: PackageType;
}
/**
* An offering is a collection of {@link Package} available for the user to purchase.
* For more info see https://docs.revenuecat.com/docs/entitlements
* @public
*/
export interface Offering {
/**
* Unique identifier defined in RevenueCat dashboard.
*/
readonly identifier: string;
/**
* Offering description defined in RevenueCat dashboard.
*/
readonly serverDescription: string;
/**
* Offering metadata defined in RevenueCat dashboard.
*/
readonly metadata: { [key: string]: unknown } | null;
/**
* A map of all the packages available for purchase keyed by package ID.
*/
readonly packagesById: { [key: string]: Package };
/**
* A list of all the packages available for purchase.
*/
readonly availablePackages: Package[];
/**
* Lifetime package type configured in the RevenueCat dashboard, if available.
*/
readonly lifetime: Package | null;
/**
* Annual package type configured in the RevenueCat dashboard, if available.
*/
readonly annual: Package | null;
/**
* Six month package type configured in the RevenueCat dashboard, if available.
*/
readonly sixMonth: Package | null;
/**
* Three month package type configured in the RevenueCat dashboard, if available.
*/
readonly threeMonth: Package | null;
/**
* Two month package type configured in the RevenueCat dashboard, if available.
*/
readonly twoMonth: Package | null;
/**
* Monthly package type configured in the RevenueCat dashboard, if available.
*/
readonly monthly: Package | null;
/**
* Weekly package type configured in the RevenueCat dashboard, if available.
*/
readonly weekly: Package | null;
readonly paywall_components: PaywallData | null;
}
/**
* This class contains all the offerings configured in RevenueCat dashboard.
* For more info see https://docs.revenuecat.com/docs/entitlements
* @public
*/
export interface Offerings {
/**
* Dictionary containing all {@link Offering} objects, keyed by their identifier.
*/
readonly all: { [offeringId: string]: Offering };
/**
* Current offering configured in the RevenueCat dashboard.
* It can be `null` if no current offering is configured or if a specific offering
* was requested that is not the current one.
*/
readonly current: Offering | null;
}
/**
* Metadata that can be passed to the backend when making a purchase.
* They will propagate to the payment gateway (i.e. Stripe) and to RevenueCat.
* @public
*/
export type PurchaseMetadata = Record<string, string | null>;
const toPrice = (priceData: PriceResponse): Price => {
return {
amount: priceData.amount_micros / 10000,
amountMicros: priceData.amount_micros,
currency: priceData.currency,
formattedPrice: formatPrice(priceData.amount_micros, priceData.currency),
};
};
const toPricingPhase = (optionPhase: PricingPhaseResponse): PricingPhase => {
const periodDuration = optionPhase.period_duration;
return {
periodDuration: periodDuration,
period: periodDuration ? parseISODuration(periodDuration) : null,
cycleCount: optionPhase.cycle_count,
price: optionPhase.price ? toPrice(optionPhase.price) : null,
} as PricingPhase;
};
const toSubscriptionOption = (
option: SubscriptionOptionResponse,
): SubscriptionOption | null => {
if (option.base == null) {
Logger.debugLog("Missing base phase for subscription option. Ignoring.");
return null;
}
return {
id: option.id,
priceId: option.price_id,
base: toPricingPhase(option.base),
trial: option.trial ? toPricingPhase(option.trial) : null,
} as SubscriptionOption;
};
const toNonSubscriptionOption = (
option: NonSubscriptionOptionResponse,
): NonSubscriptionOption | null => {
if (option.base_price == null) {
Logger.debugLog(
"Missing base price for non-subscription option. Ignoring.",
);
return null;
}
return {
id: option.id,
priceId: option.price_id,
basePrice: toPrice(option.base_price),
} as NonSubscriptionOption;
};
const toProduct = (
productDetailsData: ProductResponse,
presentedOfferingContext: PresentedOfferingContext,
): Product | null => {
const productType = productDetailsData.product_type as ProductType;
if (productType === ProductType.Subscription) {
return toSubscriptionProduct(
productDetailsData,
presentedOfferingContext,
productType,
);
} else {
return toNonSubscriptionProduct(
productDetailsData,
presentedOfferingContext,
productType,
);
}
};
const toNonSubscriptionProduct = (
productDetailsData: ProductResponse,
presentedOfferingContext: PresentedOfferingContext,
productType: ProductType,
): Product | null => {
const nonSubscriptionOptions: {
[optionId: string]: NonSubscriptionOption;
} = {};
Object.entries(productDetailsData.purchase_options).forEach(
([key, value]) => {
const option = toNonSubscriptionOption(
value as NonSubscriptionOptionResponse,
);
if (option != null) {
nonSubscriptionOptions[key] = option;
}
},
);
if (Object.keys(nonSubscriptionOptions).length === 0) {
Logger.debugLog(
`Product ${productDetailsData.identifier} has no purchase options. Ignoring.`,
);
return null;
}
const defaultOptionId = productDetailsData.default_purchase_option_id;
const defaultOption =
defaultOptionId && defaultOptionId in productDetailsData.purchase_options
? nonSubscriptionOptions[defaultOptionId]
: null;
if (defaultOption == null) {
Logger.debugLog(
`Product ${productDetailsData.identifier} has no default purchase option. Ignoring.`,
);
return null;
}
return {
identifier: productDetailsData.identifier,
displayName: productDetailsData.title,
title: productDetailsData.title,
description: productDetailsData.description,
productType: productType,
currentPrice: defaultOption.basePrice,
normalPeriodDuration: null,
presentedOfferingIdentifier: presentedOfferingContext.offeringIdentifier,
presentedOfferingContext: presentedOfferingContext,
defaultPurchaseOption: defaultOption,
defaultSubscriptionOption: null,
subscriptionOptions: {},
defaultNonSubscriptionOption: defaultOption,
};
};
const toSubscriptionProduct = (
productDetailsData: ProductResponse,
presentedOfferingContext: PresentedOfferingContext,
productType: ProductType,
): Product | null => {
const subscriptionOptions: { [optionId: string]: SubscriptionOption } = {};
Object.entries(productDetailsData.purchase_options).forEach(
([key, value]) => {
const option = toSubscriptionOption(value as SubscriptionOptionResponse);
if (option != null) {
subscriptionOptions[key] = option;
}
},
);
if (Object.keys(subscriptionOptions).length === 0) {
Logger.debugLog(
`Product ${productDetailsData.identifier} has no subscription options. Ignoring.`,
);
return null;
}
const defaultOptionId = productDetailsData.default_purchase_option_id;
const defaultOption =
defaultOptionId && defaultOptionId in subscriptionOptions
? subscriptionOptions[defaultOptionId]
: null;
if (defaultOption == null) {
Logger.debugLog(
`Product ${productDetailsData.identifier} has no default subscription option. Ignoring.`,
);
return null;
}
const currentPrice = defaultOption.base.price;
if (currentPrice == null) {
Logger.debugLog(
`Product ${productDetailsData.identifier} default option has no base price. Ignoring.`,
);
return null;
}
return {
identifier: productDetailsData.identifier,
displayName: productDetailsData.title,
title: productDetailsData.title,
description: productDetailsData.description,
productType: productType,
currentPrice: currentPrice,
normalPeriodDuration: defaultOption.base.periodDuration,
presentedOfferingIdentifier: presentedOfferingContext.offeringIdentifier,
presentedOfferingContext: presentedOfferingContext,
defaultPurchaseOption: defaultOption,
defaultSubscriptionOption: defaultOption,
subscriptionOptions: subscriptionOptions,
defaultNonSubscriptionOption: null,
};
};
const toPackage = (
presentedOfferingContext: PresentedOfferingContext,
packageData: PackageResponse,
productDetailsData: { [productId: string]: ProductResponse },
): Package | null => {
const webBillingProduct =
productDetailsData[packageData.platform_product_identifier];
if (webBillingProduct === undefined) return null;
const product = toProduct(webBillingProduct, presentedOfferingContext);
if (product === null) return null;
return {
identifier: packageData.identifier,
rcBillingProduct: product,
webBillingProduct: product,
packageType: getPackageType(packageData.identifier),
};
};
export const toOffering = (
isCurrentOffering: boolean,
offeringsData: OfferingResponse,
productDetailsData: { [productId: string]: ProductResponse },
targetingResponse?: TargetingResponse,
): Offering | null => {
const presentedOfferingContext: PresentedOfferingContext = {
offeringIdentifier: offeringsData.identifier,
targetingContext:
isCurrentOffering && targetingResponse
? {
ruleId: targetingResponse.rule_id,
revision: targetingResponse.revision,
}
: null,
placementIdentifier: null,
};
const packages = offeringsData.packages
.map((p: PackageResponse) =>
toPackage(presentedOfferingContext, p, productDetailsData),
)
.filter(notEmpty);
const packagesById: { [packageId: string]: Package } = {};
for (const p of packages) {
if (p != null) {
packagesById[p.identifier] = p as Package;
}
}
if (packages.length == 0) return null;
return {
identifier: offeringsData.identifier,
serverDescription: offeringsData.description,
metadata: offeringsData.metadata,
packagesById: packagesById,
availablePackages: packages as Package[],
lifetime: packagesById[PackageType.Lifetime] ?? null,
annual: packagesById[PackageType.Annual] ?? null,
sixMonth: packagesById[PackageType.SixMonth] ?? null,
threeMonth: packagesById[PackageType.ThreeMonth] ?? null,
twoMonth: packagesById[PackageType.TwoMonth] ?? null,
monthly: packagesById[PackageType.Monthly] ?? null,
weekly: packagesById[PackageType.Weekly] ?? null,
paywall_components: offeringsData.paywall_components
? (offeringsData.paywall_components as PaywallData)
: null,
};
};
function getPackageType(packageIdentifier: string): PackageType {
switch (packageIdentifier) {
case "$rc_lifetime":
return PackageType.Lifetime;
case "$rc_annual":
return PackageType.Annual;
case "$rc_six_month":
return PackageType.SixMonth;
case "$rc_three_month":
return PackageType.ThreeMonth;
case "$rc_two_month":
return PackageType.TwoMonth;
case "$rc_monthly":
return PackageType.Monthly;
case "$rc_weekly":
return PackageType.Weekly;
default:
if (packageIdentifier.startsWith("$rc_")) {
return PackageType.Unknown;
} else {
return PackageType.Custom;
}
}
}
| yannbf/purchases-js-repro | 0 | TypeScript | yannbf | Yann Braga | chromaui | |
src/entities/purchase-params.ts | TypeScript | import type { Package, PurchaseMetadata, PurchaseOption } from "./offerings";
import type { BrandingAppearance } from "./branding";
/**
* Parameters used to customise the purchase flow when invoking the `.purchase` method.
* @public
*/
export interface PurchaseParams {
/**
* The package you want to purchase. Obtained from {@link Purchases.getOfferings}.
*/
rcPackage: Package;
/**
* The option to be used for this purchase. If not specified or null the default one will be used.
*/
purchaseOption?: PurchaseOption | null;
/**
* The HTML element where the billing view should be added. If undefined, a new div will be created at the root of the page and appended to the body.
*/
htmlTarget?: HTMLElement;
/**
* The email of the user. If undefined, RevenueCat will ask the customer for their email.
*/
customerEmail?: string;
/**
* The locale to use for the purchase flow. If not specified, English will be used
*/
selectedLocale?: string;
/**
* The default locale to use if the selectedLocale is not available.
* Defaults to english.
*/
defaultLocale?: string;
/**
* The purchase metadata to be passed to the backend.
* Any information provided here will be propagated to the payment gateway and
* to the RC transaction as metadata.
*/
metadata?: PurchaseMetadata;
/**
* Defines an optional override for the default branding appearance.
*
* This property is used internally at RevenueCat to handle dynamic themes such
* as the ones coming from the Web Paywall Links. We suggest to use the Dashboard
* configuration to set up the appearance since a configuration passed as parameter
* using this method might break in future releases of `purchases-js`.
*
* @internal
*/
brandingAppearanceOverride?: BrandingAppearance;
}
| yannbf/purchases-js-repro | 0 | TypeScript | yannbf | Yann Braga | chromaui | |
src/entities/purchase-result.ts | TypeScript | import type { CustomerInfo } from "./customer-info";
import type { RedemptionInfo } from "./redemption-info";
/**
* Represents the result of a purchase operation.
* @public
*/
export interface PurchaseResult {
/**
* The customer information after the purchase.
*/
readonly customerInfo: CustomerInfo;
/**
* The redemption information after the purchase if available.
*/
readonly redemptionInfo: RedemptionInfo | null;
/**
* The operation session id of the purchase.
*/
readonly operationSessionId: string;
}
| yannbf/purchases-js-repro | 0 | TypeScript | yannbf | Yann Braga | chromaui | |
src/entities/redemption-info.ts | TypeScript | import type { CheckoutStatusResponse } from "../networking/responses/checkout-status-response";
/**
* This object gives you access to the purchase redemption data when
* the purchase can be redeemed to a mobile user, like in the case of anonymous users.
* @public
*/
export interface RedemptionInfo {
/**
* The redeem url.
*/
readonly redeemUrl: string | null;
}
export function toRedemptionInfo(
operationResponse: CheckoutStatusResponse,
): RedemptionInfo | null {
if (!operationResponse.operation.redemption_info) {
return null;
}
return {
redeemUrl: operationResponse.operation.redemption_info?.redeem_url ?? null,
};
}
| yannbf/purchases-js-repro | 0 | TypeScript | yannbf | Yann Braga | chromaui | |
src/entities/render-paywall-params.ts | TypeScript | import type { Offering } from "./offerings";
/**
* Parameters for the {@link Purchases.renderPaywall} method.
* @public
*/
export interface RenderPaywallParams {
/**
* The identifier of the offering to fetch the paywall for.
* Can be a string identifier or one of the predefined keywords.
*/
readonly offering: Offering;
readonly htmlTarget?: HTMLElement;
readonly purchaseHtmlTarget?: HTMLElement;
readonly customerEmail?: string;
readonly onNavigateToUrl?: (url: string) => void;
readonly onBack?: () => void;
readonly onVisitCustomerCenter?: () => void;
readonly selectedLocale?: string;
}
| yannbf/purchases-js-repro | 0 | TypeScript | yannbf | Yann Braga | chromaui | |
src/helpers/api-key-helper.ts | TypeScript | export function isSandboxApiKey(apiKey: string): boolean {
return apiKey ? apiKey.startsWith("rcb_sb_") : false;
}
| yannbf/purchases-js-repro | 0 | TypeScript | yannbf | Yann Braga | chromaui | |
src/helpers/camel-to-underscore.ts | TypeScript | export function camelToUnderscore(
obj: Record<string, unknown>,
): Record<string, unknown> {
const result: Record<string, unknown> = {};
for (const key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) {
const underscoreKey = key.replace(/([A-Z])/g, "_$1").toLowerCase();
const value = obj[key];
if (value && typeof value === "object" && !Array.isArray(value)) {
result[underscoreKey] = camelToUnderscore(
value as Record<string, unknown>,
);
} else {
result[underscoreKey] = value;
}
}
}
return result;
}
| yannbf/purchases-js-repro | 0 | TypeScript | yannbf | Yann Braga | chromaui | |
src/helpers/configuration-validators.ts | TypeScript | import { ErrorCode, PurchasesError } from "../entities/errors";
import { SDK_HEADERS } from "../networking/http-client";
export function validateApiKey(apiKey: string) {
const api_key_regex = /^rcb_[a-zA-Z0-9_.-]+$/;
if (!api_key_regex.test(apiKey)) {
throw new PurchasesError(
ErrorCode.InvalidCredentialsError,
"Invalid API key. Use your Web Billing API key.",
);
}
}
export function validateAppUserId(appUserId: string) {
const invalidAppUserIds = new Set([
"no_user",
"null",
"none",
"nil",
"(null)",
"NaN",
"\\x00",
"",
"unidentified",
"undefined",
"unknown",
]);
if (invalidAppUserIds.has(appUserId) || appUserId.includes("/")) {
throw new PurchasesError(
ErrorCode.InvalidAppUserIdError,
'Provided user id: "' +
appUserId +
'" is not valid. See https://www.revenuecat.com/docs/customers/user-ids#tips-for-setting-app-user-ids for more information.',
);
}
}
export function validateProxyUrl(proxyUrl?: string) {
if (proxyUrl?.endsWith("/")) {
throw new PurchasesError(
ErrorCode.ConfigurationError,
"Invalid proxy URL. The proxy URL should not end with a trailing slash.",
);
}
}
export function validateAdditionalHeaders(
additionalHeaders?: Record<string, string>,
) {
if (additionalHeaders) {
for (const header in additionalHeaders) {
if (SDK_HEADERS.has(header)) {
throw new PurchasesError(
ErrorCode.ConfigurationError,
`Invalid additional headers. Some headers are reserved for internal use.`,
);
}
}
}
}
| yannbf/purchases-js-repro | 0 | TypeScript | yannbf | Yann Braga | chromaui | |
src/helpers/constants.ts | TypeScript | export const VERSION = "1.0.5";
export const RC_ENDPOINT = import.meta.env.VITE_RC_ENDPOINT as string;
export const RC_ANALYTICS_ENDPOINT = import.meta.env
.VITE_RC_ANALYTICS_ENDPOINT as string;
export const ALLOW_TAX_CALCULATION_FF =
import.meta.env.VITE_ALLOW_TAX_CALCULATION_FF === "true";
| yannbf/purchases-js-repro | 0 | TypeScript | yannbf | Yann Braga | chromaui | |
src/helpers/decorators.ts | TypeScript | import { type Purchases } from "../main";
export function requiresLoadedResources<
This extends Purchases,
Args extends never[],
Result,
>(
target: (this: This, ...args: Args) => Promise<Result>,
// eslint-disable-next-line @typescript-eslint/no-unused-vars
_context: ClassMethodDecoratorContext<
This,
(...args: Args) => Promise<Result>
>,
) {
async function wrapper(this: This, ...args: Args): Promise<Result> {
await this.preload();
return await target.call(this, ...args);
}
return wrapper;
}
| yannbf/purchases-js-repro | 0 | TypeScript | yannbf | Yann Braga | chromaui | |
src/helpers/duration-helper.ts | TypeScript | import { Logger } from "./logger";
/**
* Represents a unit of time.
* @public
*/
export enum PeriodUnit {
Year = "year",
Month = "month",
Week = "week",
Day = "day",
}
/**
* Represents a period of time.
* @public
*/
export interface Period {
/**
* The number of units in the period.
*/
number: number;
/**
* The unit of time.
*/
unit: PeriodUnit;
}
export function parseISODuration(duration: string): Period | null {
const match = duration.match(/^PT?([0-9]+)([MDYW])$/);
if (!match || match.length < 3) {
Logger.errorLog(`Invalid ISO 8601 duration format: ${duration}`);
return null;
}
const numberUnits = parseInt(match[1]);
switch (match[2]) {
case "Y":
return { number: numberUnits, unit: PeriodUnit.Year };
case "M":
return { number: numberUnits, unit: PeriodUnit.Month };
case "W":
return { number: numberUnits, unit: PeriodUnit.Week };
case "D":
return { number: numberUnits, unit: PeriodUnit.Day };
default:
Logger.errorLog(`Invalid ISO 8601 unit duration format: ${duration}`);
return null;
}
}
export function getNextRenewalDate(
startDate: Date,
period: Period,
willRenew: boolean,
): Date | null {
if (!willRenew) {
return null;
}
let result = new Date(startDate);
switch (period.unit) {
case PeriodUnit.Year:
if (
result.getDate() === 29 &&
result.getMonth() === 1 &&
period.number !== 4
) {
result.setFullYear(
result.getFullYear() + period.number,
result.getMonth(),
28,
);
} else {
result.setFullYear(
result.getFullYear() + period.number,
result.getMonth(),
result.getDate(),
);
}
break;
case PeriodUnit.Month:
result.setMonth(result.getMonth() + period.number, result.getDate());
/** If exceeded the last day of the next month, just move over and take the previous day */
if (result.getDate() !== startDate.getDate()) {
result = new Date(startDate);
result.setMonth(result.getMonth() + period.number + 1, 0);
}
break;
case PeriodUnit.Week:
result.setDate(result.getDate() + period.number * 7);
break;
case PeriodUnit.Day:
result.setDate(result.getDate() + period.number);
break;
}
return result;
}
| yannbf/purchases-js-repro | 0 | TypeScript | yannbf | Yann Braga | chromaui | |
src/helpers/logger.ts | TypeScript | import { LogLevel } from "../entities/log-level";
export class Logger {
private static logLevel: LogLevel = LogLevel.Silent;
static setLogLevel(logLevel: LogLevel) {
this.logLevel = logLevel;
}
static log(message: string, logLevel: LogLevel = this.logLevel): void {
const messageWithTag = `[Purchases] ${message}`;
if (this.logLevel < logLevel || logLevel === LogLevel.Silent) {
return;
}
switch (logLevel) {
case LogLevel.Error:
console.error(messageWithTag);
break;
case LogLevel.Warn:
console.warn(messageWithTag);
break;
case LogLevel.Info:
console.info(messageWithTag);
break;
case LogLevel.Debug:
console.debug(messageWithTag);
break;
case LogLevel.Verbose:
console.debug(messageWithTag);
break;
}
}
static errorLog(message: string): void {
this.log(message, LogLevel.Error);
}
static warnLog(message: string): void {
this.log(message, LogLevel.Warn);
}
static infoLog(message: string): void {
this.log(message, LogLevel.Info);
}
static debugLog(message: string): void {
this.log(message, LogLevel.Debug);
}
static verboseLog(message: string): void {
this.log(message, LogLevel.Verbose);
}
}
| yannbf/purchases-js-repro | 0 | TypeScript | yannbf | Yann Braga | chromaui | |
src/helpers/offerings-parser.ts | TypeScript | import {
type OfferingResponse,
type OfferingsResponse,
type PlacementsResponse,
} from "../networking/responses/offerings-response";
import {
type ProductResponse,
type ProductsResponse,
} from "../networking/responses/products-response";
import {
type Offering,
type Offerings,
type Package,
toOffering,
} from "../entities/offerings";
import { Logger } from "./logger";
const addPlacementContextToPackage = (
rcPackage: Package,
placementId: string,
): Package => {
const webBillingProduct = {
...rcPackage.webBillingProduct,
presentedOfferingContext: {
...rcPackage.webBillingProduct.presentedOfferingContext,
placementIdentifier: placementId,
},
};
return {
...rcPackage,
webBillingProduct: webBillingProduct,
rcBillingProduct: webBillingProduct,
};
};
const addPlacementContextToNullablePackage = (
rcPackage: Package | null,
placementId: string,
): Package | null => {
if (rcPackage == null) {
return null;
}
return addPlacementContextToPackage(rcPackage, placementId);
};
export const findOfferingByPlacementId = (
placementsData: PlacementsResponse,
allOfferings: { [offeringId: string]: Offering },
placementId: string,
): Offering | null => {
const offeringIdsByPlacement =
placementsData.offering_ids_by_placement ?? null;
if (offeringIdsByPlacement == null) {
return null;
}
const fallbackOfferingId = placementsData.fallback_offering_id ?? null;
let offering: Offering | undefined;
if (placementId in offeringIdsByPlacement) {
const offeringId = offeringIdsByPlacement[placementId] ?? null;
if (offeringId == null) {
return null;
}
offering = allOfferings[offeringId];
if (offering == undefined) {
offering = allOfferings[fallbackOfferingId];
}
} else {
offering = allOfferings[fallbackOfferingId];
}
if (offering == undefined) {
return null;
}
const packagesById = Object.fromEntries(
Object.entries(offering.packagesById).map(([packageId, rcPackage]) => [
packageId,
addPlacementContextToPackage(rcPackage, placementId),
]),
);
return {
...offering,
packagesById: packagesById,
availablePackages: Object.values(packagesById),
weekly: addPlacementContextToNullablePackage(offering.weekly, placementId),
monthly: addPlacementContextToNullablePackage(
offering.monthly,
placementId,
),
twoMonth: addPlacementContextToNullablePackage(
offering.twoMonth,
placementId,
),
threeMonth: addPlacementContextToNullablePackage(
offering.threeMonth,
placementId,
),
sixMonth: addPlacementContextToNullablePackage(
offering.sixMonth,
placementId,
),
annual: addPlacementContextToNullablePackage(offering.annual, placementId),
lifetime: addPlacementContextToNullablePackage(
offering.lifetime,
placementId,
),
};
};
export function toOfferings(
offeringsData: OfferingsResponse,
productsData: ProductsResponse,
): Offerings {
const productsMap: { [productId: string]: ProductResponse } = {};
productsData.product_details.forEach((p: ProductResponse) => {
productsMap[p.identifier] = p;
});
const allOfferings: { [offeringId: string]: Offering } = {};
offeringsData.offerings.forEach((o: OfferingResponse) => {
const isCurrent = o.identifier === offeringsData.current_offering_id;
const offering = toOffering(
isCurrent,
o,
productsMap,
offeringsData.targeting,
);
if (offering != null) {
allOfferings[o.identifier] = offering;
}
});
const currentOffering: Offering | null = offeringsData.current_offering_id
? (allOfferings[offeringsData.current_offering_id] ?? null)
: null;
if (Object.keys(allOfferings).length == 0) {
Logger.debugLog(
"Empty offerings. Please make sure you've configured offerings correctly in the " +
"RevenueCat dashboard and that the products are properly configured.",
);
}
return {
all: allOfferings,
current: currentOffering,
};
}
| yannbf/purchases-js-repro | 0 | TypeScript | yannbf | Yann Braga | chromaui | |
src/helpers/paywall-variables-helpers.ts | TypeScript | import {
type Offering,
type Package,
type Price,
ProductType,
type PurchaseOption,
type SubscriptionOption,
} from "../entities/offerings";
import { type Period, PeriodUnit } from "./duration-helper";
import { type VariableDictionary } from "@revenuecat/purchases-ui-js";
import { type Translator } from "../ui/localization/translator";
import { LocalizationKeys } from "../ui/localization/supportedLanguages";
function getProductPerType(pkg: Package): PurchaseOption | undefined | null {
return pkg.webBillingProduct.defaultPurchaseOption;
}
function getPricePerPeriod(
formattedPrice: string,
product: SubscriptionOption,
translator: Translator,
full: boolean = false,
) {
return translator.translate(LocalizationKeys.PaywallVariablesPricePerPeriod, {
formattedPrice,
period: product.base.period
? translator.translatePeriod(
product.base.period.number,
product.base.period.unit,
{
noWhitespace: true,
short: !full,
},
)
: "",
});
}
function getDurationInMonths(period: Period, translator: Translator) {
if (period.unit === "year") {
return translator.translatePeriod(period.number * 12, PeriodUnit.Month);
}
return translator.translatePeriod(period.number, period.unit);
}
function getPricePerWeek({
price,
period,
translator,
}: {
price: Price;
period: Period | null;
translator: Translator;
full?: boolean;
}) {
const fallback = translator.formatPrice(price.amountMicros, price.currency);
if (!period) return fallback;
if (period.unit === "year") {
return translator.formatPrice(price.amountMicros / 12 / 4, price.currency);
}
if (period.unit === "month") {
return translator.formatPrice(
price.amountMicros / period.number,
price.currency,
);
}
if (period.unit === "week" && period.number > 1) {
return translator.formatPrice(
price.amountMicros / period.number,
price.currency,
);
}
if (period.unit === "day") {
return translator.formatPrice(
(price.amountMicros * 7) / period.number,
price.currency,
);
}
return fallback;
}
export function getPricePerMonth({
price,
period,
translator,
}: {
price: Price;
period: Period | null;
translator: Translator;
full?: boolean;
}) {
const fallback = translator.formatPrice(price.amountMicros, price.currency);
if (!period || !period.number) return fallback;
if (period.unit === "year") {
return translator.formatPrice(price.amountMicros / 12, price.currency);
}
if (period.unit === "month" && period.number > 1) {
return translator.formatPrice(
price.amountMicros / period.number,
price.currency,
);
}
if (period.unit === "week") {
return translator.formatPrice(
(price.amountMicros * 4) / period.number,
price.currency,
);
}
if (period.unit === "day") {
return translator.formatPrice(
(price.amountMicros * 30) / period.number,
price.currency,
);
}
return fallback;
}
function getTotalPriceAndPerMonth({
price,
period,
full = false,
translator,
}: {
price: Price;
period: Period | null;
full?: boolean;
translator: Translator;
}) {
if (!period || !period.number)
return translator.formatPrice(price.amountMicros, price.currency);
if (period.unit === PeriodUnit.Month && period.number == 1) {
return translator.formatPrice(price.amountMicros, price.currency);
}
let pricePerMonth: string | undefined = "";
switch (period.unit) {
case PeriodUnit.Year:
pricePerMonth = translator.formatPrice(
price.amountMicros / 12,
price.currency,
);
break;
case PeriodUnit.Month:
pricePerMonth = translator.formatPrice(
price.amountMicros / period.number,
price.currency,
);
break;
case PeriodUnit.Week:
pricePerMonth = translator.formatPrice(
(price.amountMicros * 4) / period.number,
price.currency,
);
break;
case PeriodUnit.Day:
pricePerMonth = translator.formatPrice(
(price.amountMicros * 30) / period.number,
price.currency,
);
break;
}
return translator.translate(
LocalizationKeys.PaywallVariablesTotalPriceAndPerMonth,
{
formattedPrice: translator.formatPrice(
price.amountMicros,
price.currency,
),
period: translator.translatePeriod(period.number, period.unit, {
noWhitespace: true,
short: !full,
}),
formattedPricePerMonth: pricePerMonth,
monthPeriod: translator.translatePeriodUnit(PeriodUnit.Month, {
noWhitespace: true,
short: !full,
}),
},
);
}
export function parseOfferingIntoVariables(
offering: Offering,
translator: Translator,
): Record<string, VariableDictionary> {
const packages = offering.availablePackages;
const highestPricePackage = packages.reduce((prev, current) => {
return prev.webBillingProduct.currentPrice.amountMicros >
current.webBillingProduct.currentPrice.amountMicros
? prev
: current;
});
return packages.reduce(
(packagesById, pkg) => {
packagesById[pkg.identifier] = parsePackageIntoVariables(
pkg,
highestPricePackage,
translator,
);
return packagesById;
},
{} as Record<string, VariableDictionary>,
);
}
function parsePackageIntoVariables(
pkg: Package,
highestPricePackage: Package,
translator: Translator,
) {
const webBillingProduct = pkg.webBillingProduct;
const formattedPrice = translator.formatPrice(
webBillingProduct.currentPrice.amountMicros,
webBillingProduct.currentPrice.currency,
);
const product = getProductPerType(pkg);
const productType = webBillingProduct.productType;
const baseObject: VariableDictionary = {
product_name: webBillingProduct.title,
price: formattedPrice,
price_per_period: "",
price_per_period_full: "",
total_price_and_per_month: "",
total_price_and_per_month_full: "",
sub_price_per_month: "",
sub_price_per_week: "",
sub_duration: "",
sub_duration_in_months: "",
sub_period: "",
sub_period_length: "",
sub_period_abbreviated: "",
sub_offer_duration: undefined,
sub_offer_duration_2: undefined, // doesn't apply - only google play
sub_offer_price: undefined,
sub_offer_price_2: undefined, // doesn't apply - only google play
sub_relative_discount: "",
};
if (productType === ProductType.Subscription && product) {
baseObject.price_per_period = getPricePerPeriod(
formattedPrice,
product as SubscriptionOption,
translator,
);
baseObject.price_per_period_full = getPricePerPeriod(
formattedPrice,
product as SubscriptionOption,
translator,
true,
);
const basePeriod = (product as SubscriptionOption).base.period;
baseObject.total_price_and_per_month = getTotalPriceAndPerMonth({
price: webBillingProduct.currentPrice,
period: basePeriod,
translator,
});
baseObject.total_price_and_per_month_full = getTotalPriceAndPerMonth({
price: webBillingProduct.currentPrice,
period: basePeriod,
full: true,
translator,
});
baseObject.sub_price_per_month = getPricePerMonth({
price: webBillingProduct.currentPrice,
period: basePeriod,
translator,
});
baseObject.sub_price_per_week = getPricePerWeek({
price: webBillingProduct.currentPrice,
period: basePeriod,
translator,
});
baseObject.sub_duration = translator.translatePeriod(
basePeriod?.number as number,
basePeriod?.unit as PeriodUnit,
);
baseObject.sub_duration_in_months = getDurationInMonths(
basePeriod as Period,
translator,
);
baseObject.sub_period = translator.translatePeriodFrequency(
basePeriod?.number as number,
basePeriod?.unit as PeriodUnit,
);
baseObject.sub_period_length = basePeriod
? translator.translatePeriodUnit(basePeriod.unit as PeriodUnit, {
noWhitespace: true,
})
: undefined;
baseObject.sub_period_abbreviated = basePeriod
? translator.translatePeriodUnit(basePeriod.unit as PeriodUnit, {
noWhitespace: true,
short: true,
})
: undefined;
const packagePrice = webBillingProduct.currentPrice.amountMicros;
const highestPrice =
highestPricePackage.webBillingProduct.currentPrice.amountMicros;
const discount = (
((highestPrice - packagePrice) * 100) /
highestPrice
).toFixed(0);
baseObject.sub_relative_discount =
packagePrice === highestPrice
? ""
: translator.translate(
LocalizationKeys.PaywallVariablesSubRelativeDiscount,
{
discount: discount,
},
);
}
if (
(productType === ProductType.NonConsumable ||
productType === ProductType.Consumable) &&
product
) {
baseObject.price = formattedPrice;
baseObject.price_per_period = formattedPrice;
baseObject.price_per_period_full = formattedPrice;
baseObject.total_price_and_per_month = formattedPrice;
baseObject.sub_price_per_month = formattedPrice;
baseObject.sub_duration = translator.translate(
LocalizationKeys.PeriodsLifetime,
);
baseObject.sub_duration_in_months = translator.translate(
LocalizationKeys.PeriodsLifetime,
);
baseObject.sub_period = translator.translate(
LocalizationKeys.PeriodsLifetime,
);
baseObject.sub_price_per_week = undefined;
baseObject.sub_relative_discount = undefined;
baseObject.price_per_period_full = formattedPrice;
baseObject.total_price_and_per_month_full = formattedPrice;
baseObject.sub_period_length = undefined;
baseObject.sub_period_abbreviated = undefined;
}
return baseObject;
}
| yannbf/purchases-js-repro | 0 | TypeScript | yannbf | Yann Braga | chromaui | |
src/helpers/price-labels.ts | TypeScript | import { parseISODuration } from "./duration-helper";
import { type Translator } from "../ui/localization/translator";
import { LocalizationKeys } from "../ui/localization/supportedLanguages";
const microsToDollars = (micros: number): number => {
return micros / 1000000;
};
export const formatPrice = (
priceInMicros: number,
currency: string,
locale?: string,
additionalFormattingOptions: {
maximumFractionDigits?: number;
} = {},
): string => {
const price = microsToDollars(priceInMicros);
const formatterOptions: Intl.NumberFormatOptions = {
style: "currency",
currency,
currencyDisplay: "symbol",
...additionalFormattingOptions,
// Some browsers require minimumFractionDigits to be set if maximumFractionDigits is set.
minimumFractionDigits: additionalFormattingOptions.maximumFractionDigits,
};
const formatter = new Intl.NumberFormat(locale, formatterOptions);
const formattedPrice = formatter.format(price);
return formattedPrice.replace("US$", "$");
};
export const getTranslatedPeriodFrequency = (
duration: string,
translator: Translator,
): string => {
const period = parseISODuration(duration);
if (!period) {
return translator.translate(LocalizationKeys.PeriodsUnknownFrequency);
}
return (
translator.translatePeriodFrequency(period.number, period.unit) ||
`${period.number} ${period.unit}s`
);
};
export const getTranslatedPeriodLength = (
isoPeriodString: string,
translator: Translator,
): string => {
const period = parseISODuration(isoPeriodString);
if (!period) {
return isoPeriodString;
}
return (
translator.translatePeriod(period.number, period.unit) ||
`${period.number} ${period.unit}s`
);
};
| yannbf/purchases-js-repro | 0 | TypeScript | yannbf | Yann Braga | chromaui | |
src/helpers/purchase-operation-helper.ts | TypeScript | import {
ErrorCode,
PurchasesError,
type PurchasesErrorExtra,
} from "../entities/errors";
import { type Backend } from "../networking/backend";
import { type CheckoutStartResponse } from "../networking/responses/checkout-start-response";
import {
CheckoutSessionStatus,
type CheckoutStatusError,
CheckoutStatusErrorCodes,
type CheckoutStatusResponse,
} from "../networking/responses/checkout-status-response";
import {
type PresentedOfferingContext,
type Product,
ProductType,
type PurchaseMetadata,
type PurchaseOption,
} from "../entities/offerings";
import { Logger } from "./logger";
import {
type RedemptionInfo,
toRedemptionInfo,
} from "../entities/redemption-info";
import { type IEventsTracker } from "../behavioural-events/events-tracker";
import type { CheckoutCompleteResponse } from "../networking/responses/checkout-complete-response";
import type { CheckoutCalculateTaxResponse } from "../networking/responses/checkout-calculate-tax-response";
export enum PurchaseFlowErrorCode {
ErrorSettingUpPurchase = 0,
ErrorChargingPayment = 1,
UnknownError = 2,
NetworkError = 3,
MissingEmailError = 4,
AlreadyPurchasedError = 5,
}
export class PurchaseFlowError extends Error {
constructor(
public readonly errorCode: PurchaseFlowErrorCode,
message?: string,
public readonly underlyingErrorMessage?: string | null,
public readonly purchasesErrorCode?: ErrorCode,
public readonly extra?: PurchasesErrorExtra,
) {
super(message);
}
isRecoverable(): boolean {
switch (this.errorCode) {
case PurchaseFlowErrorCode.NetworkError:
case PurchaseFlowErrorCode.MissingEmailError:
return true;
case PurchaseFlowErrorCode.ErrorSettingUpPurchase:
case PurchaseFlowErrorCode.ErrorChargingPayment:
case PurchaseFlowErrorCode.AlreadyPurchasedError:
case PurchaseFlowErrorCode.UnknownError:
return false;
}
}
getErrorCode(): number {
return (
this.extra?.backendErrorCode ?? this.purchasesErrorCode ?? this.errorCode
);
}
getPublicErrorMessage(productDetails: Product | null): string {
const errorCode =
this.extra?.backendErrorCode ?? this.purchasesErrorCode ?? this.errorCode;
switch (this.errorCode) {
// TODO: Localize these messages
case PurchaseFlowErrorCode.UnknownError:
return `An unknown error occurred. Error code: ${errorCode}.`;
case PurchaseFlowErrorCode.ErrorSettingUpPurchase:
return `Purchase not started due to an error. Error code: ${errorCode}.`;
case PurchaseFlowErrorCode.ErrorChargingPayment:
return "Payment failed.";
case PurchaseFlowErrorCode.NetworkError:
return "Network error. Please check your internet connection.";
case PurchaseFlowErrorCode.MissingEmailError:
return "Email is required to complete the purchase.";
case PurchaseFlowErrorCode.AlreadyPurchasedError:
if (productDetails?.productType === ProductType.Subscription) {
return "You are already subscribed to this product.";
} else {
return "You have already purchased this product.";
}
}
}
static fromPurchasesError(
e: PurchasesError,
defaultFlowErrorCode: PurchaseFlowErrorCode,
): PurchaseFlowError {
let errorCode: PurchaseFlowErrorCode;
if (e.errorCode === ErrorCode.ProductAlreadyPurchasedError) {
errorCode = PurchaseFlowErrorCode.AlreadyPurchasedError;
} else if (e.errorCode === ErrorCode.InvalidEmailError) {
errorCode = PurchaseFlowErrorCode.MissingEmailError;
} else if (e.errorCode === ErrorCode.NetworkError) {
errorCode = PurchaseFlowErrorCode.NetworkError;
} else {
errorCode = defaultFlowErrorCode;
}
return new PurchaseFlowError(
errorCode,
e.message,
e.underlyingErrorMessage,
e.errorCode,
e.extra,
);
}
}
export class PurchaseOperationHelper {
private operationSessionId: string | null = null;
private readonly backend: Backend;
private readonly eventsTracker: IEventsTracker;
private readonly maxNumberAttempts: number;
private readonly waitMSBetweenAttempts = 1000;
constructor(
backend: Backend,
eventsTracker: IEventsTracker,
maxNumberAttempts: number = 10,
) {
this.backend = backend;
this.eventsTracker = eventsTracker;
this.maxNumberAttempts = maxNumberAttempts;
}
async checkoutStart(
appUserId: string,
productId: string,
purchaseOption: PurchaseOption,
presentedOfferingContext: PresentedOfferingContext,
email?: string,
metadata?: PurchaseMetadata,
): Promise<CheckoutStartResponse> {
try {
const traceId = this.eventsTracker.getTraceId();
const checkoutStartResponse = await this.backend.postCheckoutStart(
appUserId,
productId,
presentedOfferingContext,
purchaseOption,
traceId,
email,
metadata,
);
this.operationSessionId = checkoutStartResponse.operation_session_id;
return checkoutStartResponse;
} catch (error) {
if (error instanceof PurchasesError) {
throw PurchaseFlowError.fromPurchasesError(
error,
PurchaseFlowErrorCode.ErrorSettingUpPurchase,
);
} else {
const errorMessage =
"Unknown error starting purchase: " + String(error);
Logger.errorLog(errorMessage);
throw new PurchaseFlowError(
PurchaseFlowErrorCode.UnknownError,
errorMessage,
);
}
}
}
async checkoutCalculateTax(
countryCode?: string,
postalCode?: string,
): Promise<CheckoutCalculateTaxResponse> {
const operationSessionId = this.operationSessionId;
if (!operationSessionId) {
throw new PurchaseFlowError(
PurchaseFlowErrorCode.ErrorSettingUpPurchase,
"No purchase started",
);
}
try {
const checkoutCalculateTaxResponse =
await this.backend.postCheckoutCalculateTax(
operationSessionId,
countryCode,
postalCode,
);
return checkoutCalculateTaxResponse;
} catch (error) {
if (error instanceof PurchasesError) {
throw PurchaseFlowError.fromPurchasesError(
error,
PurchaseFlowErrorCode.ErrorSettingUpPurchase,
);
} else {
const errorMessage = "Unknown error calculating tax: " + String(error);
Logger.errorLog(errorMessage);
throw new PurchaseFlowError(
PurchaseFlowErrorCode.UnknownError,
errorMessage,
);
}
}
}
async checkoutComplete(email?: string): Promise<CheckoutCompleteResponse> {
const operationSessionId = this.operationSessionId;
if (!operationSessionId) {
throw new PurchaseFlowError(
PurchaseFlowErrorCode.ErrorSettingUpPurchase,
"No purchase started",
);
}
try {
const checkoutCompleteResponse = await this.backend.postCheckoutComplete(
operationSessionId,
email,
);
return checkoutCompleteResponse;
} catch (error) {
if (error instanceof PurchasesError) {
throw PurchaseFlowError.fromPurchasesError(
error,
PurchaseFlowErrorCode.ErrorSettingUpPurchase,
);
} else {
const errorMessage =
"Unknown error starting purchase: " + String(error);
Logger.errorLog(errorMessage);
throw new PurchaseFlowError(
PurchaseFlowErrorCode.UnknownError,
errorMessage,
);
}
}
}
async pollCurrentPurchaseForCompletion(): Promise<{
redemptionInfo: RedemptionInfo | null;
operationSessionId: string;
}> {
const operationSessionId = this.operationSessionId;
if (!operationSessionId) {
throw new PurchaseFlowError(
PurchaseFlowErrorCode.ErrorSettingUpPurchase,
"No purchase in progress",
);
}
return new Promise<{
redemptionInfo: RedemptionInfo | null;
operationSessionId: string;
}>((resolve, reject) => {
const checkForOperationStatus = (checkCount = 1) => {
if (checkCount > this.maxNumberAttempts) {
this.clearPurchaseInProgress();
reject(
new PurchaseFlowError(
PurchaseFlowErrorCode.UnknownError,
"Max attempts reached trying to get successful purchase status",
),
);
return;
}
this.backend
.getCheckoutStatus(operationSessionId)
.then((operationResponse: CheckoutStatusResponse) => {
switch (operationResponse.operation.status) {
case CheckoutSessionStatus.Started:
case CheckoutSessionStatus.InProgress:
setTimeout(
() => checkForOperationStatus(checkCount + 1),
this.waitMSBetweenAttempts,
);
break;
case CheckoutSessionStatus.Succeeded:
this.clearPurchaseInProgress();
resolve({
redemptionInfo: toRedemptionInfo(operationResponse),
operationSessionId: operationSessionId,
});
return;
case CheckoutSessionStatus.Failed:
this.clearPurchaseInProgress();
this.handlePaymentError(
operationResponse.operation.error,
reject,
);
}
})
.catch((error: PurchasesError) => {
const purchasesError = PurchaseFlowError.fromPurchasesError(
error,
PurchaseFlowErrorCode.NetworkError,
);
reject(purchasesError);
});
};
checkForOperationStatus();
});
}
private clearPurchaseInProgress() {
this.operationSessionId = null;
}
private handlePaymentError(
error: CheckoutStatusError | undefined | null,
reject: (error: PurchaseFlowError) => void,
) {
if (error === null || error === undefined) {
reject(
new PurchaseFlowError(
PurchaseFlowErrorCode.UnknownError,
"Got an error status but error field is empty.",
),
);
return;
}
switch (error.code) {
case CheckoutStatusErrorCodes.SetupIntentCreationFailed:
reject(
new PurchaseFlowError(
PurchaseFlowErrorCode.ErrorSettingUpPurchase,
"Setup intent creation failed",
),
);
return;
case CheckoutStatusErrorCodes.PaymentMethodCreationFailed:
reject(
new PurchaseFlowError(
PurchaseFlowErrorCode.ErrorSettingUpPurchase,
"Payment method creation failed",
),
);
return;
case CheckoutStatusErrorCodes.PaymentChargeFailed:
reject(
new PurchaseFlowError(
PurchaseFlowErrorCode.ErrorChargingPayment,
"Payment charge failed",
),
);
return;
case CheckoutStatusErrorCodes.SetupIntentCompletionFailed:
reject(
new PurchaseFlowError(
PurchaseFlowErrorCode.ErrorSettingUpPurchase,
"Setup intent completion failed",
),
);
return;
case CheckoutStatusErrorCodes.AlreadyPurchased:
reject(
new PurchaseFlowError(
PurchaseFlowErrorCode.AlreadyPurchasedError,
"Purchased was already completed",
),
);
return;
default:
reject(
new PurchaseFlowError(
PurchaseFlowErrorCode.UnknownError,
"Unknown error code received",
),
);
return;
}
}
}
| yannbf/purchases-js-repro | 0 | TypeScript | yannbf | Yann Braga | chromaui | |
src/helpers/string-helpers.ts | TypeScript | export const capitalize = (value: string) => {
try {
return value.charAt(0).toUpperCase() + value.slice(1);
} catch {
return value;
}
};
| yannbf/purchases-js-repro | 0 | TypeScript | yannbf | Yann Braga | chromaui | |
src/helpers/type-helper.ts | TypeScript | export function notEmpty<Type>(value: Type | null | undefined): value is Type {
return value !== null && value !== undefined;
}
| yannbf/purchases-js-repro | 0 | TypeScript | yannbf | Yann Braga | chromaui | |
src/helpers/utm-params.ts | TypeScript | export const autoParseUTMParams = () => {
const params = new URLSearchParams(window.location.search);
const possibleParams = [
"utm_source",
"utm_medium",
"utm_campaign",
"utm_term",
"utm_content",
];
const utmParams: { [key: string]: string } = {};
possibleParams.forEach((param) => {
const paramValue = params.get(param);
if (paramValue !== null) {
utmParams[param] = paramValue;
}
});
return utmParams;
};
| yannbf/purchases-js-repro | 0 | TypeScript | yannbf | Yann Braga | chromaui | |
src/helpers/uuid-helper.ts | TypeScript | /**
* Generates a UUID v4 string.
* Uses crypto.randomUUID if available, otherwise falls back to a manual implementation.
* @returns A UUID v4 string in the format xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
*/
export function generateUUID(): string {
if (crypto && crypto.randomUUID) {
return crypto.randomUUID();
}
const bytes = new Uint8Array(16);
if (crypto && crypto.getRandomValues) {
crypto.getRandomValues(bytes);
} else {
for (let i = 0; i < 16; i++) {
bytes[i] = Math.floor(Math.random() * 256);
}
}
// Set version (4) and variant bits
bytes[6] = (bytes[6] & 0x0f) | 0x40; // version 4
bytes[8] = (bytes[8] & 0x3f) | 0x80; // variant
const hex = Array.from(bytes).map((b) => b.toString(16).padStart(2, "0"));
return [
hex.slice(0, 4).join(""),
hex.slice(4, 6).join(""),
hex.slice(6, 8).join(""),
hex.slice(8, 10).join(""),
hex.slice(10, 16).join(""),
].join("-");
}
| yannbf/purchases-js-repro | 0 | TypeScript | yannbf | Yann Braga | chromaui | |
src/helpers/validators.ts | TypeScript | import { Logger } from "./logger";
import { ErrorCode, PurchasesError } from "../entities/errors";
export function validateEmail(email: string): string | null {
if (email.trim() === "") {
return "You need to provide your email address to continue.";
} else if (!email.match(/^[^@]+@[^@]+\.[^@]+$/)) {
return "Email is not valid. Please provide a valid email address.";
}
return null;
}
export function validateCurrency(currency?: string) {
if (currency && !currency.match(/^[A-Z]{3}$/)) {
const errorMessage = `Currency code ${currency} is not valid. Please provide a valid ISO 4217 currency code.`;
Logger.errorLog(errorMessage);
throw new PurchasesError(ErrorCode.ConfigurationError, errorMessage);
}
}
| yannbf/purchases-js-repro | 0 | TypeScript | yannbf | Yann Braga | chromaui | |
src/main.ts | TypeScript | import type { Offering, Offerings, Package } from "./entities/offerings";
import PurchasesUi from "./ui/purchases-ui.svelte";
import { type CustomerInfo, toCustomerInfo } from "./entities/customer-info";
import {
ErrorCode,
PurchasesError,
UninitializedPurchasesError,
} from "./entities/errors";
import {
type OfferingResponse,
type OfferingsResponse,
type PackageResponse,
} from "./networking/responses/offerings-response";
import { type ProductResponse } from "./networking/responses/products-response";
import { RC_ENDPOINT } from "./helpers/constants";
import { Backend } from "./networking/backend";
import { isSandboxApiKey } from "./helpers/api-key-helper";
import {
type PurchaseFlowError,
PurchaseOperationHelper,
} from "./helpers/purchase-operation-helper";
import { type LogLevel } from "./entities/log-level";
import { Logger } from "./helpers/logger";
import {
validateAdditionalHeaders,
validateApiKey,
validateAppUserId,
validateProxyUrl,
} from "./helpers/configuration-validators";
import { type PurchaseParams } from "./entities/purchase-params";
import { defaultHttpConfig, type HttpConfig } from "./entities/http-config";
import {
type GetOfferingsParams,
OfferingKeyword,
} from "./entities/get-offerings-params";
import { validateCurrency } from "./helpers/validators";
import { type BrandingInfoResponse } from "./networking/responses/branding-response";
import { requiresLoadedResources } from "./helpers/decorators";
import {
findOfferingByPlacementId,
toOfferings,
} from "./helpers/offerings-parser";
import { type RedemptionInfo } from "./entities/redemption-info";
import { type PurchaseResult } from "./entities/purchase-result";
import { mount, unmount } from "svelte";
import { type RenderPaywallParams } from "./entities/render-paywall-params";
import { Paywall } from "@revenuecat/purchases-ui-js";
import { PaywallDefaultContainerZIndex } from "./ui/theme/constants";
import { parseOfferingIntoVariables } from "./helpers/paywall-variables-helpers";
import { Translator } from "./ui/localization/translator";
import { englishLocale } from "./ui/localization/constants";
import type { TrackEventProps } from "./behavioural-events/events-tracker";
import EventsTracker, {
type IEventsTracker,
} from "./behavioural-events/events-tracker";
import {
createCheckoutSessionEndClosedEvent,
createCheckoutSessionEndErroredEvent,
createCheckoutSessionEndFinishedEvent,
createCheckoutSessionStartEvent,
} from "./behavioural-events/sdk-event-helpers";
import { SDKEventName } from "./behavioural-events/sdk-events";
import { autoParseUTMParams } from "./helpers/utm-params";
import { defaultFlagsConfig, type FlagsConfig } from "./entities/flags-config";
import { generateUUID } from "./helpers/uuid-helper";
export { ProductType } from "./entities/offerings";
export type {
NonSubscriptionOption,
Offering,
Offerings,
Package,
Product,
PresentedOfferingContext,
Price,
PurchaseOption,
PurchaseMetadata,
SubscriptionOption,
TargetingContext,
PricingPhase,
} from "./entities/offerings";
export { PackageType } from "./entities/offerings";
export type { CustomerInfo } from "./entities/customer-info";
export type {
EntitlementInfos,
EntitlementInfo,
Store,
PeriodType,
} from "./entities/customer-info";
export {
ErrorCode,
PurchasesError,
UninitializedPurchasesError,
} from "./entities/errors";
export type { PurchasesErrorExtra } from "./entities/errors";
export type { Period, PeriodUnit } from "./helpers/duration-helper";
export type { HttpConfig } from "./entities/http-config";
export type { FlagsConfig } from "./entities/flags-config";
export { LogLevel } from "./entities/log-level";
export type { GetOfferingsParams } from "./entities/get-offerings-params";
export { OfferingKeyword } from "./entities/get-offerings-params";
export type { PurchaseParams } from "./entities/purchase-params";
export type { RedemptionInfo } from "./entities/redemption-info";
export type { PurchaseResult } from "./entities/purchase-result";
export type { BrandingAppearance } from "./entities/branding";
const ANONYMOUS_PREFIX = "$RCAnonymousID:";
/**
* Entry point for Purchases SDK. It should be instantiated as soon as your
* app is started. Only one instance of Purchases should be instantiated
* at a time!
* @public
*/
export class Purchases {
/** @internal */
readonly _API_KEY: string;
/** @internal */
private _appUserId: string;
/** @internal */
private _brandingInfo: BrandingInfoResponse | null = null;
/** @internal */
private _loadingResourcesPromise: Promise<void> | null = null;
/** @internal */
private readonly _flags: FlagsConfig;
/** @internal */
private readonly backend: Backend;
/** @internal */
private readonly purchaseOperationHelper: PurchaseOperationHelper;
/** @internal */
private readonly eventsTracker: IEventsTracker;
/** @internal */
private static instance: Purchases | undefined = undefined;
/**
* Set the log level. Logs of the given level and below will be printed
* in the console.
* Default is `LogLevel.Silent` so no logs will be printed in the console.
* @param logLevel - LogLevel to set.
*/
static setLogLevel(logLevel: LogLevel) {
Logger.setLogLevel(logLevel);
}
/**
* Get the singleton instance of Purchases. It's preferred to use the instance
* obtained from the {@link Purchases.configure} method when possible.
* @throws {@link UninitializedPurchasesError} if the instance has not been initialized yet.
*/
static getSharedInstance(): Purchases {
if (Purchases.isConfigured()) {
return Purchases.instance!;
}
throw new UninitializedPurchasesError();
}
/**
* Returns whether the Purchases SDK is configured or not.
*/
static isConfigured(): boolean {
return Purchases.instance !== undefined;
}
/**
* Configures the Purchases SDK. This should be called as soon as your app
* has a unique user id for your user. You should only call this once, and
* keep the returned instance around for use throughout your application.
* @param apiKey - RevenueCat API Key. Can be obtained from the RevenueCat dashboard.
* @param appUserId - Your unique id for identifying the user.
* @param httpConfig - Advanced http configuration to customise the SDK usage {@link HttpConfig}.
* @param flags - Advanced functionality configuration {@link FlagsConfig}.
* @throws {@link PurchasesError} if the API key or user id are invalid.
*/
static configure(
apiKey: string,
appUserId: string,
httpConfig: HttpConfig = defaultHttpConfig,
flags: FlagsConfig = defaultFlagsConfig,
): Purchases {
if (Purchases.instance !== undefined) {
Logger.warnLog(
"Purchases is already initialized. You normally should only configure Purchases once. " +
"Creating and returning new instance.",
);
}
validateApiKey(apiKey);
validateAppUserId(appUserId);
validateProxyUrl(httpConfig.proxyURL);
validateAdditionalHeaders(httpConfig.additionalHeaders);
Purchases.instance = new Purchases(apiKey, appUserId, httpConfig, flags);
return Purchases.getSharedInstance();
}
/**
* Loads and caches some optional data in the Purchases SDK.
* Currently only fetching branding information.
* You can call this method after configuring the SDK to speed
* up the first call to {@link Purchases.purchase}.
*/
public async preload(): Promise<void> {
if (this.hasLoadedResources()) {
Logger.verboseLog("Purchases resources are loaded. Skipping.");
return;
}
if (this._loadingResourcesPromise !== null) {
Logger.verboseLog("Purchases resources are loading. Waiting.");
await this._loadingResourcesPromise;
return;
}
this._loadingResourcesPromise = this.fetchAndCacheBrandingInfo()
.catch((e) => {
let errorMessage = `${e}`;
if (e instanceof PurchasesError) {
errorMessage = `${e.message}. ${e.underlyingErrorMessage ? `Underlying error: ${e.underlyingErrorMessage}` : ""}`;
}
Logger.errorLog(`Error fetching branding info: ${errorMessage}`);
})
.finally(() => {
this._loadingResourcesPromise = null;
});
return this._loadingResourcesPromise;
}
/** @internal */
private fetchAndCacheBrandingInfo(): Promise<void> {
return this.backend.getBrandingInfo().then((brandingInfo) => {
this._brandingInfo = brandingInfo;
});
}
/** @internal */
private hasLoadedResources(): boolean {
return this._brandingInfo !== null;
}
/** @internal */
private constructor(
apiKey: string,
appUserId: string,
httpConfig: HttpConfig = defaultHttpConfig,
flags: FlagsConfig = defaultFlagsConfig,
) {
this._API_KEY = apiKey;
this._appUserId = appUserId;
this._flags = { ...defaultFlagsConfig, ...flags };
if (RC_ENDPOINT === undefined) {
Logger.errorLog(
"Project was build without some of the environment variables set",
);
}
if (isSandboxApiKey(apiKey)) {
Logger.debugLog("Initializing Purchases SDK with sandbox API Key");
}
this.eventsTracker = new EventsTracker({
apiKey: this._API_KEY,
appUserId: this._appUserId,
silent: !this._flags.collectAnalyticsEvents,
});
this.backend = new Backend(this._API_KEY, httpConfig);
this.purchaseOperationHelper = new PurchaseOperationHelper(
this.backend,
this.eventsTracker,
);
this.eventsTracker.trackSDKEvent({
eventName: SDKEventName.SDKInitialized,
});
}
/**
* Renders an RC Paywall and allows the user to purchase from it using Web Billing.
* @experimental
* @internal
* @param paywallParams - The parameters object to customise the paywall render. Check {@link RenderPaywallParams}
* @returns Promise<PurchaseResult>
*/
public async renderPaywall(
paywallParams: RenderPaywallParams,
): Promise<PurchaseResult> {
console.warn(
"This method is @experimental, Paywalls are not generally available but they will come soon!",
);
const htmlTarget = paywallParams.htmlTarget;
let resolvedHTMLTarget =
htmlTarget ?? document.getElementById("rcb-ui-pw-root");
if (resolvedHTMLTarget === null) {
const element = document.createElement("div");
element.id = "rcb-ui-pw-root";
element.className = "rcb-ui-pw-root";
// one point less than the purchase flow modal.
element.style.zIndex = `${PaywallDefaultContainerZIndex}`;
document.body.appendChild(element);
resolvedHTMLTarget = element;
}
if (resolvedHTMLTarget === null) {
throw new Error(
"Could not generate a mount point for the billing widget",
);
}
const certainHTMLTarget = resolvedHTMLTarget as unknown as HTMLElement;
// cleanup whatever is already there.
certainHTMLTarget.innerHTML = "";
const offering = paywallParams.offering;
if (!offering.paywall_components) {
throw new Error("You cannot use paywalls yet, they are coming soon!");
}
const selectedLocale = paywallParams.selectedLocale || navigator.language;
const translator = new Translator(
{},
selectedLocale,
offering.paywall_components.default_locale,
);
const startPurchaseFlow = (
selectedPackageId: string,
): Promise<PurchaseResult> => {
const pkg = offering.availablePackages.find(
(p) => p.identifier === selectedPackageId,
);
if (pkg === undefined) {
throw new Error(`No package found for ${selectedPackageId}`);
}
return this.purchase({
rcPackage: pkg,
htmlTarget: paywallParams.purchaseHtmlTarget,
customerEmail: paywallParams.customerEmail,
selectedLocale: selectedLocale,
defaultLocale:
offering.paywall_components?.default_locale || englishLocale,
});
};
const navigateToUrl = (url: string) => {
if (paywallParams.onNavigateToUrl) {
paywallParams.onNavigateToUrl(url);
return;
}
// Opinionated approach:
// navigating to the URL in a new tab.
window.open(url, "_blank")?.focus();
};
const onRestorePurchasesClicked = () => {
// DO NOTHING
};
const onVisitCustomerCenterClicked = () => {
if (paywallParams.onVisitCustomerCenter) {
paywallParams.onVisitCustomerCenter();
return;
}
// DO NOTHING, RC's customer center is not supported in web
};
const variablesPerPackage = parseOfferingIntoVariables(
offering,
translator,
);
return new Promise((resolve, reject) => {
mount(Paywall, {
target: certainHTMLTarget,
props: {
paywallData: offering.paywall_components!,
selectedLocale: selectedLocale,
onNavigateToUrlClicked: navigateToUrl,
onVisitCustomerCenterClicked: onVisitCustomerCenterClicked,
onBackClicked: () => {
if (paywallParams.onBack) {
paywallParams.onBack();
return;
}
// Opinionated approach
// closing the current purchase and emptying the paywall.
certainHTMLTarget.innerHTML = "";
Logger.debugLog("Purchase cancelled by user");
reject(new PurchasesError(ErrorCode.UserCancelledError));
},
onRestorePurchasesClicked: onRestorePurchasesClicked,
onPurchaseClicked: (selectedPackageId: string) => {
startPurchaseFlow(selectedPackageId)
.then((purchaseResult) => {
resolve(purchaseResult);
})
.catch((err) => reject(err));
},
onError: (err: unknown) => reject(err),
variablesPerPackage,
},
});
});
}
/**
* Fetch the configured offerings for this user. You can configure these
* in the RevenueCat dashboard.
* @param params - The parameters object to customise the offerings fetch. Check {@link GetOfferingsParams}
*/
public async getOfferings(params?: GetOfferingsParams): Promise<Offerings> {
validateCurrency(params?.currency);
const appUserId = this._appUserId;
const offeringsResponse = await this.backend.getOfferings(appUserId);
const offeringIdFilter =
params?.offeringIdentifier === OfferingKeyword.Current
? offeringsResponse.current_offering_id
: params?.offeringIdentifier;
if (offeringIdFilter) {
offeringsResponse.offerings = offeringsResponse.offerings.filter(
(offering: OfferingResponse) =>
offering.identifier === offeringIdFilter,
);
}
return await this.getAllOfferings(offeringsResponse, appUserId, params);
}
/**
* Retrieves a specific offering by a placement identifier.
* For more info see https://www.revenuecat.com/docs/tools/targeting
* @param placementIdentifier - The placement identifier to retrieve the offering for.
* @param params - The parameters object to customise the offerings fetch. Check {@link GetOfferingsParams}
*/
public async getCurrentOfferingForPlacement(
placementIdentifier: string,
params?: GetOfferingsParams,
): Promise<Offering | null> {
const appUserId = this._appUserId;
const offeringsResponse = await this.backend.getOfferings(appUserId);
const offerings = await this.getAllOfferings(
offeringsResponse,
appUserId,
params,
);
const placementData = offeringsResponse.placements ?? null;
if (placementData == null) {
return null;
}
return findOfferingByPlacementId(
placementData,
offerings.all,
placementIdentifier,
);
}
private async getAllOfferings(
offeringsResponse: OfferingsResponse,
appUserId: string,
params?: GetOfferingsParams,
): Promise<Offerings> {
const productIds = offeringsResponse.offerings
.flatMap((o: OfferingResponse) => o.packages)
.map((p: PackageResponse) => p.platform_product_identifier);
const productsResponse = await this.backend.getProducts(
appUserId,
productIds,
params?.currency,
);
this.logMissingProductIds(productIds, productsResponse.product_details);
return toOfferings(offeringsResponse, productsResponse);
}
/**
* Convenience method to check whether a user is entitled to a specific
* entitlement. This will use {@link Purchases.getCustomerInfo} under the hood.
* @param entitlementIdentifier - The entitlement identifier you want to check.
* @returns Whether the user is entitled to the specified entitlement
* @throws {@link PurchasesError} if there is an error while fetching the customer info.
* @see {@link Purchases.getCustomerInfo}
*/
public async isEntitledTo(entitlementIdentifier: string): Promise<boolean> {
const customerInfo = await this.getCustomerInfo();
return entitlementIdentifier in customerInfo.entitlements.active;
}
/**
* Method to perform a purchase for a given package. You can obtain the
* package from {@link Purchases.getOfferings}. This method will present the purchase
* form on your site, using the given HTML element as the mount point, if
* provided, or as a modal if not.
* @deprecated - please use .purchase
* @param rcPackage - The package you want to purchase. Obtained from {@link Purchases.getOfferings}.
* @param customerEmail - The email of the user. If undefined, RevenueCat will ask the customer for their email.
* @param htmlTarget - The HTML element where the billing view should be added. If undefined, a new div will be created at the root of the page and appended to the body.
* @returns a Promise for the customer info after the purchase is completed successfully.
* @throws {@link PurchasesError} if there is an error while performing the purchase. If the {@link PurchasesError.errorCode} is {@link ErrorCode.UserCancelledError}, the user cancelled the purchase.
*/
public purchasePackage(
rcPackage: Package,
customerEmail?: string,
htmlTarget?: HTMLElement,
): Promise<PurchaseResult> {
return this.purchase({
rcPackage,
customerEmail,
htmlTarget,
});
}
/**
* Method to perform a purchase for a given package. You can obtain the
* package from {@link Purchases.getOfferings}. This method will present the purchase
* form on your site, using the given HTML element as the mount point, if
* provided, or as a modal if not.
* @param params - The parameters object to customise the purchase flow. Check {@link PurchaseParams}
* @returns a Promise for the customer and redemption info after the purchase is completed successfully.
* @throws {@link PurchasesError} if there is an error while performing the purchase. If the {@link PurchasesError.errorCode} is {@link ErrorCode.UserCancelledError}, the user cancelled the purchase.
*/
@requiresLoadedResources
public purchase(params: PurchaseParams): Promise<PurchaseResult> {
const {
rcPackage,
purchaseOption,
htmlTarget,
customerEmail,
selectedLocale = englishLocale,
defaultLocale = englishLocale,
} = params;
let resolvedHTMLTarget =
htmlTarget ?? document.getElementById("rcb-ui-root");
if (resolvedHTMLTarget === null) {
const element = document.createElement("div");
element.className = "rcb-ui-root";
document.body.appendChild(element);
resolvedHTMLTarget = element;
}
if (resolvedHTMLTarget === null) {
throw new Error(
"Could not generate a mount point for the billing widget",
);
}
const certainHTMLTarget = resolvedHTMLTarget as unknown as HTMLElement;
const appUserId = this._appUserId;
Logger.debugLog(
`Presenting purchase form for package ${rcPackage.identifier}`,
);
const localeToBeUsed = selectedLocale || defaultLocale;
const purchaseOptionToUse =
purchaseOption ?? rcPackage.webBillingProduct.defaultPurchaseOption;
const event = createCheckoutSessionStartEvent({
appearance: this._brandingInfo?.appearance,
rcPackage,
purchaseOptionToUse,
customerEmail,
});
this.eventsTracker.trackSDKEvent(event);
const utmParamsMetadata = this._flags.autoCollectUTMAsMetadata
? autoParseUTMParams()
: {};
const metadata = { ...utmParamsMetadata, ...(params.metadata || {}) };
let component: ReturnType<typeof mount> | null = null;
const finalBrandingInfo: BrandingInfoResponse | null = this._brandingInfo;
if (finalBrandingInfo && params.brandingAppearanceOverride) {
finalBrandingInfo.appearance = params.brandingAppearanceOverride;
}
const isInElement = htmlTarget !== undefined;
return new Promise((resolve, reject) => {
if (!isInElement) {
window.history.pushState({ checkoutOpen: true }, "");
}
const onClose = () => {
const event = createCheckoutSessionEndClosedEvent();
this.eventsTracker.trackSDKEvent(event);
window.removeEventListener("popstate", onClose);
if (component) {
unmount(component);
}
certainHTMLTarget.innerHTML = "";
Logger.debugLog("Purchase cancelled by user");
reject(new PurchasesError(ErrorCode.UserCancelledError));
};
if (!isInElement) {
window.addEventListener("popstate", onClose);
}
const onFinished = async (
operationSessionId: string,
redemptionInfo: RedemptionInfo | null,
) => {
const event = createCheckoutSessionEndFinishedEvent({
redemptionInfo,
});
this.eventsTracker.trackSDKEvent(event);
Logger.debugLog("Purchase finished");
if (component) {
unmount(component);
}
certainHTMLTarget.innerHTML = "";
// TODO: Add info about transaction in result.
const purchaseResult: PurchaseResult = {
customerInfo: await this._getCustomerInfoForUserId(appUserId),
redemptionInfo: redemptionInfo,
operationSessionId: operationSessionId,
};
resolve(purchaseResult);
};
const onError = (e: PurchaseFlowError) => {
const event = createCheckoutSessionEndErroredEvent({
errorCode: e.errorCode?.toString(),
errorMessage: e.message,
});
this.eventsTracker.trackSDKEvent(event);
if (component) {
unmount(component);
}
certainHTMLTarget.innerHTML = "";
reject(PurchasesError.getForPurchasesFlowError(e));
};
component = mount(PurchasesUi, {
target: certainHTMLTarget,
props: {
isInElement: isInElement,
appUserId,
rcPackage,
purchaseOption: purchaseOptionToUse,
customerEmail,
onFinished,
onClose,
onError,
purchases: this,
eventsTracker: this.eventsTracker,
brandingInfo: this._brandingInfo,
purchaseOperationHelper: this.purchaseOperationHelper,
selectedLocale: localeToBeUsed,
metadata: metadata,
defaultLocale,
},
});
});
}
/**
* Gets latest available {@link CustomerInfo}.
* @returns The latest {@link CustomerInfo}.
* @throws {@link PurchasesError} if there is an error while fetching the customer info.
*/
public async getCustomerInfo(): Promise<CustomerInfo> {
return await this._getCustomerInfoForUserId(this._appUserId);
}
/**
* Gets the current app user id.
*/
public getAppUserId(): string {
return this._appUserId;
}
/**
* Change the current app user id. Returns the customer info for the new
* user id.
* @param newAppUserId - The user id to change to.
*/
public async changeUser(newAppUserId: string): Promise<CustomerInfo> {
validateAppUserId(newAppUserId);
this._appUserId = newAppUserId;
this.eventsTracker.updateUser(newAppUserId);
// TODO: Cancel all pending requests if any.
// TODO: What happens with a possibly initialized purchase?
return await this.getCustomerInfo();
}
/** @internal */
private logMissingProductIds(
productIds: string[],
productDetails: ProductResponse[],
) {
const foundProductIdsMap: { [productId: string]: ProductResponse } = {};
productDetails.forEach(
(ent: ProductResponse) => (foundProductIdsMap[ent.identifier] = ent),
);
const missingProductIds: string[] = [];
productIds.forEach((productId: string) => {
if (foundProductIdsMap[productId] === undefined) {
missingProductIds.push(productId);
}
});
if (missingProductIds.length > 0) {
Logger.debugLog(
`Could not find product data for product ids:
${missingProductIds.join()}.
Please check that your product configuration is correct.`,
);
}
}
/**
* @returns Whether the SDK is using a sandbox API Key.
*/
public isSandbox(): boolean {
return isSandboxApiKey(this._API_KEY);
}
/**
* Closes the Purchases instance. You should never have to do this normally.
*/
public close() {
if (Purchases.instance === this) {
if (this.eventsTracker) {
this.eventsTracker.dispose();
}
Purchases.instance = undefined;
} else {
Logger.warnLog(
"Trying to close a Purchases instance that is not the current instance. Ignoring.",
);
}
}
/** @internal */
private async _getCustomerInfoForUserId(
appUserId: string,
): Promise<CustomerInfo> {
const subscriberResponse = await this.backend.getCustomerInfo(appUserId);
return toCustomerInfo(subscriberResponse);
}
/**
* Generates an anonymous app user ID that follows RevenueCat's format.
* This can be used when you don't have a user identifier system in place.
* The generated ID will be in the format: $RCAnonymousID:\<UUID without dashes\>
* Example: $RCAnonymousID:123e4567e89b12d3a456426614174000
* @returns A new anonymous app user ID string
* @public
*/
public static generateRevenueCatAnonymousAppUserId(): string {
return `${ANONYMOUS_PREFIX}${generateUUID().replace(/-/g, "")}`;
}
/**
* Track an event.
* @param props - The properties of the event.
* @internal
*/
public _trackEvent(props: TrackEventProps): void {
this.eventsTracker.trackExternalEvent(props);
}
}
| yannbf/purchases-js-repro | 0 | TypeScript | yannbf | Yann Braga | chromaui | |
src/networking/assets.ts | TypeScript | export const buildAssetURL = (assetPath: string): string => {
const assetsBaseUrl = (import.meta.env.VITE_ASSETS_ENDPOINT as string) || "";
return `${assetsBaseUrl}/${assetPath}`;
};
| yannbf/purchases-js-repro | 0 | TypeScript | yannbf | Yann Braga | chromaui | |
src/networking/backend.ts | TypeScript | import { type OfferingsResponse } from "./responses/offerings-response";
import { performRequest } from "./http-client";
import {
CheckoutCalculateTaxEndpoint,
CheckoutCompleteEndpoint,
CheckoutStartEndpoint,
GetBrandingInfoEndpoint,
GetCheckoutStatusEndpoint,
GetCustomerInfoEndpoint,
GetOfferingsEndpoint,
GetProductsEndpoint,
} from "./endpoints";
import { type SubscriberResponse } from "./responses/subscriber-response";
import type { CheckoutStartResponse } from "./responses/checkout-start-response";
import { type ProductsResponse } from "./responses/products-response";
import { type BrandingInfoResponse } from "./responses/branding-response";
import { type CheckoutStatusResponse } from "./responses/checkout-status-response";
import { defaultHttpConfig, type HttpConfig } from "../entities/http-config";
import type {
PresentedOfferingContext,
PurchaseMetadata,
PurchaseOption,
} from "../entities/offerings";
import type { CheckoutCompleteResponse } from "./responses/checkout-complete-response";
import type { CheckoutCalculateTaxResponse } from "./responses/checkout-calculate-tax-response";
export class Backend {
private readonly API_KEY: string;
private readonly httpConfig: HttpConfig;
constructor(API_KEY: string, httpConfig: HttpConfig = defaultHttpConfig) {
this.API_KEY = API_KEY;
this.httpConfig = httpConfig;
}
async getOfferings(appUserId: string): Promise<OfferingsResponse> {
return await performRequest<null, OfferingsResponse>(
new GetOfferingsEndpoint(appUserId),
{
apiKey: this.API_KEY,
httpConfig: this.httpConfig,
},
);
}
async getCustomerInfo(appUserId: string): Promise<SubscriberResponse> {
return await performRequest<null, SubscriberResponse>(
new GetCustomerInfoEndpoint(appUserId),
{
apiKey: this.API_KEY,
httpConfig: this.httpConfig,
},
);
}
async getProducts(
appUserId: string,
productIds: string[],
currency?: string,
): Promise<ProductsResponse> {
return await performRequest<null, ProductsResponse>(
new GetProductsEndpoint(appUserId, productIds, currency),
{
apiKey: this.API_KEY,
httpConfig: this.httpConfig,
},
);
}
async getBrandingInfo(): Promise<BrandingInfoResponse> {
return await performRequest<null, BrandingInfoResponse>(
new GetBrandingInfoEndpoint(),
{
apiKey: this.API_KEY,
httpConfig: this.httpConfig,
},
);
}
async postCheckoutStart(
appUserId: string,
productId: string,
presentedOfferingContext: PresentedOfferingContext,
purchaseOption: PurchaseOption,
traceId: string,
email?: string,
metadata: PurchaseMetadata | undefined = undefined,
): Promise<CheckoutStartResponse> {
type CheckoutStartRequestBody = {
app_user_id: string;
product_id: string;
presented_offering_identifier: string;
price_id: string;
presented_placement_identifier?: string;
offer_id?: string;
applied_targeting_rule?: {
rule_id: string;
revision: number;
};
email?: string;
metadata?: PurchaseMetadata;
trace_id: string;
};
const requestBody: CheckoutStartRequestBody = {
app_user_id: appUserId,
product_id: productId,
email: email,
price_id: purchaseOption.priceId,
presented_offering_identifier:
presentedOfferingContext.offeringIdentifier,
trace_id: traceId,
};
if (metadata) {
requestBody.metadata = metadata;
}
if (purchaseOption.id !== "base_option") {
requestBody.offer_id = purchaseOption.id;
}
if (presentedOfferingContext.targetingContext) {
requestBody.applied_targeting_rule = {
rule_id: presentedOfferingContext.targetingContext.ruleId,
revision: presentedOfferingContext.targetingContext.revision,
};
}
if (presentedOfferingContext.placementIdentifier) {
requestBody.presented_placement_identifier =
presentedOfferingContext.placementIdentifier;
}
return await performRequest<
CheckoutStartRequestBody,
CheckoutStartResponse
>(new CheckoutStartEndpoint(), {
apiKey: this.API_KEY,
body: requestBody,
httpConfig: this.httpConfig,
});
}
async postCheckoutCalculateTax(
operationSessionId: string,
countryCode?: string,
postalCode?: string,
): Promise<CheckoutCalculateTaxResponse> {
type CheckoutCalculateTaxRequestBody = {
country_code?: string;
postal_code?: string;
};
const requestBody: CheckoutCalculateTaxRequestBody = {
country_code: countryCode,
postal_code: postalCode,
};
return await performRequest<
CheckoutCalculateTaxRequestBody,
CheckoutCalculateTaxResponse
>(new CheckoutCalculateTaxEndpoint(operationSessionId), {
apiKey: this.API_KEY,
body: requestBody,
httpConfig: this.httpConfig,
});
}
async postCheckoutComplete(
operationSessionId: string,
email?: string,
): Promise<CheckoutCompleteResponse> {
type CheckoutCompleteRequestBody = {
email?: string;
};
const requestBody: CheckoutCompleteRequestBody = {
email: email,
};
return await performRequest<
CheckoutCompleteRequestBody,
CheckoutCompleteResponse
>(new CheckoutCompleteEndpoint(operationSessionId), {
apiKey: this.API_KEY,
body: requestBody,
httpConfig: this.httpConfig,
});
}
async getCheckoutStatus(
operationSessionId: string,
): Promise<CheckoutStatusResponse> {
return await performRequest<null, CheckoutStatusResponse>(
new GetCheckoutStatusEndpoint(operationSessionId),
{
apiKey: this.API_KEY,
httpConfig: this.httpConfig,
},
);
}
}
| yannbf/purchases-js-repro | 0 | TypeScript | yannbf | Yann Braga | chromaui | |
src/networking/endpoints.ts | TypeScript | type HttpMethodType = "GET" | "POST";
const SUBSCRIBERS_PATH = "/v1/subscribers";
const RC_BILLING_PATH = "/rcbilling/v1";
interface Endpoint {
method: HttpMethodType;
name: string;
urlPath(): string;
}
export class GetOfferingsEndpoint implements Endpoint {
private readonly appUserId: string;
constructor(appUserId: string) {
this.appUserId = appUserId;
}
method: HttpMethodType = "GET";
name: string = "getOfferings";
urlPath(): string {
const encodedAppUserId = encodeURIComponent(this.appUserId);
return `${SUBSCRIBERS_PATH}/${encodedAppUserId}/offerings`;
}
}
export class PurchaseEndpoint implements Endpoint {
method: HttpMethodType = "POST";
name: string = "purchase";
urlPath(): string {
return `${RC_BILLING_PATH}/purchase`;
}
}
export class GetProductsEndpoint implements Endpoint {
method: HttpMethodType = "GET";
name: string = "getProducts";
private readonly appUserId: string;
private readonly productIds: string[];
private readonly currency: string | undefined;
constructor(appUserId: string, productIds: string[], currency?: string) {
this.appUserId = appUserId;
this.productIds = productIds;
this.currency = currency;
}
urlPath(): string {
const encodedAppUserId = encodeURIComponent(this.appUserId);
const encodedProductIds = this.productIds
.map(encodeURIComponent)
.join("&id=");
const currencyParam = this.currency ? `¤cy=${this.currency}` : "";
return `${RC_BILLING_PATH}/subscribers/${encodedAppUserId}/products?id=${encodedProductIds}${currencyParam}`;
}
}
export class GetCustomerInfoEndpoint implements Endpoint {
method: HttpMethodType = "GET";
name: string = "getCustomerInfo";
private readonly appUserId: string;
constructor(appUserId: string) {
this.appUserId = appUserId;
}
urlPath(): string {
const encodedAppUserId = encodeURIComponent(this.appUserId);
return `${SUBSCRIBERS_PATH}/${encodedAppUserId}`;
}
}
export class GetBrandingInfoEndpoint implements Endpoint {
method: HttpMethodType = "GET";
name: string = "getBrandingInfo";
urlPath(): string {
return `${RC_BILLING_PATH}/branding`;
}
}
export class CheckoutStartEndpoint implements Endpoint {
method: HttpMethodType = "POST";
name: string = "postCheckoutStart";
urlPath(): string {
return `${RC_BILLING_PATH}/checkout/start`;
}
}
export class CheckoutCalculateTaxEndpoint implements Endpoint {
method: HttpMethodType = "POST";
name: string = "postCheckoutCalculateTax";
private readonly operationSessionId: string;
constructor(operationSessionId: string) {
this.operationSessionId = operationSessionId;
}
urlPath(): string {
return `${RC_BILLING_PATH}/checkout/${this.operationSessionId}/calculate_taxes`;
}
}
export class CheckoutCompleteEndpoint implements Endpoint {
method: HttpMethodType = "POST";
name: string = "postCheckoutComplete";
private readonly operationSessionId: string;
constructor(operationSessionId: string) {
this.operationSessionId = operationSessionId;
}
urlPath(): string {
return `${RC_BILLING_PATH}/checkout/${this.operationSessionId}/complete`;
}
}
export class GetCheckoutStatusEndpoint implements Endpoint {
method: HttpMethodType = "GET";
name: string = "getCheckoutStatus";
private readonly operationSessionId: string;
constructor(operationSessionId: string) {
this.operationSessionId = operationSessionId;
}
urlPath(): string {
return `${RC_BILLING_PATH}/checkout/${this.operationSessionId}`;
}
}
export type SupportedEndpoint =
| GetOfferingsEndpoint
| PurchaseEndpoint
| GetProductsEndpoint
| GetCustomerInfoEndpoint
| GetBrandingInfoEndpoint
| GetCheckoutStatusEndpoint;
| yannbf/purchases-js-repro | 0 | TypeScript | yannbf | Yann Braga | chromaui | |
src/networking/http-client.ts | TypeScript | import { type SupportedEndpoint } from "./endpoints";
import {
type BackendErrorCode,
ErrorCode,
ErrorCodeUtils,
PurchasesError,
} from "../entities/errors";
import { RC_ENDPOINT, VERSION } from "../helpers/constants";
import { StatusCodes } from "http-status-codes";
import { isSandboxApiKey } from "../helpers/api-key-helper";
import type { HttpConfig } from "../entities/http-config";
interface HttpRequestConfig<RequestBody> {
apiKey: string;
body?: RequestBody;
headers?: { [key: string]: string };
httpConfig?: HttpConfig;
}
export async function performRequest<RequestBody, ResponseType>(
endpoint: SupportedEndpoint,
config: HttpRequestConfig<RequestBody>,
): Promise<ResponseType> {
const { apiKey, body, headers, httpConfig } = config;
const baseUrl = httpConfig?.proxyURL ?? RC_ENDPOINT;
const url = `${baseUrl}${endpoint.urlPath()}`;
try {
const response = await fetch(url, {
method: endpoint.method,
headers: getHeaders(apiKey, headers, httpConfig?.additionalHeaders),
body: getBody(body),
});
await handleErrors(response, endpoint);
return (await response.json()) as ResponseType; // TODO: Validate response is correct.
} catch (error) {
if (error instanceof TypeError) {
throw new PurchasesError(
ErrorCode.NetworkError,
ErrorCodeUtils.getPublicMessage(ErrorCode.NetworkError),
error.message,
);
} else {
throw error;
}
}
}
async function handleErrors(response: Response, endpoint: SupportedEndpoint) {
const statusCode = response.status;
if (statusCode >= StatusCodes.INTERNAL_SERVER_ERROR) {
throwUnknownError(endpoint, statusCode, await response.text());
} else if (statusCode >= StatusCodes.BAD_REQUEST) {
const errorBody = await response.json();
const errorBodyString = errorBody ? JSON.stringify(errorBody) : null;
const backendErrorCodeNumber: number | null = errorBody?.code;
const backendErrorMessage: string | null = errorBody?.message;
if (backendErrorCodeNumber != null) {
const backendErrorCode: BackendErrorCode | null =
ErrorCodeUtils.convertCodeToBackendErrorCode(backendErrorCodeNumber);
if (backendErrorCode == null) {
throwUnknownError(
endpoint,
statusCode,
errorBodyString,
backendErrorCodeNumber,
);
} else {
throw PurchasesError.getForBackendError(
backendErrorCode,
backendErrorMessage,
);
}
} else {
throwUnknownError(endpoint, statusCode, errorBodyString);
}
}
}
function throwUnknownError(
endpoint: SupportedEndpoint,
statusCode: number,
errorBody: string | null,
backendErrorCode?: number,
) {
throw new PurchasesError(
ErrorCode.UnknownBackendError,
`Unknown backend error.`,
`Request: ${endpoint.name}. Status code: ${statusCode}. Body: ${errorBody}.`,
{ backendErrorCode: backendErrorCode },
);
}
function getBody<RequestBody>(body?: RequestBody): string | null {
if (body == null) {
return null;
} else {
return JSON.stringify(body);
}
}
const AUTHORIZATION_HEADER = "Authorization";
const CONTENT_TYPE_HEADER = "Content-Type";
const ACCEPT_HEADER = "Accept";
const PLATFORM_HEADER = "X-Platform";
const VERSION_HEADER = "X-Version";
const IS_SANDBOX_HEADER = "X-Is-Sandbox";
export const SDK_HEADERS = new Set([
AUTHORIZATION_HEADER,
CONTENT_TYPE_HEADER,
ACCEPT_HEADER,
PLATFORM_HEADER,
VERSION_HEADER,
IS_SANDBOX_HEADER,
]);
export function getHeaders(
apiKey: string,
headers?: { [key: string]: string },
additionalHeaders?: { [key: string]: string },
): { [key: string]: string } {
let all_headers = {
[AUTHORIZATION_HEADER]: `Bearer ${apiKey}`,
[CONTENT_TYPE_HEADER]: "application/json",
[ACCEPT_HEADER]: "application/json",
[PLATFORM_HEADER]: "web",
[VERSION_HEADER]: VERSION,
[IS_SANDBOX_HEADER]: `${isSandboxApiKey(apiKey)}`,
};
if (headers) {
all_headers = { ...all_headers, ...headers };
}
if (additionalHeaders) {
// The order here is intentional, so we don't allow overriding the SDK
// headers with additional headers.
all_headers = { ...additionalHeaders, ...all_headers };
}
return all_headers;
}
| yannbf/purchases-js-repro | 0 | TypeScript | yannbf | Yann Braga | chromaui | |
src/networking/responses/branding-response.ts | TypeScript | import type { BrandingAppearance } from "../../entities/branding";
export type BrandingInfoResponse = {
app_icon: string | null;
app_icon_webp: string | null;
appearance: BrandingAppearance | null;
id: string;
app_name: string | null;
support_email?: string | null;
gateway_tax_collection_enabled: boolean;
};
| yannbf/purchases-js-repro | 0 | TypeScript | yannbf | Yann Braga | chromaui | |
src/networking/responses/checkout-calculate-tax-response.ts | TypeScript | import type { StripeElementsConfiguration } from "./stripe-elements";
export interface TaxBreakdown {
taxable_amount_in_micros: number;
tax_amount_in_micros: number;
display_name: string;
tax_rate_in_micros: number | null;
country: string | null;
state: string | null;
tax_type: string | null;
}
export interface CheckoutCalculateTaxResponse {
operation_session_id: string;
currency: string;
total_amount_in_micros: number;
tax_amount_in_micros: number;
total_excluding_tax_in_micros: number;
tax_inclusive: boolean;
pricing_phases: {
base: {
tax_breakdown: TaxBreakdown[];
};
};
gateway_params: {
elements_configuration: StripeElementsConfiguration;
};
}
| yannbf/purchases-js-repro | 0 | TypeScript | yannbf | Yann Braga | chromaui | |
src/networking/responses/checkout-complete-response.ts | TypeScript | export interface CheckoutCompleteResponse {
operation_session_id: string;
gateway_params: {
client_secret?: string;
};
}
| yannbf/purchases-js-repro | 0 | TypeScript | yannbf | Yann Braga | chromaui |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.