@entmesh/sdk-miniapp 0.0.0-stage → 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/README.md CHANGED
@@ -1,3 +1,187 @@
1
- # Temporary Holding Version
1
+ # Entmesh Mini Program SDK
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ One privacy-first SDK for WeChat, Alipay, and Douyin mini programs. Import the runtime-specific entry, initialize before `App` and `Page` registration, grant analytics consent, and register the Collector domain in the platform console.
4
+
5
+ The first public npm release is [@entmesh/sdk-miniapp@0.2.0](https://www.npmjs.com/package/@entmesh/sdk-miniapp/v/0.2.0), published on 2026-10-31. Its source is tagged [v0.2.0](https://cnb.cool/mliev/entmesh/sdk-miniapp/-/tree/v0.2.0).
6
+
7
+ ## Installation and platform entries
8
+
9
+ Install from the public npm registry:
10
+
11
+ ```sh
12
+ npm install @entmesh/sdk-miniapp --registry=https://registry.npmjs.org/
13
+ ```
14
+
15
+ To reproduce the first release, install `@entmesh/sdk-miniapp@0.2.0` explicitly.
16
+ Use the entry for your platform:
17
+
18
+ | Platform | Import |
19
+ | --- | --- |
20
+ | WeChat | `@entmesh/sdk-miniapp/wechat` |
21
+ | Alipay | `@entmesh/sdk-miniapp/alipay` |
22
+ | Douyin | `@entmesh/sdk-miniapp/douyin` |
23
+
24
+ Each entry exports `createClient` and the platform-independent option types.
25
+ Import a platform subpath; the package root is not an exported entry.
26
+
27
+ ## Quick start
28
+
29
+ ```ts
30
+ import { createClient } from '@entmesh/sdk-miniapp/wechat'
31
+
32
+ const entmesh = createClient({
33
+ endpoint: 'https://events.example.com',
34
+ clientKey: 'ck_...',
35
+ applicationId: 'wx...',
36
+ consent: 'pending',
37
+ autocapture: true,
38
+ })
39
+
40
+ await entmesh.consent('grant')
41
+ await entmesh.track('order_created', { order_id: 'order-1' })
42
+ ```
43
+
44
+ The SDK uses platform secure-random, storage, and request APIs. It never falls back to `Math.random`, never reads host-device advertising identifiers, and never sends plaintext batches.
45
+
46
+ ## Page context and visible time (0.2.1)
47
+
48
+ With `autocapture` enabled, the SDK tracks application startup/foreground/background
49
+ and each page's show/hide/unload lifecycle. Initialize before `App()` and `Page()`
50
+ registration. Page paths are recorded in `context.page.path`; manual `track()` and
51
+ `identify()` events inherit the page that was current when the call occurred.
52
+ `page(route, { title: 'Order details' })` also supplies `context.page.title`.
53
+
54
+ Page visibility events carry `properties.visible_ms`. Each visible interval is
55
+ counted once, even when page hiding, application backgrounding and unloading all
56
+ occur. Background time is excluded. A page exit following an already-recorded hide
57
+ does not repeat the duration. Startup is recorded once per SDK instance, and the
58
+ last visibility/background events enter the persistent queue before flushing.
59
+
60
+ If the user grants consent while a page is already visible, the SDK records that
61
+ page once and begins timing at consent. Activity before consent is not replayed.
62
+ Repeated grants and duplicate show callbacks do not create additional views.
63
+ Clicks, page-internal tab changes, scrolling and element impressions still require
64
+ manual events; this release does not automatically collect them.
65
+
66
+ Upgrade the business mini program to `@entmesh/sdk-miniapp@0.2.1` to collect visible
67
+ time. Earlier events retain their existing route, but no measured duration; reports
68
+ display **未采集** rather than estimating time from neighboring timestamps.
69
+
70
+ Examples written before the public release used `@entmesh/miniapp-sdk`. Update
71
+ both the dependency name and imports to `@entmesh/sdk-miniapp`; the platform
72
+ suffixes and client API remain the same. The public package is distributed through
73
+ npmjs.org, so a CNB npm registry configuration is not required.
74
+
75
+ ## User properties (Proto 4.30)
76
+
77
+ ```ts
78
+ await entmesh.identify('user-123', { plan: 'trial' })
79
+ await entmesh.setUserProperties({ plan: 'pro' })
80
+ await entmesh.unsetUserProperties(['legacy_tier'])
81
+ await entmesh.flush()
82
+ ```
83
+
84
+ Enable the profile platform and organization entitlement before using these APIs. Attribute mutations use a dedicated transport and do not create behavior events or sessions. Set merges specified top-level fields; objects and arrays replace the previous whole value. Unset removes a key; explicit null remains an empty value. Existing identify properties also populate the profile; ordinary event properties do not.
85
+
86
+ Public clients require an identified user and granted consent. Business entities and directed relationships are authored only through server APIs, after their types are registered in the project profile catalog.
87
+
88
+ ## Development and releases
89
+
90
+ Node.js 22 or later is required. Tests run from a standalone checkout; the HPKE
91
+ interoperability fixture is included under `test/fixtures` with its protocol version.
92
+
93
+ ```sh
94
+ npm ci
95
+ npm test
96
+ npm run lint
97
+ npm run build
98
+ npm run check:package
99
+ ```
100
+
101
+ `package.json` is the version source. Both `npm version` and `npm run build`
102
+ synchronize `VERSION` and the generated runtime constant in `src/version.ts`.
103
+
104
+ Pushes and pull requests targeting `main` or `develop` only validate the SDK.
105
+ Pushing a stable `vX.Y.Z` tag runs the release pipeline, sets the package version
106
+ before testing and building,
107
+ and publishes `@entmesh/sdk-miniapp` publicly to npmjs.org. The first release is
108
+ `v0.2.0`; preparing an already-matching package version is supported. Publishing a
109
+ version that already exists on npm fails instead of silently skipping it.
110
+
111
+ Before pushing a release tag, create `sdk-miniapp-npm.yml` on the `main` branch of
112
+ the `mliev/keywords` secret repository:
113
+
114
+ ```yaml
115
+ NPM_TOKEN: "<npm granular publishing token>"
116
+ allow_slugs:
117
+ - mliev/entmesh/sdk-miniapp
118
+ ```
119
+
120
+ The token must have publishing access to the `@entmesh` scope and Bypass 2FA enabled
121
+ for automated publishing. Configure the actual value only in the secret repository.
122
+ Only the publish step imports it. `npm run publish:npm` checks the package, uses a
123
+ temporary npm configuration containing an environment-variable reference, and
124
+ removes that configuration on exit. The token is never written to the SDK source
125
+ or printed by the publishing script.
126
+
127
+ ### Publish a new version
128
+
129
+ Run from a clean `main` checkout. The example uses `0.2.2`; replace it with the
130
+ next unused stable version.
131
+
132
+ ```sh
133
+ release_version=0.2.2
134
+ npm ci
135
+ npm version "$release_version" --no-git-tag-version --allow-same-version
136
+ npm test
137
+ npm run lint
138
+ npm run build
139
+ npm run check:package
140
+ git add package.json package-lock.json VERSION src/version.ts
141
+ git commit -m "chore: prepare sdk-miniapp $release_version"
142
+ git push origin main
143
+ ```
144
+
145
+ After the `main` quality pipeline succeeds, publish its version tag:
146
+
147
+ ```sh
148
+ git tag -a "v$release_version" -m "Release @entmesh/sdk-miniapp $release_version"
149
+ git push origin "refs/tags/v$release_version"
150
+ ```
151
+
152
+ The tag pipeline validates the tag, installs dependencies, synchronizes versions,
153
+ runs tests and type checking, builds, checks package contents, and publishes with
154
+ public access. Package checks cover the three platform entries, declarations,
155
+ runtime version, and the files included in the npm package.
156
+
157
+ ### Verify publication and troubleshoot
158
+
159
+ Check the release pipeline and then verify the public registry:
160
+
161
+ ```sh
162
+ npm view "@entmesh/sdk-miniapp@$release_version" version dist.integrity --registry=https://registry.npmjs.org/ --prefer-online
163
+ ```
164
+
165
+ In a separate consumer project, install the published version and check its imports:
166
+
167
+ ```sh
168
+ npm install "@entmesh/sdk-miniapp@$release_version" --registry=https://registry.npmjs.org/
169
+ node --input-type=module <<'JS'
170
+ for (const platform of ['wechat', 'alipay', 'douyin']) {
171
+ const sdk = await import('@entmesh/sdk-miniapp/' + platform)
172
+ if (typeof sdk.createClient !== 'function') throw new Error(platform)
173
+ console.log(platform + ': import OK')
174
+ }
175
+ JS
176
+ ```
177
+
178
+ - If npm reports that the package is being processed, publication has been accepted
179
+ but registry queries or installs may temporarily return 404. Wait and repeat the
180
+ registry and consumer checks before declaring the version available.
181
+ - A missing `NPM_TOKEN` stops publication. Check the secret file URL, its
182
+ `allow_slugs`, and the token's scope permissions and expiration.
183
+ - An already-published version cannot be overwritten. Use a new version and tag;
184
+ do not move the existing release tag.
185
+ - HPKE tests must read the committed `test/fixtures/hpke-browser-v1.json`. Do not
186
+ restore a dependency on a sibling `proto` checkout. The cross-repository E2E
187
+ contract test checks this copy against the protocol source.
@@ -0,0 +1,4 @@
1
+ import { MiniProgramClient } from './core.js';
2
+ import type { MiniProgramOptions } from './types.js';
3
+ export declare function createClient(options: MiniProgramOptions): MiniProgramClient;
4
+ export type { ConsentState, MiniProgramOptions, Properties } from './types.js';
package/dist/alipay.js ADDED
@@ -0,0 +1,8 @@
1
+ import { MiniProgramClient, installLifecycle } from './core.js';
2
+ import { runtimeAdapter } from './runtime.js';
3
+ export function createClient(options) {
4
+ const client = new MiniProgramClient(runtimeAdapter(globalThis.my, 'alipay_mini_program'), options);
5
+ if (options.autocapture !== false)
6
+ installLifecycle(client);
7
+ return client;
8
+ }
package/dist/core.d.ts ADDED
@@ -0,0 +1,39 @@
1
+ import type { ConsentState, MiniProgramOptions, Properties, RuntimeAdapter } from './types.js';
2
+ export declare class MiniProgramClient {
3
+ private readonly adapter;
4
+ private readonly options;
5
+ private consentState;
6
+ private queue;
7
+ private anonymous;
8
+ private session;
9
+ private user?;
10
+ private timer?;
11
+ private sending?;
12
+ private key?;
13
+ private readonly ready;
14
+ private recording;
15
+ private consentGeneration;
16
+ private readonly lifecycle;
17
+ constructor(adapter: RuntimeAdapter, options: MiniProgramOptions);
18
+ private initialize;
19
+ track(eventName: string, properties?: Properties): Promise<void>;
20
+ page(route: string, properties?: Properties): Promise<void>;
21
+ screen(route: string, properties?: Properties): Promise<void>;
22
+ identify(userID: string, properties?: Properties): Promise<void>;
23
+ setUserProperties(properties: Properties): Promise<void>;
24
+ unsetUserProperties(keys: string[]): Promise<void>;
25
+ private profileMutation;
26
+ reset(): Promise<void>;
27
+ consent(state: ConsentState): Promise<void>;
28
+ refreshDeviceIdentifiers(): Promise<void>;
29
+ flush(): Promise<void>;
30
+ shutdown(): Promise<void>;
31
+ private record;
32
+ private capture;
33
+ private deliver;
34
+ private discovery;
35
+ private readQueue;
36
+ private persistQueue;
37
+ private id;
38
+ }
39
+ export declare function installLifecycle(client: MiniProgramClient): void;
package/dist/core.js ADDED
@@ -0,0 +1,209 @@
1
+ import { decodeBase64url, encryptedEnvelope, sealHPKE, utf8 } from './hpke.js';
2
+ import { SDK_VERSION } from './version.js';
3
+ import { LifecycleTracker } from './lifecycle.js';
4
+ const ANONYMOUS_KEY = 'entmesh_anonymous_id';
5
+ const SESSION_KEY = 'entmesh_session';
6
+ const QUEUE_KEY = 'entmesh_event_queue';
7
+ const SESSION_TIMEOUT = 30 * 60 * 1000;
8
+ const QUEUE_LIMIT = 500;
9
+ const lifecycleTrackers = new WeakMap();
10
+ export class MiniProgramClient {
11
+ constructor(adapter, options) {
12
+ this.adapter = adapter;
13
+ this.options = options;
14
+ this.anonymous = '';
15
+ this.session = { id: '', lastActivity: 0 };
16
+ this.recording = Promise.resolve();
17
+ this.consentGeneration = 0;
18
+ if (!options.clientKey.startsWith('ck_'))
19
+ throw new Error('clientKey must be a ck_ key');
20
+ if (!/^https:\/\//.test(options.endpoint) && !/^http:\/\/localhost(?::\d+)?$/.test(options.endpoint))
21
+ throw new Error('endpoint must use HTTPS');
22
+ this.consentState = options.consent ?? 'pending';
23
+ this.queue = this.readQueue();
24
+ this.lifecycle = new LifecycleTracker(this.consentState === 'grant', (type, name, properties, page) => this.capture(type, name, properties, page), () => this.flush());
25
+ lifecycleTrackers.set(this, this.lifecycle);
26
+ this.ready = this.initialize();
27
+ void this.ready.catch(() => undefined);
28
+ }
29
+ async initialize() {
30
+ this.anonymous = String(this.adapter.getStorage(ANONYMOUS_KEY) || '') || await this.id();
31
+ this.adapter.setStorage(ANONYMOUS_KEY, this.anonymous);
32
+ const stored = this.adapter.getStorage(SESSION_KEY);
33
+ const now = Date.now();
34
+ this.session = stored?.id && now - stored.lastActivity < SESSION_TIMEOUT ? stored : { id: await this.id(), lastActivity: now };
35
+ this.adapter.setStorage(SESSION_KEY, this.session);
36
+ this.timer = setInterval(() => { void this.flush(); }, this.options.flushIntervalMs ?? 5000);
37
+ }
38
+ async track(eventName, properties = {}) { await this.capture('track', eventName, properties); }
39
+ async page(route, properties = {}) {
40
+ const page = this.lifecycle.setPage(route, properties);
41
+ await this.capture('page', '$page_view', { ...properties, route }, page);
42
+ }
43
+ async screen(route, properties = {}) { await this.page(route, properties); }
44
+ async identify(userID, properties = {}) {
45
+ const value = userID.trim();
46
+ if (!value)
47
+ throw new Error('userID is required');
48
+ this.user = value;
49
+ await this.capture('identify', '$identify', properties);
50
+ }
51
+ async setUserProperties(properties) { await this.profileMutation('set', properties); }
52
+ async unsetUserProperties(keys) { await this.profileMutation('unset', undefined, keys); }
53
+ async profileMutation(operation, properties, unset) {
54
+ if (this.consentState !== 'grant')
55
+ return;
56
+ const user = this.user;
57
+ const generation = this.consentGeneration;
58
+ if (!user)
59
+ throw new Error('identify a user before updating properties');
60
+ const occurredAt = new Date().toISOString();
61
+ const values = properties ? JSON.parse(JSON.stringify(properties)) : undefined;
62
+ const keys = unset ? [...unset] : undefined;
63
+ await this.record(async () => {
64
+ if (generation !== this.consentGeneration || this.consentState !== 'grant')
65
+ return;
66
+ if (this.queue.length >= QUEUE_LIMIT)
67
+ throw new Error('profile queue is full');
68
+ const mutationID = await this.id();
69
+ if (generation !== this.consentGeneration || this.consentState !== 'grant')
70
+ return;
71
+ this.queue.push({ mutation_id: mutationID, occurred_at: occurredAt, subject: { kind: 'user', id: user }, operation, ...(values ? { properties: values } : {}), ...(keys ? { unset: keys } : {}) });
72
+ this.persistQueue();
73
+ });
74
+ if (this.queue.length >= (this.options.batchSize ?? 20))
75
+ await this.flush();
76
+ }
77
+ async reset() {
78
+ this.user = undefined;
79
+ await this.ready;
80
+ await this.recording;
81
+ this.anonymous = await this.id();
82
+ this.session = { id: await this.id(), lastActivity: Date.now() };
83
+ this.adapter.setStorage(ANONYMOUS_KEY, this.anonymous);
84
+ this.adapter.setStorage(SESSION_KEY, this.session);
85
+ }
86
+ async consent(state) {
87
+ if (this.consentState !== state)
88
+ this.consentGeneration++;
89
+ this.consentState = state;
90
+ const lifecycle = this.lifecycle.setConsent(state === 'grant');
91
+ if (state === 'deny' || state === 'revoke') {
92
+ this.queue = [];
93
+ this.persistQueue();
94
+ if (state === 'revoke') {
95
+ this.adapter.removeStorage(ANONYMOUS_KEY);
96
+ this.adapter.removeStorage(SESSION_KEY);
97
+ await this.reset();
98
+ }
99
+ return;
100
+ }
101
+ if (state === 'grant') {
102
+ await lifecycle;
103
+ await this.flush();
104
+ }
105
+ }
106
+ async refreshDeviceIdentifiers() { }
107
+ async flush() {
108
+ await this.ready;
109
+ await this.recording;
110
+ while (this.sending)
111
+ await this.sending;
112
+ if (this.consentState !== 'grant' || this.queue.length === 0)
113
+ return;
114
+ this.sending = (async () => { let remaining = this.queue.length; while (remaining > 0 && this.consentState === 'grant') {
115
+ const before = this.queue.length;
116
+ await this.deliver();
117
+ const sent = before - this.queue.length;
118
+ if (sent <= 0)
119
+ break;
120
+ remaining -= sent;
121
+ } })().finally(() => { this.sending = undefined; });
122
+ return this.sending;
123
+ }
124
+ async shutdown() { await this.ready; if (this.timer)
125
+ clearInterval(this.timer); await this.flush(); }
126
+ record(action) {
127
+ const pending = this.recording.then(() => this.ready).then(action);
128
+ this.recording = pending.catch(() => undefined);
129
+ return pending;
130
+ }
131
+ async capture(type, eventName, properties, page = this.lifecycle.pageContext()) {
132
+ if (this.consentState !== 'grant')
133
+ return;
134
+ if (!/^[$A-Za-z][A-Za-z0-9_.-]{0,127}$/.test(eventName))
135
+ throw new Error('event name is invalid');
136
+ const now = Date.now();
137
+ const generation = this.consentGeneration;
138
+ const user = this.user;
139
+ const snapshot = { ...page };
140
+ const endsVisibleInterval = eventName === '$visibility' || eventName === '$page_exit';
141
+ const values = JSON.parse(JSON.stringify(properties));
142
+ await this.record(async () => {
143
+ if (generation !== this.consentGeneration || this.consentState !== 'grant')
144
+ return;
145
+ if (!this.session.id || (!endsVisibleInterval && now - this.session.lastActivity >= SESSION_TIMEOUT))
146
+ this.session = { id: await this.id(), lastActivity: now };
147
+ this.session.lastActivity = now;
148
+ this.adapter.setStorage(SESSION_KEY, this.session);
149
+ const event = {
150
+ message_id: await this.id(), type, event_name: eventName, occurred_at: new Date(now).toISOString(),
151
+ anonymous_id: this.anonymous, session_id: this.session.id, properties: values,
152
+ context: { sdk: { name: 'entmesh-miniapp', version: SDK_VERSION }, device: this.adapter.systemContext(), ...(snapshot.path ? { page: snapshot } : {}) },
153
+ };
154
+ if (user)
155
+ event.user_id = user;
156
+ if (generation !== this.consentGeneration || this.consentState !== 'grant')
157
+ return;
158
+ if (this.queue.length >= QUEUE_LIMIT)
159
+ this.queue.shift();
160
+ this.queue.push(event);
161
+ this.persistQueue();
162
+ });
163
+ if (this.queue.length >= (this.options.batchSize ?? 20))
164
+ await this.flush();
165
+ }
166
+ async deliver() {
167
+ const profile = 'mutation_id' in this.queue[0];
168
+ const events = this.queue.slice(0, this.options.batchSize ?? 20).filter((item, index, items) => items.slice(0, index + 1).every((record) => ('mutation_id' in record) === profile));
169
+ const batchID = await this.id();
170
+ const batch = JSON.stringify({
171
+ schema_version: '1', batch_id: batchID, sent_at: new Date().toISOString(),
172
+ client: { platform: this.adapter.platform, application_id: this.options.applicationId, app_version: this.options.appVersion, sdk_name: 'entmesh-miniapp', sdk_version: SDK_VERSION },
173
+ ...(profile ? { mutations: events } : { events }),
174
+ });
175
+ try {
176
+ const discovery = await this.discovery();
177
+ const info = utf8(`entmesh-client-${profile ? "profile" : "batch"}-v1\0${discovery.kid}\0${this.options.clientKey}`);
178
+ const ciphertext = await sealHPKE(decodeBase64url(discovery.public_key), info, utf8(batch), (length) => this.adapter.randomBytes(length));
179
+ const response = await this.adapter.request({ url: `${this.options.endpoint.replace(/\/$/, '')}/v1/client/${profile ? "profiles/" : ""}batch/${this.options.clientKey}`, method: 'POST', data: JSON.parse(encryptedEnvelope(discovery.kid, ciphertext)), headers: { 'content-type': 'application/json' } });
180
+ if (response.statusCode === 409) {
181
+ this.key = undefined;
182
+ return;
183
+ }
184
+ if (response.statusCode < 200 || response.statusCode >= 300)
185
+ return;
186
+ this.queue = this.queue.filter(event => !events.includes(event));
187
+ this.persistQueue();
188
+ }
189
+ catch { /* Retain the persistent queue for the next bounded flush attempt. */ }
190
+ }
191
+ async discovery() {
192
+ if (this.key && this.key.expiresAt > Date.now())
193
+ return this.key.value;
194
+ const response = await this.adapter.request({ url: `${this.options.endpoint.replace(/\/$/, '')}/v1/browser-encryption-key`, method: 'GET' });
195
+ if (response.statusCode !== 200 || !response.data || typeof response.data !== 'object')
196
+ throw new Error('encryption key discovery failed');
197
+ const value = response.data;
198
+ if (value.version !== '1' || !value.kid || !value.public_key || value.suite?.kem !== 'DHKEM_P256_HKDF_SHA256' || value.suite?.kdf !== 'HKDF_SHA256' || value.suite?.aead !== 'AES_256_GCM')
199
+ throw new Error('encryption key discovery is invalid');
200
+ this.key = { value, expiresAt: Date.now() + 5 * 60 * 1000 };
201
+ return value;
202
+ }
203
+ readQueue() { const value = this.adapter.getStorage(QUEUE_KEY); return Array.isArray(value) ? value.slice(-QUEUE_LIMIT) : []; }
204
+ persistQueue() { this.adapter.setStorage(QUEUE_KEY, this.queue); }
205
+ async id() { return Array.from(await this.adapter.randomBytes(16), (value) => value.toString(16).padStart(2, '0')).join(''); }
206
+ }
207
+ export function installLifecycle(client) {
208
+ lifecycleTrackers.get(client)?.install();
209
+ }
@@ -0,0 +1,4 @@
1
+ import { MiniProgramClient } from './core.js';
2
+ import type { MiniProgramOptions } from './types.js';
3
+ export declare function createClient(options: MiniProgramOptions): MiniProgramClient;
4
+ export type { ConsentState, MiniProgramOptions, Properties } from './types.js';
package/dist/douyin.js ADDED
@@ -0,0 +1,8 @@
1
+ import { MiniProgramClient, installLifecycle } from './core.js';
2
+ import { runtimeAdapter } from './runtime.js';
3
+ export function createClient(options) {
4
+ const client = new MiniProgramClient(runtimeAdapter(globalThis.tt, 'douyin_mini_program'), options);
5
+ if (options.autocapture !== false)
6
+ installLifecycle(client);
7
+ return client;
8
+ }
package/dist/hpke.d.ts ADDED
@@ -0,0 +1,5 @@
1
+ export declare function utf8(value: string): Uint8Array;
2
+ export declare function concat(...values: Uint8Array[]): Uint8Array;
3
+ export declare function decodeBase64url(value: string): Uint8Array;
4
+ export declare function sealHPKE(recipientPublicKey: Uint8Array, info: Uint8Array, plaintext: Uint8Array, randomBytes: (length: number) => Promise<Uint8Array>): Promise<Uint8Array>;
5
+ export declare function encryptedEnvelope(kid: string, ciphertext: Uint8Array): string;
package/dist/hpke.js ADDED
@@ -0,0 +1,100 @@
1
+ import { gcm } from '@noble/ciphers/aes.js';
2
+ import { p256 } from '@noble/curves/nist.js';
3
+ import { expand, extract } from '@noble/hashes/hkdf.js';
4
+ import { sha256 } from '@noble/hashes/sha2.js';
5
+ const VERSION = utf8('HPKE-v1');
6
+ const KEM_SUITE = concat(utf8('KEM'), i2osp(0x0010, 2));
7
+ const HPKE_SUITE = concat(utf8('HPKE'), i2osp(0x0010, 2), i2osp(0x0001, 2), i2osp(0x0002, 2));
8
+ export function utf8(value) {
9
+ const encoded = unescape(encodeURIComponent(value));
10
+ return Uint8Array.from(encoded, (character) => character.charCodeAt(0));
11
+ }
12
+ export function concat(...values) {
13
+ const output = new Uint8Array(values.reduce((sum, value) => sum + value.length, 0));
14
+ let offset = 0;
15
+ for (const value of values) {
16
+ output.set(value, offset);
17
+ offset += value.length;
18
+ }
19
+ return output;
20
+ }
21
+ function i2osp(value, length) {
22
+ const result = new Uint8Array(length);
23
+ for (let index = length - 1; index >= 0; index--) {
24
+ result[index] = value & 0xff;
25
+ value >>>= 8;
26
+ }
27
+ return result;
28
+ }
29
+ function labeledExtract(suite, salt, label, ikm) {
30
+ return extract(sha256, concat(VERSION, suite, utf8(label), ikm), salt);
31
+ }
32
+ function labeledExpand(suite, prk, label, info, length) {
33
+ return expand(sha256, prk, concat(i2osp(length, 2), VERSION, suite, utf8(label), info), length);
34
+ }
35
+ function base64url(bytes) {
36
+ const alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_';
37
+ let output = '';
38
+ for (let offset = 0; offset < bytes.length; offset += 3) {
39
+ const a = bytes[offset] ?? 0, b = bytes[offset + 1] ?? 0, c = bytes[offset + 2] ?? 0;
40
+ const value = (a << 16) | (b << 8) | c;
41
+ output += alphabet[(value >>> 18) & 63] + alphabet[(value >>> 12) & 63];
42
+ if (offset + 1 < bytes.length)
43
+ output += alphabet[(value >>> 6) & 63];
44
+ if (offset + 2 < bytes.length)
45
+ output += alphabet[value & 63];
46
+ }
47
+ return output;
48
+ }
49
+ export function decodeBase64url(value) {
50
+ if (!/^[A-Za-z0-9_-]+$/.test(value))
51
+ throw new Error('invalid base64url');
52
+ const alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_';
53
+ const output = [];
54
+ let buffer = 0, bits = 0;
55
+ for (const character of value) {
56
+ const index = alphabet.indexOf(character);
57
+ if (index < 0)
58
+ throw new Error('invalid base64url');
59
+ buffer = (buffer << 6) | index;
60
+ bits += 6;
61
+ if (bits >= 8) {
62
+ bits -= 8;
63
+ output.push((buffer >>> bits) & 0xff);
64
+ }
65
+ }
66
+ return Uint8Array.from(output);
67
+ }
68
+ export async function sealHPKE(recipientPublicKey, info, plaintext, randomBytes) {
69
+ if (recipientPublicKey.length !== 65 || recipientPublicKey[0] !== 4)
70
+ throw new Error('invalid recipient public key');
71
+ const ikm = await randomBytes(32);
72
+ const dkpPRK = labeledExtract(KEM_SUITE, new Uint8Array(), 'dkp_prk', ikm);
73
+ let secretKey;
74
+ for (let counter = 0; counter < 256 && !secretKey; counter++) {
75
+ const candidate = labeledExpand(KEM_SUITE, dkpPRK, 'candidate', Uint8Array.of(counter), 32);
76
+ try {
77
+ p256.getPublicKey(candidate, false);
78
+ secretKey = candidate;
79
+ }
80
+ catch { /* try the next deterministic candidate */ }
81
+ }
82
+ if (!secretKey)
83
+ throw new Error('secure random private key generation failed');
84
+ const enc = p256.getPublicKey(secretKey, false);
85
+ const dhPoint = p256.getSharedSecret(secretKey, recipientPublicKey, false);
86
+ const dh = dhPoint.slice(1, 33);
87
+ const kemContext = concat(enc, recipientPublicKey);
88
+ const eaePRK = labeledExtract(KEM_SUITE, new Uint8Array(), 'eae_prk', dh);
89
+ const sharedSecret = labeledExpand(KEM_SUITE, eaePRK, 'shared_secret', kemContext, 32);
90
+ const pskIDHash = labeledExtract(HPKE_SUITE, new Uint8Array(), 'psk_id_hash', new Uint8Array());
91
+ const infoHash = labeledExtract(HPKE_SUITE, new Uint8Array(), 'info_hash', info);
92
+ const keyScheduleContext = concat(Uint8Array.of(0), pskIDHash, infoHash);
93
+ const secret = labeledExtract(HPKE_SUITE, sharedSecret, 'secret', new Uint8Array());
94
+ const key = labeledExpand(HPKE_SUITE, secret, 'key', keyScheduleContext, 32);
95
+ const nonce = labeledExpand(HPKE_SUITE, secret, 'base_nonce', keyScheduleContext, 12);
96
+ return concat(enc, gcm(key, nonce, new Uint8Array()).encrypt(plaintext));
97
+ }
98
+ export function encryptedEnvelope(kid, ciphertext) {
99
+ return JSON.stringify({ version: '1', kid, ciphertext: base64url(ciphertext) });
100
+ }
@@ -0,0 +1,2 @@
1
+ export { MiniProgramClient } from './core.js';
2
+ export type * from './types.js';
package/dist/index.js ADDED
@@ -0,0 +1 @@
1
+ export { MiniProgramClient } from './core.js';
@@ -0,0 +1,29 @@
1
+ import type { Properties } from './types.js';
2
+ export interface PageContext {
3
+ path: string;
4
+ title?: string;
5
+ }
6
+ type Emit = (type: 'page' | 'track', name: string, properties: Properties, page: PageContext) => Promise<void>;
7
+ /** Owns visible intervals; App and Page callbacks can close the same interval safely. */
8
+ export declare class LifecycleTracker {
9
+ private granted;
10
+ private readonly emit;
11
+ private readonly flush;
12
+ private readonly pages;
13
+ private active?;
14
+ private context;
15
+ private foreground?;
16
+ private started;
17
+ constructor(granted: boolean, emit: Emit, flush: () => Promise<void>);
18
+ pageContext(): PageContext;
19
+ setPage(path: string, properties?: Properties): PageContext;
20
+ setConsent(granted: boolean): Promise<void>;
21
+ private start;
22
+ private begin;
23
+ private finish;
24
+ private app;
25
+ private page;
26
+ private route;
27
+ install(): void;
28
+ }
29
+ export {};
@@ -0,0 +1,147 @@
1
+ /** Owns visible intervals; App and Page callbacks can close the same interval safely. */
2
+ export class LifecycleTracker {
3
+ constructor(granted, emit, flush) {
4
+ this.granted = granted;
5
+ this.emit = emit;
6
+ this.flush = flush;
7
+ this.pages = new WeakMap();
8
+ this.context = { path: '' };
9
+ this.started = false;
10
+ }
11
+ pageContext() { return { ...this.context }; }
12
+ setPage(path, properties = {}) {
13
+ const title = typeof properties.title === 'string' ? properties.title : undefined;
14
+ this.context = { path, ...(title ? { title } : {}) };
15
+ if (this.active?.page.path === path)
16
+ this.active.page = this.pageContext();
17
+ return this.pageContext();
18
+ }
19
+ setConsent(granted) {
20
+ const changed = this.granted !== granted;
21
+ this.granted = granted;
22
+ if (!granted) {
23
+ if (this.active)
24
+ this.active.since = undefined;
25
+ return Promise.resolve();
26
+ }
27
+ const start = this.start();
28
+ const page = changed && this.active ? this.begin(this.active) : Promise.resolve();
29
+ return Promise.all([start, page]).then(() => undefined);
30
+ }
31
+ start() {
32
+ if (!this.granted || this.started)
33
+ return Promise.resolve();
34
+ this.started = true;
35
+ return this.emit('track', '$app_start', {}, this.pageContext());
36
+ }
37
+ begin(state) {
38
+ if (!this.granted || this.foreground === false || !state.shown || state.since !== undefined)
39
+ return Promise.resolve();
40
+ state.since = Date.now();
41
+ return this.emit('page', '$page_view', { route: state.page.path }, { ...state.page });
42
+ }
43
+ finish(state, name) {
44
+ if (!state)
45
+ return Promise.resolve();
46
+ const since = state.since;
47
+ state.since = undefined;
48
+ if (!this.granted || (since === undefined && name === '$visibility'))
49
+ return Promise.resolve();
50
+ const properties = { route: state.page.path };
51
+ if (since !== undefined)
52
+ properties.visible_ms = Math.max(0, Date.now() - since);
53
+ return this.emit('track', name, properties, { ...state.page });
54
+ }
55
+ app(handler, options) {
56
+ const path = options && typeof options === 'object' && 'path' in options && typeof options.path === 'string' ? options.path : '';
57
+ if (path && !this.active)
58
+ this.setPage(path);
59
+ if (handler === 'onLaunch')
60
+ return this.start();
61
+ if (handler === 'onShow') {
62
+ if (this.foreground === true)
63
+ return Promise.resolve();
64
+ this.foreground = true;
65
+ const foreground = this.emit('track', '$app_foreground', {}, this.pageContext());
66
+ const page = this.active && (!path || path === this.active.page.path) ? this.begin(this.active) : Promise.resolve();
67
+ return Promise.all([foreground, page]).then(() => undefined);
68
+ }
69
+ if (this.foreground === false)
70
+ return Promise.resolve();
71
+ this.foreground = false;
72
+ const visible = this.finish(this.active, '$visibility');
73
+ const background = this.emit('track', '$app_background', {}, this.pageContext());
74
+ return Promise.all([visible, background]).then(() => this.flush());
75
+ }
76
+ page(handler, owner) {
77
+ let state = this.pages.get(owner);
78
+ if (handler === 'onShow') {
79
+ const path = this.route(owner);
80
+ if (!state) {
81
+ state = { page: { path }, shown: false };
82
+ this.pages.set(owner, state);
83
+ }
84
+ const previous = this.active !== state ? this.finish(this.active, '$visibility') : Promise.resolve();
85
+ if (this.active && this.active !== state)
86
+ this.active.shown = false;
87
+ state.page = { ...state.page, path };
88
+ state.shown = true;
89
+ this.active = state;
90
+ this.context = { ...state.page };
91
+ return Promise.all([previous, this.begin(state)]).then(() => undefined);
92
+ }
93
+ if (!state)
94
+ return Promise.resolve();
95
+ state.shown = false;
96
+ const result = this.finish(state, handler === 'onUnload' ? '$page_exit' : '$visibility');
97
+ if (handler === 'onUnload') {
98
+ this.pages.delete(owner);
99
+ if (this.active === state)
100
+ this.active = undefined;
101
+ }
102
+ return result;
103
+ }
104
+ route(owner) {
105
+ const route = owner.route || owner.__route__;
106
+ if (typeof route === 'string')
107
+ return route;
108
+ const getPages = globalThis.getCurrentPages;
109
+ if (typeof getPages === 'function') {
110
+ try {
111
+ const pages = getPages();
112
+ const current = pages[pages.length - 1];
113
+ return String(current?.route || current?.__route__ || '');
114
+ }
115
+ catch { /* Some runtimes expose no page stack during registration. */ }
116
+ }
117
+ return '';
118
+ }
119
+ install() {
120
+ const root = globalThis;
121
+ for (const name of ['App', 'Page']) {
122
+ const original = root[name];
123
+ if (typeof original !== 'function' || original.__entmesh)
124
+ continue;
125
+ const tracker = this;
126
+ const wrapped = (options) => {
127
+ const next = { ...options };
128
+ const handlers = name === 'App' ? ['onLaunch', 'onShow', 'onHide'] : ['onShow', 'onHide', 'onUnload'];
129
+ for (const handler of handlers) {
130
+ const existing = next[handler];
131
+ next[handler] = function (...args) {
132
+ // Analytics errors must not replace a business callback's return value or exception.
133
+ try {
134
+ const pending = name === 'App' ? tracker.app(handler, args[0]) : tracker.page(handler, this);
135
+ void pending.catch(() => undefined);
136
+ }
137
+ catch { /* The application's lifecycle still runs if collection fails. */ }
138
+ return typeof existing === 'function' ? existing.apply(this, args) : undefined;
139
+ };
140
+ }
141
+ return original(next);
142
+ };
143
+ wrapped.__entmesh = true;
144
+ root[name] = wrapped;
145
+ }
146
+ }
147
+ }
@@ -0,0 +1,29 @@
1
+ import type { PropertyValue } from './types.js';
2
+ export interface ProfileSubject {
3
+ kind: 'user' | 'entity';
4
+ id: string;
5
+ entity_type?: string;
6
+ }
7
+ export interface ProfileMutation {
8
+ mutation_id: string;
9
+ occurred_at: string;
10
+ subject: ProfileSubject;
11
+ operation: 'set' | 'unset' | 'entity_upsert' | 'link' | 'unlink';
12
+ properties?: Record<string, PropertyValue>;
13
+ unset?: string[];
14
+ relation_type?: string;
15
+ target?: ProfileSubject;
16
+ }
17
+ export interface ProfileBatch {
18
+ schema_version: '1';
19
+ batch_id: string;
20
+ sent_at: string;
21
+ client?: {
22
+ platform: string;
23
+ application_id: string;
24
+ app_version?: string;
25
+ sdk_name: string;
26
+ sdk_version: string;
27
+ };
28
+ mutations: ProfileMutation[];
29
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,4 @@
1
+ import type { MiniProgramPlatform, RuntimeAdapter } from './types.js';
2
+ type Runtime = Record<string, (...args: never[]) => unknown>;
3
+ export declare function runtimeAdapter(runtime: Runtime, platform: MiniProgramPlatform): RuntimeAdapter;
4
+ export {};
@@ -0,0 +1,81 @@
1
+ function callRequest(runtime, options) {
2
+ return new Promise((resolve, reject) => {
3
+ const request = runtime.request;
4
+ if (typeof request !== 'function') {
5
+ reject(new Error('mini-program request API is unavailable'));
6
+ return;
7
+ }
8
+ request.call(runtime, {
9
+ url: options.url, method: options.method, data: options.data,
10
+ header: options.headers, headers: options.headers,
11
+ dataType: options.method === 'GET' ? 'json' : 'text',
12
+ success: (result) => resolve({ statusCode: Number(result.statusCode ?? result.status ?? 0), data: result.data }),
13
+ fail: reject,
14
+ });
15
+ });
16
+ }
17
+ function secureRandom(runtime, length) {
18
+ return new Promise((resolve, reject) => {
19
+ const getRandomValues = runtime.getRandomValues;
20
+ if (typeof getRandomValues !== 'function') {
21
+ reject(new Error('secure random API is unavailable'));
22
+ return;
23
+ }
24
+ getRandomValues.call(runtime, {
25
+ length,
26
+ success: (result) => {
27
+ const value = result.randomValues ?? result.data;
28
+ if (value instanceof ArrayBuffer)
29
+ resolve(new Uint8Array(value));
30
+ else if (ArrayBuffer.isView(value))
31
+ resolve(new Uint8Array(value.buffer, value.byteOffset, value.byteLength));
32
+ else
33
+ reject(new Error('secure random API returned invalid bytes'));
34
+ },
35
+ fail: reject,
36
+ });
37
+ });
38
+ }
39
+ export function runtimeAdapter(runtime, platform) {
40
+ return {
41
+ platform,
42
+ request: (options) => callRequest(runtime, options),
43
+ getStorage(key) {
44
+ const value = typeof runtime.getStorageSync === 'function'
45
+ ? runtime.getStorageSync.call(runtime, (platform === 'alipay_mini_program' ? { key } : key))
46
+ : undefined;
47
+ if (value && typeof value === 'object' && 'data' in value)
48
+ return value.data;
49
+ return value;
50
+ },
51
+ setStorage(key, value) {
52
+ if (typeof runtime.setStorageSync !== 'function')
53
+ return;
54
+ if (platform === 'alipay_mini_program')
55
+ runtime.setStorageSync.call(runtime, { key, data: value });
56
+ else
57
+ runtime.setStorageSync.call(runtime, key, value);
58
+ },
59
+ removeStorage(key) {
60
+ if (typeof runtime.removeStorageSync !== 'function')
61
+ return;
62
+ if (platform === 'alipay_mini_program')
63
+ runtime.removeStorageSync.call(runtime, { key });
64
+ else
65
+ runtime.removeStorageSync.call(runtime, key);
66
+ },
67
+ randomBytes: (length) => secureRandom(runtime, length),
68
+ systemContext() {
69
+ for (const name of ['getDeviceInfo', 'getDeviceInfoSync', 'getSystemInfoSync']) {
70
+ const method = runtime[name];
71
+ if (typeof method === 'function') {
72
+ try {
73
+ return method.call(runtime);
74
+ }
75
+ catch { /* try the next supported API */ }
76
+ }
77
+ }
78
+ return {};
79
+ },
80
+ };
81
+ }
@@ -0,0 +1,44 @@
1
+ export type ConsentState = 'pending' | 'grant' | 'deny' | 'revoke';
2
+ export type MiniProgramPlatform = 'wechat_mini_program' | 'alipay_mini_program' | 'douyin_mini_program';
3
+ export type PropertyScalar = string | number | boolean | null;
4
+ export type PropertyValue = PropertyScalar | PropertyScalar[] | Record<string, PropertyScalar>;
5
+ export type Properties = Record<string, PropertyValue>;
6
+ export interface MiniProgramOptions {
7
+ endpoint: string;
8
+ clientKey: string;
9
+ applicationId: string;
10
+ appVersion?: string;
11
+ consent?: ConsentState;
12
+ autocapture?: boolean;
13
+ flushIntervalMs?: number;
14
+ batchSize?: number;
15
+ }
16
+ export interface EventV1 {
17
+ message_id: string;
18
+ type: 'page' | 'track' | 'identify';
19
+ event_name: string;
20
+ occurred_at: string;
21
+ anonymous_id: string;
22
+ user_id?: string;
23
+ session_id: string;
24
+ properties: Properties;
25
+ context: Record<string, unknown>;
26
+ }
27
+ export interface RuntimeResponse {
28
+ statusCode: number;
29
+ data: unknown;
30
+ }
31
+ export interface RuntimeAdapter {
32
+ readonly platform: MiniProgramPlatform;
33
+ request(options: {
34
+ url: string;
35
+ method: 'GET' | 'POST';
36
+ data?: unknown;
37
+ headers?: Record<string, string>;
38
+ }): Promise<RuntimeResponse>;
39
+ getStorage(key: string): unknown;
40
+ setStorage(key: string, value: unknown): void;
41
+ removeStorage(key: string): void;
42
+ randomBytes(length: number): Promise<Uint8Array>;
43
+ systemContext(): Record<string, unknown>;
44
+ }
package/dist/types.js ADDED
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1 @@
1
+ export declare const SDK_VERSION = "0.2.1";
@@ -0,0 +1,2 @@
1
+ // Generated from package.json by scripts/sync-version.mjs.
2
+ export const SDK_VERSION = '0.2.1';
@@ -0,0 +1,4 @@
1
+ import { MiniProgramClient } from './core.js';
2
+ import type { MiniProgramOptions } from './types.js';
3
+ export declare function createClient(options: MiniProgramOptions): MiniProgramClient;
4
+ export type { ConsentState, MiniProgramOptions, Properties } from './types.js';
package/dist/wechat.js ADDED
@@ -0,0 +1,8 @@
1
+ import { MiniProgramClient, installLifecycle } from './core.js';
2
+ import { runtimeAdapter } from './runtime.js';
3
+ export function createClient(options) {
4
+ const client = new MiniProgramClient(runtimeAdapter(globalThis.wx, 'wechat_mini_program'), options);
5
+ if (options.autocapture !== false)
6
+ installLifecycle(client);
7
+ return client;
8
+ }
package/package.json CHANGED
@@ -1,6 +1,49 @@
1
1
  {
2
2
  "name": "@entmesh/sdk-miniapp",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.1",
4
+ "type": "module",
5
+ "main": "./dist/index.js",
6
+ "types": "./dist/index.d.ts",
7
+ "exports": {
8
+ "./wechat": {
9
+ "types": "./dist/wechat.d.ts",
10
+ "import": "./dist/wechat.js"
11
+ },
12
+ "./alipay": {
13
+ "types": "./dist/alipay.d.ts",
14
+ "import": "./dist/alipay.js"
15
+ },
16
+ "./douyin": {
17
+ "types": "./dist/douyin.d.ts",
18
+ "import": "./dist/douyin.js"
19
+ }
20
+ },
21
+ "files": [
22
+ "dist",
23
+ "README.md"
24
+ ],
25
+ "publishConfig": {
26
+ "registry": "https://registry.npmjs.org/",
27
+ "access": "public"
28
+ },
29
+ "scripts": {
30
+ "build": "node scripts/sync-version.mjs && tsc -p tsconfig.json",
31
+ "test": "vitest run",
32
+ "lint": "tsc --noEmit",
33
+ "version": "node scripts/sync-version.mjs",
34
+ "check:package": "node scripts/check-package.mjs",
35
+ "publish:npm": "node scripts/publish.mjs"
36
+ },
37
+ "dependencies": {
38
+ "@noble/ciphers": "^2.0.1",
39
+ "@noble/curves": "^2.0.1",
40
+ "@noble/hashes": "^2.0.1"
41
+ },
42
+ "devDependencies": {
43
+ "typescript": "^5.8.3",
44
+ "vitest": "^3.2.4"
45
+ },
46
+ "engines": {
47
+ "node": ">=22"
48
+ }
49
+ }