@iftc/yete 0.0.1-alpha.4 → 0.0.1-alpha.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,6 @@
1
+ const { marked } = require('marked');
2
+ module.exports = function (md) {
3
+ if (md) {
4
+ return marked(md);
5
+ }
6
+ }
package/index.js CHANGED
@@ -12,6 +12,49 @@ class YeteError extends Error {
12
12
  this.name = 'YeteError';
13
13
  }
14
14
  }
15
+ /**
16
+ * 检查浏览器兼容性
17
+ * @throws {YeteError} 如果不兼容或无法判断则抛出错误
18
+ */
19
+ (function checkBrowserCompatibility() {
20
+ const ua = navigator.userAgent;
21
+ let browser = null;
22
+ let version = 0;
23
+ if (/Edg\/(\d+)/.test(ua)) {
24
+ browser = 'Edge';
25
+ version = parseInt(ua.match(/Edg\/(\d+)/)[1], 10);
26
+ } else if (/Chrome\/(\d+)/.test(ua) && !/Chromium/.test(ua)) {
27
+ browser = 'Chrome';
28
+ version = parseInt(ua.match(/Chrome\/(\d+)/)[1], 10);
29
+ } else if (/Firefox\/(\d+)/.test(ua)) {
30
+ browser = 'Firefox';
31
+ version = parseInt(ua.match(/Firefox\/(\d+)/)[1], 10);
32
+ } else if (/Version\/(\d+)/.test(ua) && /Safari/.test(ua)) {
33
+ browser = 'Safari';
34
+ version = parseInt(ua.match(/Version\/(\d+)/)[1], 10);
35
+ }
36
+ console.log(browser, version);
37
+ const minVersions = {
38
+ 'Chrome': 87,
39
+ 'Firefox': 140,
40
+ 'Safari': 18.4,
41
+ 'Edge': 87
42
+ };
43
+ let isCompatible = false;
44
+ if (browser && minVersions[browser] !== undefined) {
45
+ if (version >= minVersions[browser]) {
46
+ isCompatible = true;
47
+ }
48
+ }
49
+ if (!isCompatible) {
50
+ const msg = browser
51
+ ? `您的浏览器版本过低 (${browser} ${version}),请使用 Chrome 71+, Firefox 69+, Safari 12.1+ 或 Edge 79+。`
52
+ : `无法识别您的浏览器环境,请使用现代浏览器 (Chrome, Firefox, Safari, Edge)。`;
53
+
54
+ alert(msg);
55
+ console.error(new YeteError('Browser incompatible'));
56
+ }
57
+ })();
15
58
  /**
16
59
  * 页面基类
17
60
  * @example
@@ -69,6 +112,8 @@ let custom502Page = null;
69
112
 
70
113
  let searchParams = new URLSearchParams("");
71
114
 
115
+ const hostname = location.hostname;
116
+
72
117
  /**
73
118
  * 导出的对象
74
119
  */
@@ -592,6 +637,405 @@ const obj = {
592
637
  } else {
593
638
  return loadUI(str);
594
639
  }
