uni-log-sdk 0.1.1 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,54 +1,71 @@
1
1
  {
2
- "name": "uni-log-sdk",
3
- "version": "0.1.1",
4
- "private": false,
5
- "description": "uni-app / uni-app x 日志上报 SDK:console、JS 错误、自定义事件与设备信息批量上报",
6
- "keywords": [
7
- "uni-app",
8
- "uni-app x",
9
- "uni_modules",
10
- "日志",
11
- "埋点",
12
- "sdk"
13
- ],
14
- "license": "UNLICENSED",
15
- "main": "dist/index.js",
16
- "module": "dist/index.mjs",
17
- "types": "dist/index.d.ts",
18
- "exports": {
19
- ".": {
20
- "types": "./dist/index.d.ts",
21
- "import": "./dist/index.mjs",
22
- "require": "./dist/index.js"
23
- }
2
+ "name": "uni-log-sdk",
3
+ "version": "0.2.1",
4
+ "private": false,
5
+ "description": "uni-app / uni-app x 日志上报 SDK:console、JS 错误、自定义事件与设备信息批量上报",
6
+ "keywords": [
7
+ "uni-app",
8
+ "uni-app x",
9
+ "uni_modules",
10
+ "日志",
11
+ "埋点",
12
+ "sdk"
13
+ ],
14
+ "license": "UNLICENSED",
15
+ "main": "dist/index.js",
16
+ "module": "dist/index.mjs",
17
+ "types": "dist/index.d.ts",
18
+ "exports": {
19
+ ".": {
20
+ "types": "./dist/index.d.ts",
21
+ "import": "./dist/index.mjs",
22
+ "require": "./dist/index.js"
24
23
  },
25
- "bin": {
26
- "uni-log": "bin/uni-log.mjs"
27
- },
28
- "files": [
29
- "dist",
30
- "uni_modules",
31
- "bin",
32
- "scripts",
33
- "README.md"
34
- ],
35
- "engines": {
36
- "node": ">=18"
37
- },
38
- "scripts": {
39
- "build": "tsup && node scripts/build-uni-module.mjs",
40
- "test": "vitest run",
41
- "test:watch": "vitest",
42
- "postinstall": "node scripts/postinstall.mjs",
43
- "prepublishOnly": "npm run build && npm test"
44
- },
45
- "publishConfig": {
46
- "registry": "https://registry.npmjs.org/"
24
+ "./react-native": {
25
+ "types": "./dist/adapters/react-native.d.ts",
26
+ "import": "./dist/adapters/react-native.mjs",
27
+ "require": "./dist/adapters/react-native.js"
28
+ }
29
+ },
30
+ "bin": {
31
+ "uni-log": "bin/uni-log.mjs"
32
+ },
33
+ "files": [
34
+ "dist",
35
+ "uni_modules",
36
+ "bin",
37
+ "scripts/postinstall.mjs",
38
+ "README.md",
39
+ "CHANGELOG.md"
40
+ ],
41
+ "engines": {
42
+ "node": ">=18"
43
+ },
44
+ "publishConfig": {
45
+ "registry": "https://registry.npmjs.org/"
46
+ },
47
+ "devDependencies": {
48
+ "tsup": "^8.0.0",
49
+ "typescript": "^5.6.0",
50
+ "vitest": "^3.0.0",
51
+ "@uni-log/shared": "0.1.0"
52
+ },
53
+ "peerDependencies": {
54
+ "@react-native-async-storage/async-storage": ">=1.20.0",
55
+ "react-native": ">=0.60.0"
56
+ },
57
+ "peerDependenciesMeta": {
58
+ "@react-native-async-storage/async-storage": {
59
+ "optional": true
47
60
  },
48
- "devDependencies": {
49
- "@uni-log/shared": "workspace:*",
50
- "tsup": "^8.0.0",
51
- "typescript": "^5.6.0",
52
- "vitest": "^3.0.0"
61
+ "react-native": {
62
+ "optional": true
53
63
  }
54
- }
64
+ },
65
+ "scripts": {
66
+ "build": "tsup && node scripts/build-uni-module.mjs",
67
+ "test": "vitest run",
68
+ "test:watch": "vitest",
69
+ "postinstall": "node scripts/postinstall.mjs"
70
+ }
71
+ }
@@ -3,7 +3,7 @@
3
3
  * 探测宿主工程里是否只有一个 uni-app 工程,是则把 uni_modules/uni-log 物化过去。
4
4
  *
5
5
  * 设计约束:
6
- * - 只在本包作为依赖安装时执行(包位于 node_modules 下);本仓库源码开发不触发
6
+ * - 只在本包作为依赖安装时执行(包位于 node_modules 下);直接引用源码时不触发
7
7
  * - 找不到工程 / 找到多个工程时不写文件,只提示,避免写错目录
8
8
  * - 目标版本不低于当前包版本时跳过,避免降级覆盖
9
9
  * - UNI_LOG_AUTO_SYNC=0 可关闭
@@ -19,7 +19,7 @@ function info(msg) {
19
19
  console.log(`[uni-log] ${msg}`)
20
20
  }
21
21
 
22
- /** 本仓库源码目录(packages/sdk)不自动同步,避免 pnpm install 时改动 demo 工程 */
22
+ /** 直接以源码方式引用时不自动同步,避免安装依赖时改动业务工程 */
23
23
  if (!pkgRoot.split(sep).includes('node_modules')) process.exit(0)
24
24
 
25
25
  if (process.env.UNI_LOG_AUTO_SYNC === '0') {
@@ -1 +1 @@
1
- var W=Object.create;var D=Object.defineProperty;var G=Object.getOwnPropertyDescriptor;var q=Object.getOwnPropertyNames;var K=Object.getPrototypeOf,$=Object.prototype.hasOwnProperty;var V=(n,t)=>()=>(t||n((t={exports:{}}).exports,t),t.exports);var J=(n,t,e,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of q(t))!$.call(n,i)&&i!==e&&D(n,i,{get:()=>t[i],enumerable:!(r=G(t,i))||r.enumerable});return n};var Y=(n,t,e)=>(e=n!=null?W(K(n)):{},J(t||!n||!n.__esModule?D(e,"default",{value:n,enumerable:!0}):e,n));var A=V(u=>{"use strict";Object.defineProperty(u,"__esModule",{value:!0});u.PROTOCOL_LIMITS=u.INGEST_PATH=u.LOG_LEVELS=void 0;u.LOG_LEVELS=["debug","info","warn","error","crash"];u.INGEST_PATH="/ingest/v1/logs";u.PROTOCOL_LIMITS={maxBatch:50,maxMsgLength:4e3,maxStackLength:8e3,maxEventsPerBatch:50,maxEventKeyLength:64,maxEventValLength:255,maxBodyBytes:512*1024}});var T=V(h=>{"use strict";var F=h&&h.__createBinding||(Object.create?(function(n,t,e,r){r===void 0&&(r=e);var i=Object.getOwnPropertyDescriptor(t,e);(!i||("get"in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[e]}}),Object.defineProperty(n,r,i)}):(function(n,t,e,r){r===void 0&&(r=e),n[r]=t[e]})),X=h&&h.__exportStar||function(n,t){for(var e in n)e!=="default"&&!Object.prototype.hasOwnProperty.call(t,e)&&F(t,n,e)};Object.defineProperty(h,"__esModule",{value:!0});X(A(),h)});var g=Y(T());function p(){let n=globalThis.uni;return n!=null?n:null}function z(){var n,t,e;try{let r=globalThis;return typeof r.getCurrentPages=="function"?r.getCurrentPages():typeof getCurrentPages=="function"?getCurrentPages():(e=(t=(n=r.uni)==null?void 0:n.getCurrentPages)==null?void 0:t.call(n))!=null?e:null}catch{return null}}function Q(n){return typeof n=="number"&&Number.isFinite(n)?n:void 0}function P(n){return typeof n=="string"&&n.length>0?n:void 0}function Z(n){let t=l=>{var c;try{return(c=l==null?void 0:l())!=null?c:{}}catch{return{}}},e=t(n==null?void 0:n.getSystemInfoSync),r=t(n==null?void 0:n.getDeviceInfo),i=t(n==null?void 0:n.getAppBaseInfo),a=t(n==null?void 0:n.getWindowInfo);if(Object.keys(e).length===0&&Object.keys(r).length===0)return null;let s=(...l)=>l.map(P).find(Boolean),d=(...l)=>l.map(Q).find(c=>c!==void 0),y=s(r.deviceId,e.deviceId,e.deviceUUID),v=s(e.uniPlatform,e.platform,r.platform,r.uniPlatform);return!y||!v?null:{deviceId:y,platform:v,deviceName:s(r.deviceName,e.deviceName),model:s(r.deviceModel,e.deviceModel,e.model),vendor:s(r.deviceBrand,e.deviceBrand,e.brand),os:s(e.osVersion,e.system,r.osVersion,r.system),osVersion:s(e.osVersion,r.osVersion),osName:s(e.osName,r.osName,i.osName),net:s(e.networkType,e.netType),language:s(i.language,e.language),pixelRatio:d(a.pixelRatio,e.pixelRatio),windowWidth:d(a.windowWidth,e.windowWidth),windowHeight:d(a.windowHeight,e.windowHeight),screenWidth:d(a.screenWidth,e.screenWidth),screenHeight:d(a.screenHeight,e.screenHeight)}}function j(){return{request(n){var e;let t=p();if(!(t!=null&&t.request)){(e=n.fail)==null||e.call(n,{errMsg:"uni-log: uni.request \u4E0D\u53EF\u7528"});return}t.request({...n,method:"POST"})},getStorage(n){var t,e;try{let r=(e=(t=p())==null?void 0:t.getStorageSync)==null?void 0:e.call(t,n);return typeof r=="string"&&r.length>0?r:null}catch{return null}},setStorage(n,t){var e,r;try{(r=(e=p())==null?void 0:e.setStorageSync)==null||r.call(e,n,t)}catch{}},getDeviceInfo(){try{return Z(p())}catch{return null}},getCurrentPage(){var n;try{let t=z(),e=t==null?void 0:t[t.length-1];return(n=e==null?void 0:e.route)!=null?n:null}catch{return null}},getPlatformVersion(){let n=p(),t=r=>{var i,a;try{let s=r();return s&&(a=(i=P(s.hostVersion))!=null?i:P(s.version))!=null?a:null}catch{return null}},e=n!=null&&n.getAppBaseInfo?t(()=>n.getAppBaseInfo()):null;return e||(n!=null&&n.getSystemInfoSync?t(()=>n.getSystemInfoSync()):null)},onError(n){var t,e;try{(e=(t=p())==null?void 0:t.onError)==null||e.call(t,n)}catch{}},onUnhandledRejection(n){var t,e;try{(e=(t=p())==null?void 0:t.onUnhandledRejection)==null||e.call(t,n)}catch{}}}}var m="uni-log:pending",B=20,ee="0.1.1";function f(n,t){return n.length>t?n.slice(0,t):n}function S(n){let t=n==null?void 0:n.trim();return t?f(t,128):void 0}function te(n,t,e){var i;let r={t:Date.now(),lv:n,msg:f(t||"(empty)",g.PROTOCOL_LIMITS.maxMsgLength)};return e!=null&&e.stack&&(r.stack=f(e.stack,g.PROTOCOL_LIMITS.maxStackLength)),e!=null&&e.page&&(r.page=f(e.page,255)),e!=null&&e.extra&&(r.extra=e.extra),(i=e==null?void 0:e.tags)!=null&&i.length&&(r.tags=e.tags),r}var w=class{constructor(t,e=j()){this.ready=!1;this.logs=[];this.events=[];this.timer=null;this.flushingPromise=null;this.launchTime=Date.now();this.pageCount=0;this.lastPage=null;this.deviceInfo=null;this.deviceNameOverride=null;this.options=t,this.adapter=e,this.sessionId=`sess-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`}start(){var e;if(this.ready)return;this.ready=!0;let t=Math.max(1e3,(e=this.options.flushInterval)!=null?e:1e4);this.timer=setInterval(()=>{this.flush().catch(()=>{})},t),this.retryPending().catch(()=>{}),this.options.collectErrors!==!1&&this.installErrorHooks(),this.samplePage()}stop(){this.ready=!1,this.timer&&(clearInterval(this.timer),this.timer=null)}log(t,e,r){if(!this.ready)return;let i=g.LOG_LEVELS.includes(t)?t:"info";this.samplePage();let a=this.adapter.getCurrentPage();this.logs.push(te(i,e,{...r,...a?{page:a}:{}})),this.logs.length>=g.PROTOCOL_LIMITS.maxBatch&&this.flush()}report(t,e){if(!this.ready||!t||t.length>g.PROTOCOL_LIMITS.maxEventKeyLength)return;this.samplePage();let r={t:Date.now(),ev:t};e&&(r.val=f(e,g.PROTOCOL_LIMITS.maxEventValLength));let i=this.adapter.getCurrentPage();i&&(r.page=i),this.events.push(r),this.events.length>=g.PROTOCOL_LIMITS.maxEventsPerBatch&&this.flush()}pageView(t){if(!this.ready)return;let e=t!=null?t:this.adapter.getCurrentPage();this.pageCount+=1,e&&(this.lastPage=e)}setDeviceName(t){let e=t.trim();this.deviceNameOverride=e?f(e,128):null}samplePage(){let t=this.adapter.getCurrentPage();t&&t!==this.lastPage&&(this.lastPage=t,this.pageCount+=1)}async flush(){if(!this.ready)return;if(this.flushingPromise)return this.flushingPromise;let t=async()=>{var r;let e;try{for(this.samplePage(),e=this.buildPayload(!0);;){if(!await this.send(e)){(e.logs.length||(r=e.events)!=null&&r.length)&&(this.persistPending([e]),this.options.debug&&console.warn("[uni-log] \u4E0A\u62A5\u5931\u8D25\uFF0C\u5DF2\u6682\u5B58\u5F85\u7EED\u4F20"));break}if(this.logs.length===0&&this.events.length===0)break;e=this.buildPayload(!1)}}catch(i){if(e)try{this.persistPending([e])}catch{}this.options.debug&&console.warn("[uni-log] flush \u5F02\u5E38",i)}finally{this.flushingPromise=null}};return this.flushingPromise=t(),this.flushingPromise}buildPayload(t){var s,d,y,v,l,c,b,k,I,L,E,R,_,N,O,U,x,C;let e=(s=this.deviceInfo)!=null?s:this.deviceInfo=this.adapter.getDeviceInfo(),r=(c=(l=(v=this.deviceNameOverride)!=null?v:S((y=(d=this.options).getDeviceName)==null?void 0:y.call(d)))!=null?l:S(this.options.deviceName))!=null?c:S(e==null?void 0:e.deviceName),i={deviceId:(b=e==null?void 0:e.deviceId)!=null?b:this.fallbackDeviceId(),platform:(k=e==null?void 0:e.platform)!=null?k:"unknown",...r?{deviceName:r}:{},...e!=null&&e.model?{model:e.model}:{},...e!=null&&e.vendor?{vendor:e.vendor}:{},...e!=null&&e.os?{os:e.os}:{},...e!=null&&e.osVersion?{osVersion:e.osVersion}:{},...e!=null&&e.osName?{osName:e.osName}:{},...((E=e==null?void 0:e.net)!=null?E:(L=(I=this.options).getNet)!=null&&L.call(I))?{net:(N=e==null?void 0:e.net)!=null?N:(_=(R=this.options).getNet)==null?void 0:_.call(R)}:{},...e!=null&&e.language?{language:e.language}:{},...e!=null&&e.pixelRatio?{pixelRatio:e.pixelRatio}:{},...e!=null&&e.windowWidth?{windowWidth:e.windowWidth}:{},...e!=null&&e.windowHeight?{windowHeight:e.windowHeight}:{},...e!=null&&e.screenWidth?{screenWidth:e.screenWidth}:{},...e!=null&&e.screenHeight?{screenHeight:e.screenHeight}:{}};return{header:{appKey:this.options.appKey,...this.options.appVer?{appVer:this.options.appVer}:{},...this.options.release?{release:this.options.release}:{},...this.options.channel?{channel:this.options.channel}:{},sessionId:this.sessionId,...(U=(O=this.options).getUserId)!=null&&U.call(O)?{userId:this.options.getUserId()}:{},...(C=(x=this.options).getNet)!=null&&C.call(x)?{net:this.options.getNet()}:{},sdkVer:ee,...this.adapter.getPlatformVersion()?{platformVersion:this.adapter.getPlatformVersion()}:{}},device:i,...t?{session:{launchTime:this.launchTime,duration:Math.max(0,Math.round((Date.now()-this.launchTime)/1e3)),pageCount:this.pageCount}}:{},logs:this.logs.splice(0,g.PROTOCOL_LIMITS.maxBatch),...this.events.length?{events:this.events.splice(0,g.PROTOCOL_LIMITS.maxEventsPerBatch)}:{}}}fallbackDeviceId(){let t=this.adapter.getStorage("uni-log:did");return t||(t=`did-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`,this.adapter.setStorage("uni-log:did",t)),t}send(t){return new Promise(e=>{let r=!1,i=s=>{r||(r=!0,clearTimeout(a),e(s))},a=setTimeout(()=>i(!1),8e3);try{this.adapter.request({url:`${this.options.serverUrl}${g.INGEST_PATH}`,data:t,header:{"Content-Type":"application/json"},success:s=>i(!!s&&s.statusCode>=200&&s.statusCode<300),fail:()=>i(!1)})}catch{i(!1)}})}safeStringify(t){let e=new WeakSet;return JSON.stringify(t,(r,i)=>{if(typeof i=="bigint")return i.toString();if(typeof i=="object"&&i!==null){if(e.has(i))return;e.add(i)}return i})}persistPending(t){let e=this.adapter.getStorage(m),r=[];try{r=e?JSON.parse(e):[],Array.isArray(r)||(r=[])}catch{r=[]}r.push(...t),r.length>B&&(r=r.slice(-B));try{this.adapter.setStorage(m,this.safeStringify(r))}catch(i){this.options.debug&&console.warn("[uni-log] \u6682\u5B58\u5931\u8D25",i)}}async retryPending(){let t=this.adapter.getStorage(m);if(!t)return;this.adapter.setStorage(m,"");let e;try{e=JSON.parse(t)}catch{return}if(!(!Array.isArray(e)||e.length===0)){for(let r=0;r<e.length;r++)if(!await this.send(e[r])){this.persistPending(e.slice(r)),this.options.debug&&console.warn("[uni-log] \u7EED\u4F20\u5931\u8D25\uFF0C\u6682\u5B58\u5DF2\u8FD8\u539F");return}}}installErrorHooks(){this.adapter.onError(t=>{this.log("error",String(t),{stack:String(t)})}),this.adapter.onUnhandledRejection(t=>{var i;let e=t,r=(i=e==null?void 0:e.reason)!=null?i:t;this.log("error",String(r),{stack:r==null?void 0:r.stack})})}};var o=null;function ce(n){return o==null||o.stop(),o=new w(n),o.start(),n.hookConsole!==!1&&re(),o}function he(){return o}function pe(n,t,e){o==null||o.log(n,t,e)}var ne={debug:(n,t)=>o==null?void 0:o.log("debug",n,t),info:(n,t)=>o==null?void 0:o.log("info",n,t),warn:(n,t)=>o==null?void 0:o.log("warn",n,t),error:(n,t)=>o==null?void 0:o.log("error",n,t)},M=new Set,H=!0;function fe(n){H=n}function re(){let n={debug:"debug",log:"info",info:"info",warn:"warn",error:"error"},t=console;for(let[e,r]of Object.entries(n)){if(M.has(e))continue;let i=t[e];if(typeof i!="function")continue;let a=i.bind(console);t[e]=(...s)=>{H&&ne[r](s.map(ie).join(" ")),a(...s)},M.add(e)}}function ie(n){if(typeof n=="string")return n;if(n instanceof Error)return n.stack||n.message;try{let t=JSON.stringify(n);return t===void 0?String(n):t}catch{return String(n)}}function ye(n,t){o==null||o.report(n,t)}function ve(n){o==null||o.setDeviceName(n)}async function me(){await(o==null?void 0:o.flush())}export{me as flush,he as getClient,re as hookConsole,ce as init,ye as report,fe as setConsoleReport,ve as setDeviceName,pe as ulog,ne as ulogger};
1
+ import{b as a,c as b,d as c,e as d,f as e,g as f,h as g,i as h,j as i,k as j,l as k}from"./chunk-SOQF2GQO.mjs";export{a as createBrowserAdapter,b as detectAdapter,k as flush,d as getClient,h as hookConsole,c as init,i as report,g as setConsoleReport,j as setDeviceName,e as ulog,f as ulogger};
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "id": "uni-log",
3
3
  "displayName": "uni-log 日志上报",
4
- "version": "0.1.1",
4
+ "version": "0.2.1",
5
5
  "description": "uni-app / uni-app x 日志上报 SDK:console、JS 错误、自定义事件与设备信息批量上报",
6
6
  "keywords": [
7
7
  "uni-app",
@@ -1,11 +1,37 @@
1
1
  # uni-log-sdk
2
2
 
3
- uni-app / uni-app x 日志上报 SDK:console、JS 错误、自定义事件、设备与会话心跳,批量上报到自建 uni-log 服务端。
3
+ 多端日志上报 SDK(uni-app / uni-app x / React Native / 任意 TS Web):console、JS 错误、自定义事件、设备与会话心跳,批量上报到自建 uni-log 服务端。
4
4
 
5
- - 纯 JS、无外部运行时依赖(shared 协议已内联),可在 uni-app x 蒸汽模式、普通 uni-app、H5、小程序中运行
5
+ - 纯 JS、无外部运行时依赖(协议代码已内置),可在 uni-app x 蒸汽模式、普通 uni-app、H5、小程序、React Native(CLI / Expo)、任意 TS Web 应用中运行
6
6
  - 默认 10s 批量上报,满 50 条立即发送;发送失败写入本地暂存,冷启动自动续传
7
7
  - 提供 uni_modules 形态,HBuilderX 工程可直接引用
8
8
 
9
+ ## 支持平台
10
+
11
+ | 运行环境 | 接入方式 | 说明 |
12
+ | --- | --- | --- |
13
+ | uniapp / uniapp x(App·H5·小程序) | 主入口 `init()` 自动探测 uni 适配器 | console 劫持、页面栈、错误钩子全自动 |
14
+ | **React Native(CLI / Expo)** | 子路径 `uni-log-sdk/react-native` 的 `initRN()` | 存储经 AsyncStorage(Expo Go 内置);页面路由需一行接线 |
15
+ | **任意 TS Web 应用**(React / Vue / 纯浏览器) | 主入口 `init()` 自动探测浏览器适配器 | fetch + localStorage + window 错误事件,零配置 |
16
+ | 非 TS 技术栈(Flutter / 原生) | 按协议自行实现(HTTP + JSON + HMAC-SHA256) | 服务端零改动,详见协议定义 `@uni-log/shared` |
17
+
18
+ ### 适配器架构(贡献者向)
19
+
20
+ 平台差异全部收敛在 `src/adapters/`,`client.ts` 只面向 `types.ts` 里的 `PlatformAdapter` 接口:
21
+
22
+ ```
23
+ src/adapters/
24
+ ├── types.ts # PlatformAdapter / RequestOptions / RequestTask 纯接口
25
+ ├── uni.ts # uni 适配器(uni-app / uni-app x):uni.request / 同步 storage / 页面栈三级兜底
26
+ ├── web.ts # 浏览器适配器:localStorage / window 错误事件(SSR 防御)
27
+ ├── react-native.ts # RN 适配器:AsyncStorage 异步写穿+预读(ready 信号)/ ErrorUtils 链式
28
+ ├── fetch.ts # web / react-native 共用的 fetch 请求实现(POST + AbortController)
29
+ ├── detect.ts # detectAdapter:有 uni 全局走 uni,否则浏览器
30
+ └── index.ts # 桶出口(不得引出 RN 适配器——主入口依赖图禁止沾染 react-native)
31
+ ```
32
+
33
+ 新增平台支持 = 在 `adapters/` 加一个适配器文件 +(如需子路径)在 `tsup.config.ts` 加入口;队列、签名、重试、暂存续传等核心逻辑无需改动。
34
+
9
35
  ## 安装
10
36
 
11
37
  ### 方式一:uni_modules(推荐,HBuilderX / CLI 通用)
@@ -64,18 +90,23 @@ import { init } from '@/uni_modules/uni-log'
64
90
  init({
65
91
  serverUrl: 'https://log.example.com', // 不带尾斜杠;App 真机不要用 localhost
66
92
  appKey: '<看板「应用管理」分配>',
93
+ appSecret: '<看板「应用管理」分配,与 appKey 成对>',
67
94
  appVer: '1.0.0',
68
95
  release: 'release',
69
96
  channel: 'default',
70
97
  })
71
98
  ```
72
99
 
100
+ > 服务端默认强制 HMAC-SHA256 签名。`appSecret` 只应通过构建环境变量/CI 注入,
101
+ > 不要提交进各项目仓库;泄露后在看板「重置凭据」即可作废旧值。
102
+
73
103
  ### 选项
74
104
 
75
105
  | 选项 | 类型 | 默认 | 说明 |
76
106
  | --- | --- | --- | --- |
77
107
  | `serverUrl` | string | 必填 | 服务端地址,上报路径为 `/ingest/v1/logs` |
78
108
  | `appKey` | string | 必填 | 应用 Key,看板「应用管理」获取 |
109
+ | `appSecret` | string | - | 签名密钥;服务端开启强制签名时必填 |
79
110
  | `appVer` | string | - | 业务应用版本号 |
80
111
  | `release` | string | - | 发布渠道/环境标识 |
81
112
  | `channel` | string | - | 渠道 code / 小程序场景值 |
@@ -110,13 +141,36 @@ setConsoleReport(false) // 关闭 console.* 上报(保留原生打印),避
110
141
  await flush() // 应用退后台/页面隐藏时可主动上报
111
142
  ```
112
143
 
144
+ ## React Native / Expo 接入
145
+
146
+ ```bash
147
+ npm i uni-log-sdk @react-native-async-storage/async-storage
148
+ ```
149
+
150
+ ```ts
151
+ import { initRN } from 'uni-log-sdk/react-native'
152
+
153
+ initRN({
154
+ serverUrl: 'https://log.example.com',
155
+ appKey: '<看板分配>',
156
+ appSecret: '<与 appKey 成对>',
157
+ // 页面路由接线(react-navigation 为例):
158
+ getPage: () => navigationRef.getCurrentRoute()?.name ?? null,
159
+ })
160
+ ```
161
+
162
+ - JS 错误经 `ErrorUtils.setGlobalHandler` 自动捕获(链式保留原 handler)。
163
+ - 未处理 Promise rejection 需宿主接线:`require('promise/setimmediate/rejection-tracking').enable({ allRejections: true, onUnhandled: (id, e) => ulog('error', String(e)) })`。
164
+ - 存储经 AsyncStorage 异步写穿 + 冷启动预读;Expo Go 内置 async-storage,bare RN 需安装。
165
+
113
166
  ## 注意事项
114
167
 
115
168
  - `serverUrl` 不要带尾斜杠;App 真机需用局域网 IP 或 HTTPS 域名,Android 9+ 默认禁止明文 HTTP。
116
169
  - 小程序需要将上报域名加入 request 合法域名(开发期可在开发者工具勾选「不校验合法域名」)。
117
170
  - 自动可用的采集:设备信息、会话心跳、JS 错误;页面 PV 与自定义事件需手动调用。
118
- - `console` 全量上报目前依赖运行时劫持;编译期 `transform-console` 插件尚未发布。
119
- - 上报内容会经过服务端协议校验:单批 ≤50 条、`msg` ≤4000 字符、请求体 ≤512KB,超长由 SDK 自动截断。
171
+ - `console` 全量上报通过运行时劫持实现,初始化时自动开启,可用 `hookConsole: false` 关闭。
172
+ - 单批最多 50 条日志 / 50 条事件;单条 `msg` 超过 4000 字符、`stack` 超过 8000 字符会自动截断。服务端请求体上限 1MB,超限批次会被拒绝,SDK 会暂存并在下次启动续传。
173
+ - 各版本的新增、修复与**升级指南(含破坏性变更)**见 [CHANGELOG.md](./CHANGELOG.md)。
120
174
 
121
175
  ## License
122
176
 
@@ -1,32 +0,0 @@
1
- /**
2
- * 由 tsup 产物生成 uni_modules 形态:
3
- * dist/index.mjs -> uni_modules/uni-log/index.js
4
- * 同时写入 uni_modules 插件清单(HBuilderX 需要 id/displayName/version)。
5
- * 在 packages/sdk 下执行 `npm run build` 时自动运行。
6
- */
7
- import { copyFileSync, existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
8
- import { dirname, join } from 'node:path'
9
- import { fileURLToPath } from 'node:url'
10
-
11
- const pkgRoot = join(dirname(fileURLToPath(import.meta.url)), '..')
12
- const pkg = JSON.parse(readFileSync(join(pkgRoot, 'package.json'), 'utf8'))
13
- const pluginDir = join(pkgRoot, 'uni_modules', 'uni-log')
14
-
15
- rmSync(pluginDir, { recursive: true, force: true })
16
- mkdirSync(pluginDir, { recursive: true })
17
- copyFileSync(join(pkgRoot, 'dist', 'index.mjs'), join(pluginDir, 'index.js'))
18
-
19
- const pluginPkg = {
20
- id: 'uni-log',
21
- displayName: 'uni-log 日志上报',
22
- version: pkg.version,
23
- description: pkg.description,
24
- keywords: pkg.keywords ?? [],
25
- }
26
- writeFileSync(join(pluginDir, 'package.json'), `${JSON.stringify(pluginPkg, null, 4)}\n`)
27
-
28
- // HBuilderX 插件详情页展示 readme.md(小写文件名是 uni_modules 约定)
29
- const readme = join(pkgRoot, 'README.md')
30
- if (existsSync(readme)) copyFileSync(readme, join(pluginDir, 'readme.md'))
31
-
32
- console.log(`[uni-log] uni_modules 已生成:${pluginDir}(v${pkg.version})`)