640
+ },
641
+ /**
642
+ * 认证管理类
643
+ * @description 提供用户认证、令牌管理、授权验证等功能
644
+ */
645
+ Auth: class {
646
+ /**
647
+ * 构造函数
648
+ * @param {Object} options 配置选项
649
+ * @property {String} apiBaseUrl API 基础地址
650
+ * @property {String} tokenKey localStorage 中存储 token 的键名
651
+ */
652
+ constructor(options = {}) {
653
+ this.apiBaseUrl = options.apiBaseUrl || 'https://iftc.koyeb.app/api/auth';
654
+ this.tokenKey = options.tokenKey || 'auth_token';
655
+ this.checkInterval = options.checkInterval || 2000;
656
+ this.onAuthSuccess = options.onAuthSuccess || null;
657
+ this.onAuthFail = options.onAuthFail || null;
658
+ }
659
+
660
+ /**
661
+ * 获取存储的 auth_token
662
+ * @returns {String|null}
663
+ * @example
664
+ * const token = auth.getAuthToken();
665
+ */
666
+ getAuthToken() {
667
+ return localStorage.getItem(this.tokenKey);
668
+ }
669
+
670
+ /**
671
+ * 设置存储的 auth_token
672
+ * @param {String} token
673
+ * @example
674
+ * auth.setAuthToken('your_token_here');
675
+ */
676
+ setAuthToken(token) {
677
+ localStorage.setItem(this.tokenKey, token);
678
+ }
679
+
680
+ /**
681
+ * 清除存储的 auth_token
682
+ * @example
683
+ * auth.clearAuthToken();
684
+ */
685
+ clearAuthToken() {
686
+ localStorage.removeItem(this.tokenKey);
687
+ }
688
+
689
+ /**
690
+ * 检查是否已授权
691
+ * @returns {Promise<Boolean>}
692
+ * @example
693
+ * if (auth.isAuthorized()) { ... }
694
+ */
695
+ async isAuthorized() {
696
+ return !!await cookieStore.get("ID");
697
+ }
698
+
699
+ /**
700
+ * 获取授权链接
701
+ * @param {String} redirectUrl 回调地址
702
+ * @returns {String}
703
+ * @example
704
+ * const url = auth.getAuthUrl(location.href);
705
+ */
706
+ getAuthUrl(redirectUrl) {
707
+ return `${this.apiBaseUrl}/token?redirect=${encodeURIComponent(redirectUrl)}`;
708
+ }
709
+
710
+ /**
711
+ * 发起授权请求
712
+ * @description 跳转到授权页面
713
+ * @param {String} redirectUrl 回调地址
714
+ * @example
715
+ * auth.requestAuth(location.href);
716
+ */
717
+ async requestAuth(redirectUrl) {
718
+ const url = this.getAuthUrl(redirectUrl);
719
+ const response = await fetch(url);
720
+ const json = await response.json();
721
+
722
+ if (json.code !== 200) {
723
+ throw new YeteError(json.msg || '获取授权令牌失败');
724
+ }
725
+
726
+ this.setAuthToken(json.data.token);
727
+ location.href = json.data.url;
728
+ return json;
729
+ }
730
+
731
+ /**
732
+ * 验证 auth_token 有效性
733
+ * @param {String} token 可选,不传则使用存储的 auth_token
734
+ * @returns {Promise<Boolean>}
735
+ * @example
736
+ * const isValid = await auth.verify();
737
+ */
738
+ async verify(token = null) {
739
+ const targetToken = token || this.getAuthToken();
740
+
741
+ if (!targetToken) {
742
+ throw new YeteError('未找到授权令牌');
743
+ }
744
+
745
+ const response = await fetch(`${this.apiBaseUrl}/verify?token=${targetToken}`);
746
+ const json = await response.json();
747
+
748
+ if (json.code === 200) {
749
+ await this.setCookie('ID', json.data.id, 365);
750
+ localStorage.setItem("ID", json.data.id);
751
+ return true;
752
+ }
753
+
754
+ return false;
755
+ }
756
+ /**
757
+ * 设置 cookie
758
+ * @param {String} name 键名
759
+ * @param {String} value 键值
760
+ * @param {Number} days 过期天数
761
+ */
762
+ async setCookie(name, value, days = 1) {
763
+ const expires = new Date();
764
+ expires.setTime(expires.getTime() + days * 24 * 60 * 60 * 1000);
765
+
766
+ try {
767
+ console.log(location.hostname);
768
+ await cookieStore.set({
769
+ name,
770
+ value,
771
+ expires: expires.toISOString(),
772
+ path: '/',
773
+ domain: hostname,
774
+ secure: true
775
+ });
776
+ } catch (error) {
777
+ console.warn('cookieStore not supported, falling back to document.cookie');
778
+ document.cookie = `${name}=${value}; expires=${expires.toUTCString()}; path=/`;
779
+ }
780
+ }
781
+
782
+ /**
783
+ * 获取 cookie
784
+ * @param {String} name 键名
785
+ * @returns {String|null}
786
+ */
787
+ async getCookie(name) {
788
+ try {
789
+ const cookies = await cookieStore.get(name);
790
+ return cookies ? cookies.value : null;
791
+ } catch (error) {
792
+ // 如果 cookieStore 不支持,降级到 document.cookie
793
+ console.warn('cookieStore not supported, falling back to document.cookie');
794
+ return this.getCookieFromDocument(name);
795
+ }
796
+ }
797
+
798
+ /**
799
+ * 从 document.cookie 获取 cookie(备用方案)
800
+ * @param {String} name 键名
801
+ * @returns {String|null}
802
+ */
803
+ getCookieFromDocument(name) {
804
+ const nameEQ = name + "=";
805
+ const ca = document.cookie.split(';');
806
+ for (let i = 0; i < ca.length; i++) {
807
+ let c = ca[i];
808
+ while (c.charAt(0) === ' ') c = c.substring(1, c.length);
809
+ if (c.indexOf(nameEQ) === 0) {
810
+ return c.substring(nameEQ.length, c.length);
811
+ }
812
+ }
813
+ return null;
814
+ }
815
+
816
+ /**
817
+ * 获取用户 ID
818
+ * @returns {String|null}
819
+ */
820
+ getUserId() {
821
+ return localStorage.getItem("ID");
822
+ }
823
+
824
+ /**
825
+ * 检查授权状态并等待授权完成
826
+ * @param {Function} callback 授权成功后的回调
827
+ * @param {Number} timeout 超时时间(毫秒)
828
+ * @returns {Promise<Object>}
829
+ * @example
830
+ * await auth.waitForAuth((userInfo) => {
831
+ * console.log('用户 ID:', userInfo.id);
832
+ * });
833
+ */
834
+ async waitForAuth(callback, timeout = 60000) {
835
+ const url = new URL(location.href);
836
+ const authParam = url.searchParams.get('auth');
837
+
838
+ if (!authParam) {
839
+ throw new YeteError('缺少 auth 参数');
840
+ }
841
+
842
+ return new Promise((resolve, reject) => {
843
+ const startTime = Date.now();
844
+ const intervalId = setInterval(async () => {
845
+ // 检查超时
846
+ if (Date.now() - startTime > timeout) {
847
+ clearInterval(intervalId);
848
+ reject(new YeteError('授权超时'));
849
+ return;
850
+ }
851
+
852
+ try {
853
+ const json = await this.verify();
854
+ if (json.code === 200) {
855
+ clearInterval(intervalId);
856
+ if (callback) callback(json.data);
857
+ if (this.onAuthSuccess) this.onAuthSuccess(json.data);
858
+ resolve(json);
859
+ }
860
+ } catch (error) {
861
+ console.error('验证失败:', error);
862
+ }
863
+ }, this.checkInterval);
864
+ });
865
+ }
866
+
867
+ /**
868
+ * 处理授权回调
869
+ * @description 在授权回调页面调用此方法
870
+ * @param {Function} successCallback 授权成功回调
871
+ * @param {Function} failCallback 授权失败回调
872
+ * @example
873
+ * auth.handleAuthCallback((userInfo) => {
874
+ * document.write('授权成功,用户 ID: ' + userInfo.id);
875
+ * });
876
+ */
877
+ async handleAuthCallback(successCallback, failCallback) {
878
+ const url = new URL(location.href);
879
+ const authParam = url.searchParams.get('auth');
880
+
881
+ if (!authParam) {
882
+ return;
883
+ }
884
+
885
+ try {
886
+ const result = await this.waitForAuth(successCallback);
887
+ if (successCallback) {
888
+ successCallback(result.data);
889
+ }
890
+ } catch (error) {
891
+ console.error('授权失败:', error);
892
+ if (failCallback) {
893
+ failCallback(error);
894
+ }
895
+ if (this.onAuthFail) {
896
+ this.onAuthFail(error);
897
+ }
898
+ }
899
+ }
900
+
901
+ /**
902
+ * 获取用户信息
903
+ * @returns {Promise<Object>}
904
+ * @example
905
+ * const userInfo = await auth.getUserInfo();
906
+ */
907
+ async getUserInfo() {
908
+ const res = await fetch(`${this.apiBaseUrl}/api/user/details?ID=${this.getUserId()}`);
909
+ }
910
+
911
+ /**
912
+ * 登出
913
+ * @example
914
+ * auth.logout();
915
+ */
916
+ logout() {
917
+ this.clearAuthToken();
918
+ location.reload();
919
+ }
920
+ },
921
+ };
922
+
923
+ /**
924
+ * 生成哈希值
925
+ * @description 与Java的用法一致
926
+ * @returns {Number}
927
+ * @example
928
+ * const hash = 'hello world'.hashCode();
929
+ */
930
+ String.prototype.hashCode = function () {
931
+ let hash = 0;
932
+ for (let i = 0; i < this.length; i++) {
933
+ const char = this.charCodeAt(i);
934
+ hash = (hash << 5) - hash + char;
935
+ hash |= 0;
936
+ }
937
+ return hash;
938
+ };
939
+
940
+ /**
941
+ * 响应事件监听
942
+ */
943
+ Response.prototype.events = {};
944
+ /**
945
+ * 是否正在监听响应事件
946
+ */
947
+ Response.prototype.listening = false;
948
+ /**
949
+ * 添加响应事件监听
950
+ * @param {string} eventName 事件名
951
+ * @param {function} callback 回调函数
952
+ * @example
953
+ * response.on('eventName', function() {})
954
+ */
955
+ Response.prototype.on = function (eventName, callback) {
956
+ if (!this.events[eventName]) {
957
+ this.events[eventName] = [];
958
+ }
959
+ this.events[eventName].push(callback);
960
+ };
961
+ /**
962
+ * 触发事件
963
+ * @param {string} eventName 事件名
964
+ * @param {...any} args 参数
965
+ * @example
966
+ * response.emit('eventName', '参数1', '参数2', ...);
967
+ */
968
+ Response.prototype.emit = function (eventName, ...args) {
969
+ if (this.events[eventName]) {
970
+ this.events[eventName].forEach(callback => callback(...args));
971
+ }
972
+ };
973
+ /**
974
+ * 移除事件监听
975
+ * @param {string} eventName 事件名
976
+ * @param {Function} callback 回调函数
977
+ * @example
978
+ * response.off('eventName', callback);
979
+ */
980
+ Response.prototype.off = function (eventName, callback) {
981
+ if (this.events[eventName]) {
982
+ this.events[eventName] = this.events[eventName].filter(cb => cb !== callback);
983
+ }
984
+ };
985
+ /**
986
+ * 开始同步监听(开启后将无法使用异步)
987
+ * @returns {Promise<void>}
988
+ * @example
989
+ * response.listen();
990
+ */
991
+ Response.prototype.listen = async function () {
992
+ if (this.listening) {
993
+ throw new YeteError('已开启同步监听,请勿重复开启');
994
+ }
995
+ const res = this;
996
+ const headers = res.headers;
997
+ this.listening = true;
998
+ const contentType = headers.get('Content-Type');
999
+ if (contentType && contentType.includes('application/json')) {
1000
+ const json = await res.json();
1001
+ res.emit('res', {
1002
+ type: 'json',
1003
+ data: json,
1004
+ });
1005
+ } else if (contentType && contentType.includes('text/html')) {
1006
+ const text = await res.text();
1007
+ const doc = new DOMParser().parseFromString(text, "text/html");
1008
+ res.emit('res', {
1009
+ type: 'html',
1010
+ data: doc,
1011
+ });
1012
+ } else if (contentType && contentType.includes('text/plain')) {
1013
+ const text = await res.text();
1014
+ res.emit('res', {
1015
+ type: 'text',
1016
+ data: text,
1017
+ })
1018
+ } else if (contentType && contentType.includes('text/xml')) {
1019
+ const text = await res.text();
1020
+ const xmlDoc = new DOMParser().parseFromString(text, "text/xml");
1021
+ res.emit('res', {
1022
+ type: 'xml',
1023
+ data: xmlDoc,
1024
+ });
1025
+ } else if (contentType && contentType.includes('text/event-stream')) {
1026
+ obj.HTTP.readStream(res, ({ chunk, done }) => {
1027
+ res.emit('res', {
1028
+ type: 'stream',
1029
+ data: chunk,
1030
+ done: done,
1031
+ });
1032
+ });
1033
+ } else {
1034
+ const blob = await res.blob();
1035
+ res.emit('res', {
1036
+ type: 'blob',
1037
+ data: blob,
1038
+ });
595
1039
  }
596
1040
  };
597
1041
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@iftc/yete",
3
- "version": "0.0.1-alpha.4",
3
+ "version": "0.0.1-alpha.5",
4
4
  "description": "",
5
5
  "keywords": [
6
6
  "IFTC",
@@ -16,6 +16,7 @@
16
16
  },
17
17
  "dependencies": {
18
18
  "dexie": "^4.3.0",
19
- "esbuild": "^0.27.3"
19
+ "esbuild": "^0.27.3",
20
+ "marked": "^17.0.5"
20
21
  }
21
22
  }