@appgrowstack/app-events 0.0.0-stage → 0.7.0
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/CHANGELOG.md +121 -0
- package/LICENSE +21 -0
- package/README.md +231 -2
- package/dist/catalog.d.ts +65 -0
- package/dist/catalog.js +102 -0
- package/dist/common-catalog.generated.d.ts +5 -0
- package/dist/common-catalog.generated.js +957 -0
- package/dist/envelope.d.ts +106 -0
- package/dist/envelope.js +145 -0
- package/dist/forward.d.ts +79 -0
- package/dist/forward.js +155 -0
- package/dist/handler.d.ts +105 -0
- package/dist/handler.js +137 -0
- package/dist/index.d.ts +7 -0
- package/dist/index.js +8 -0
- package/dist/migration.d.ts +1 -0
- package/dist/migration.js +15 -0
- package/dist/store.d.ts +94 -0
- package/dist/store.js +112 -0
- package/migrations/0001_app_events.sql +15 -0
- package/migrations/0002_app_events_auth_kind.sql +5 -0
- package/migrations/0003_app_events_form.sql +4 -0
- package/package.json +42 -4
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
import { type Catalog } from "./catalog.js";
|
|
2
|
+
export declare const SCHEMA_VERSION = 1;
|
|
3
|
+
/**
|
|
4
|
+
* ビルドの種類。iOS は testflight(TestFlight)・appstore(App Store)、Android は play_test(Google Play の内部テスト・クローズドテスト)・play(Google Play の製品版)。
|
|
5
|
+
* debug は開発中のビルド(どちらの OS も)。OS は channel から分かるので、封筒に OS の欄は持たない
|
|
6
|
+
*/
|
|
7
|
+
export declare const CHANNELS: readonly ["debug", "testflight", "appstore", "play_test", "play"];
|
|
8
|
+
export type Channel = (typeof CHANNELS)[number];
|
|
9
|
+
/** ストアの製品版から入れた人のビルド。数える人はこれと、channel が null(列より前の版)の行 */
|
|
10
|
+
export declare const STORE_CHANNELS: readonly ["appstore", "play"];
|
|
11
|
+
/** Google Play のビルド。公開した版(App Store Connect から取る)の絞りを当てない */
|
|
12
|
+
export declare const PLAY_CHANNELS: readonly ["play_test", "play"];
|
|
13
|
+
/**
|
|
14
|
+
* 端末の形(電話のアプリが TV の画面も持つときなど、同じ channel の中で分けて数える)。無い・null・空の文字列は null(電話・タブレットの既定の形)。
|
|
15
|
+
* 小文字で始まる16字までの英小文字と _(例 tv)。ほかの形は封筒ごと 400 で断る
|
|
16
|
+
*/
|
|
17
|
+
export declare const FORM: RegExp;
|
|
18
|
+
export interface Envelope {
|
|
19
|
+
schema_version: number;
|
|
20
|
+
app: string;
|
|
21
|
+
install_id: string;
|
|
22
|
+
uid: string | null;
|
|
23
|
+
app_version: string | null;
|
|
24
|
+
build: string | null;
|
|
25
|
+
channel: Channel | null;
|
|
26
|
+
lang: string | null;
|
|
27
|
+
region: string | null;
|
|
28
|
+
form: string | null;
|
|
29
|
+
sent_at: number;
|
|
30
|
+
}
|
|
31
|
+
export type PropValue = string | number | boolean;
|
|
32
|
+
export interface AppEvent {
|
|
33
|
+
id: string;
|
|
34
|
+
name: string;
|
|
35
|
+
occurred_at: number;
|
|
36
|
+
props: Record<string, PropValue>;
|
|
37
|
+
}
|
|
38
|
+
/** 外した出来事(index は events の何番目か) */
|
|
39
|
+
export interface Rejected {
|
|
40
|
+
index: number;
|
|
41
|
+
id: string | null;
|
|
42
|
+
reason: string;
|
|
43
|
+
}
|
|
44
|
+
/** カタログに無い名前・引数が合わない出来事。mark のときは書いた上でここに載る */
|
|
45
|
+
export interface Marked {
|
|
46
|
+
id: string;
|
|
47
|
+
name: string;
|
|
48
|
+
reason: string;
|
|
49
|
+
}
|
|
50
|
+
export interface CatalogCheck {
|
|
51
|
+
catalog: Catalog;
|
|
52
|
+
/** アプリ固有の出来事の名前(共通カタログに無いが送ってよい) */
|
|
53
|
+
extraEvents?: readonly string[];
|
|
54
|
+
/**
|
|
55
|
+
* カタログに無い名前と引数の合わない出来事を、外す(reject)か、書いて印を付ける(mark・既定)。
|
|
56
|
+
* reject のときは値までカタログに照らす(checkProps の strict)。アプリの catalog.json を渡して使う
|
|
57
|
+
*/
|
|
58
|
+
unknown?: "reject" | "mark";
|
|
59
|
+
/** true なら count・number・flag を文字列の形でも受ける(checkProps の stringValues)。既定は false */
|
|
60
|
+
stringValues?: boolean;
|
|
61
|
+
}
|
|
62
|
+
export interface ParseOptions {
|
|
63
|
+
/** このアプリの名前。封筒の app と違えば断る */
|
|
64
|
+
app: string;
|
|
65
|
+
now: number;
|
|
66
|
+
check: CatalogCheck;
|
|
67
|
+
maxEvents?: number;
|
|
68
|
+
/** 1つの出来事の引数の数の上限(既定 DEFAULT_MAX_PROPS)。超えた出来事は外す。Infinity で数えない */
|
|
69
|
+
maxProps?: number;
|
|
70
|
+
/** 引数の名前と、文字列の値の長さの上限(既定 DEFAULT_MAX_TEXT)。超えた出来事は外す。Infinity で数えない */
|
|
71
|
+
maxText?: number;
|
|
72
|
+
/**
|
|
73
|
+
* app_version の形。渡すと、合わない封筒を 400 で断る(例 NUMERIC_APP_VERSION)。既定は照らさない(32字までの文字列)
|
|
74
|
+
*/
|
|
75
|
+
appVersion?: RegExp;
|
|
76
|
+
/**
|
|
77
|
+
* install_id の大小。lower(既定)は小文字にしてから書く(約束は小文字。前に大文字で送っていた端末も同じ人として数える)。
|
|
78
|
+
* keep は届いたまま(前からある表に大文字の行があり、表の中で同じ端末を数え続けるアプリ)
|
|
79
|
+
*/
|
|
80
|
+
installIdCase?: "lower" | "keep";
|
|
81
|
+
}
|
|
82
|
+
/** 数字と点だけの版(1・1.2・1.2.3・1.2.3.4)。前のじぶんBGM の受け口が通していた形 */
|
|
83
|
+
export declare const NUMERIC_APP_VERSION: RegExp;
|
|
84
|
+
export type Parsed = {
|
|
85
|
+
ok: true;
|
|
86
|
+
envelope: Envelope;
|
|
87
|
+
events: AppEvent[];
|
|
88
|
+
rejected: Rejected[];
|
|
89
|
+
marked: Marked[];
|
|
90
|
+
} | {
|
|
91
|
+
ok: false;
|
|
92
|
+
status: 400 | 413;
|
|
93
|
+
error: string;
|
|
94
|
+
};
|
|
95
|
+
export declare const DEFAULT_MAX_EVENTS = 200;
|
|
96
|
+
/**
|
|
97
|
+
* 1つの出来事の引数の数の上限。いまのアプリのカタログで一番多い出来事(ごほうび習慣の paywall_shown・読書メモリーの
|
|
98
|
+
* lookback_sheet_placed)が 16 個なので、その倍。生成器の envelope の方言は数を決めていないので、カタログの側で増えても外れないよう余裕を持つ
|
|
99
|
+
*/
|
|
100
|
+
export declare const DEFAULT_MAX_PROPS = 32;
|
|
101
|
+
/**
|
|
102
|
+
* 引数の名前と文字列の値の長さの上限。swift-analytics の値の上限(envelope の方言の token・enum は 64 字、ga4 は 100 字)より上に置き、
|
|
103
|
+
* 人の書いた文(メモ・習慣の名前など)が値に入って届く入口を塞ぐ。ごほうび習慣の前の受け口の MAX_TEXT と同じ
|
|
104
|
+
*/
|
|
105
|
+
export declare const DEFAULT_MAX_TEXT = 100;
|
|
106
|
+
export declare function parseEnvelope(body: unknown, opts: ParseOptions): Parsed;
|
package/dist/envelope.js
ADDED
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
// 封筒(swift-analytics の Schema/common/ENVELOPE.md)を読んで確かめる。app-playbook の config/catalog/ENVELOPE.md が写し。
|
|
2
|
+
// 封筒の形が崩れていれば全体を断り、出来事の1つが崩れていればその出来事だけを外す(残りは受ける。swift-analytics の BatchSink は 400・413 で束ごと捨てるので、1つのために束を断らない)
|
|
3
|
+
import { checkProps, findEvent } from "./catalog.js";
|
|
4
|
+
export const SCHEMA_VERSION = 1;
|
|
5
|
+
/**
|
|
6
|
+
* ビルドの種類。iOS は testflight(TestFlight)・appstore(App Store)、Android は play_test(Google Play の内部テスト・クローズドテスト)・play(Google Play の製品版)。
|
|
7
|
+
* debug は開発中のビルド(どちらの OS も)。OS は channel から分かるので、封筒に OS の欄は持たない
|
|
8
|
+
*/
|
|
9
|
+
export const CHANNELS = ["debug", "testflight", "appstore", "play_test", "play"];
|
|
10
|
+
/** ストアの製品版から入れた人のビルド。数える人はこれと、channel が null(列より前の版)の行 */
|
|
11
|
+
export const STORE_CHANNELS = ["appstore", "play"];
|
|
12
|
+
/** Google Play のビルド。公開した版(App Store Connect から取る)の絞りを当てない */
|
|
13
|
+
export const PLAY_CHANNELS = ["play_test", "play"];
|
|
14
|
+
/**
|
|
15
|
+
* 端末の形(電話のアプリが TV の画面も持つときなど、同じ channel の中で分けて数える)。無い・null・空の文字列は null(電話・タブレットの既定の形)。
|
|
16
|
+
* 小文字で始まる16字までの英小文字と _(例 tv)。ほかの形は封筒ごと 400 で断る
|
|
17
|
+
*/
|
|
18
|
+
export const FORM = /^[a-z][a-z_]{0,15}$/;
|
|
19
|
+
/** 数字と点だけの版(1・1.2・1.2.3・1.2.3.4)。前のじぶんBGM の受け口が通していた形 */
|
|
20
|
+
export const NUMERIC_APP_VERSION = /^\d{1,4}(\.\d{1,4}){0,3}$/;
|
|
21
|
+
export const DEFAULT_MAX_EVENTS = 200;
|
|
22
|
+
/**
|
|
23
|
+
* 1つの出来事の引数の数の上限。いまのアプリのカタログで一番多い出来事(ごほうび習慣の paywall_shown・読書メモリーの
|
|
24
|
+
* lookback_sheet_placed)が 16 個なので、その倍。生成器の envelope の方言は数を決めていないので、カタログの側で増えても外れないよう余裕を持つ
|
|
25
|
+
*/
|
|
26
|
+
export const DEFAULT_MAX_PROPS = 32;
|
|
27
|
+
/**
|
|
28
|
+
* 引数の名前と文字列の値の長さの上限。swift-analytics の値の上限(envelope の方言の token・enum は 64 字、ga4 は 100 字)より上に置き、
|
|
29
|
+
* 人の書いた文(メモ・習慣の名前など)が値に入って届く入口を塞ぐ。ごほうび習慣の前の受け口の MAX_TEXT と同じ
|
|
30
|
+
*/
|
|
31
|
+
export const DEFAULT_MAX_TEXT = 100;
|
|
32
|
+
const NAME = /^[a-z][a-z0-9_]{0,39}$/;
|
|
33
|
+
const ID = /^[A-Za-z0-9_.:-]{1,64}$/;
|
|
34
|
+
/** これより小さい時刻は秒で送っている(2001-09-09 より前のミリ秒) */
|
|
35
|
+
const MIN_MS = 1_000_000_000_000;
|
|
36
|
+
const FUTURE_MS = 24 * 60 * 60 * 1000;
|
|
37
|
+
/** 無い・null・空の文字列は null(空の文字列の行と null の行が混ざると、言語ごとの数え方が2つになる) */
|
|
38
|
+
function optString(o, k, max = 64) {
|
|
39
|
+
const v = o[k];
|
|
40
|
+
if (v === undefined || v === null || v === "")
|
|
41
|
+
return null;
|
|
42
|
+
if (typeof v !== "string" || v.length > max)
|
|
43
|
+
return new Error(`${k} が ${max} 字以内の文字列でない`);
|
|
44
|
+
return v;
|
|
45
|
+
}
|
|
46
|
+
export function parseEnvelope(body, opts) {
|
|
47
|
+
const bad = (error, status = 400) => ({ ok: false, status, error });
|
|
48
|
+
if (typeof body !== "object" || body === null || Array.isArray(body))
|
|
49
|
+
return bad("封筒が JSON の表でない");
|
|
50
|
+
const o = body;
|
|
51
|
+
if (o.schema_version !== SCHEMA_VERSION)
|
|
52
|
+
return bad(`schema_version が ${SCHEMA_VERSION} でない: ${JSON.stringify(o.schema_version)}`);
|
|
53
|
+
if (o.app !== opts.app)
|
|
54
|
+
return bad(`app が ${opts.app} でない: ${JSON.stringify(o.app)}`);
|
|
55
|
+
if (typeof o.install_id !== "string" || !ID.test(o.install_id))
|
|
56
|
+
return bad("install_id が無いか形が違う");
|
|
57
|
+
if (typeof o.sent_at !== "number" || !Number.isInteger(o.sent_at))
|
|
58
|
+
return bad("sent_at が整数のミリ秒でない");
|
|
59
|
+
if (o.sent_at < MIN_MS)
|
|
60
|
+
return bad("sent_at が秒に見える(ミリ秒で送る)");
|
|
61
|
+
if (o.channel !== undefined && o.channel !== null && o.channel !== "" && !CHANNELS.includes(o.channel)) {
|
|
62
|
+
return bad(`channel が ${CHANNELS.join("・")} のどれでもない: ${JSON.stringify(o.channel)}`);
|
|
63
|
+
}
|
|
64
|
+
const fields = { uid: optString(o, "uid", 128), app_version: optString(o, "app_version", 32), build: optString(o, "build", 32), lang: optString(o, "lang", 16), region: optString(o, "region", 16), form: optString(o, "form", 16) };
|
|
65
|
+
for (const v of Object.values(fields))
|
|
66
|
+
if (v instanceof Error)
|
|
67
|
+
return bad(v.message);
|
|
68
|
+
if (typeof fields.form === "string" && !FORM.test(fields.form))
|
|
69
|
+
return bad(`form の形が違う: ${JSON.stringify(fields.form)}`);
|
|
70
|
+
if (opts.appVersion && typeof fields.app_version === "string" && !opts.appVersion.test(fields.app_version)) {
|
|
71
|
+
return bad(`app_version の形が違う: ${JSON.stringify(fields.app_version)}`);
|
|
72
|
+
}
|
|
73
|
+
if (!Array.isArray(o.events))
|
|
74
|
+
return bad("events が配列でない");
|
|
75
|
+
const max = opts.maxEvents ?? DEFAULT_MAX_EVENTS;
|
|
76
|
+
if (o.events.length > max)
|
|
77
|
+
return bad(`events が ${max} 個を超えている(${o.events.length} 個)`, 413);
|
|
78
|
+
const envelope = {
|
|
79
|
+
schema_version: SCHEMA_VERSION,
|
|
80
|
+
app: opts.app,
|
|
81
|
+
// 約束は小文字(app-growth の docs/sdk.md 8節の3)
|
|
82
|
+
install_id: opts.installIdCase === "keep" ? o.install_id : o.install_id.toLowerCase(),
|
|
83
|
+
uid: fields.uid,
|
|
84
|
+
app_version: fields.app_version,
|
|
85
|
+
build: fields.build,
|
|
86
|
+
channel: (o.channel === "" ? null : (o.channel ?? null)),
|
|
87
|
+
lang: fields.lang,
|
|
88
|
+
region: fields.region,
|
|
89
|
+
form: fields.form,
|
|
90
|
+
sent_at: o.sent_at,
|
|
91
|
+
};
|
|
92
|
+
const allowed = new Set([...opts.check.catalog.events.map((e) => e.name), ...(opts.check.extraEvents ?? [])]);
|
|
93
|
+
const rejectUnknown = opts.check.unknown === "reject";
|
|
94
|
+
const maxProps = opts.maxProps ?? DEFAULT_MAX_PROPS;
|
|
95
|
+
const maxText = opts.maxText ?? DEFAULT_MAX_TEXT;
|
|
96
|
+
const events = [];
|
|
97
|
+
const rejected = [];
|
|
98
|
+
const marked = [];
|
|
99
|
+
const seen = new Set();
|
|
100
|
+
o.events.forEach((raw, index) => {
|
|
101
|
+
const e = (typeof raw === "object" && raw !== null ? raw : {});
|
|
102
|
+
const id = typeof e.id === "string" && ID.test(e.id) ? e.id : null;
|
|
103
|
+
const drop = (reason) => rejected.push({ index, id, reason });
|
|
104
|
+
if (!id)
|
|
105
|
+
return drop("id が無いか形が違う");
|
|
106
|
+
if (seen.has(id))
|
|
107
|
+
return drop("同じ束の中で id が重なっている");
|
|
108
|
+
if (typeof e.name !== "string" || !NAME.test(e.name))
|
|
109
|
+
return drop(`name が snake_case の40字以内でない: ${JSON.stringify(e.name)}`);
|
|
110
|
+
if (typeof e.occurred_at !== "number" || !Number.isInteger(e.occurred_at))
|
|
111
|
+
return drop("occurred_at が整数のミリ秒でない");
|
|
112
|
+
if (e.occurred_at < MIN_MS)
|
|
113
|
+
return drop("occurred_at が秒に見える(ミリ秒で送る)");
|
|
114
|
+
if (e.occurred_at > opts.now + FUTURE_MS)
|
|
115
|
+
return drop("occurred_at が1日より先");
|
|
116
|
+
const props = e.props ?? {};
|
|
117
|
+
if (typeof props !== "object" || props === null || Array.isArray(props))
|
|
118
|
+
return drop("props が表でない");
|
|
119
|
+
const nested = Object.entries(props).find(([, v]) => !["string", "number", "boolean"].includes(typeof v));
|
|
120
|
+
if (nested)
|
|
121
|
+
return drop(`props.${nested[0]} が文字列・数・真偽でない(入れ子にしない)`);
|
|
122
|
+
const entries = Object.entries(props);
|
|
123
|
+
if (entries.length > maxProps)
|
|
124
|
+
return drop(`props が ${maxProps} 個を超えている(${entries.length} 個)`);
|
|
125
|
+
// 理由はログと応答に出るので、長い名前と値そのものは載せない
|
|
126
|
+
if (entries.some(([k]) => k.length > maxText))
|
|
127
|
+
return drop(`props に ${maxText} 字を超える名前がある`);
|
|
128
|
+
const long = entries.find(([, v]) => typeof v === "string" && v.length > maxText);
|
|
129
|
+
if (long)
|
|
130
|
+
return drop(`props.${long[0]} の値が ${maxText} 字を超えている`);
|
|
131
|
+
const issues = [];
|
|
132
|
+
if (!allowed.has(e.name))
|
|
133
|
+
issues.push(`カタログに無い名前: ${e.name}`);
|
|
134
|
+
const def = findEvent(opts.check.catalog, e.name);
|
|
135
|
+
if (def)
|
|
136
|
+
issues.push(...checkProps(def, props, { strict: rejectUnknown, stringValues: opts.check.stringValues ?? false }));
|
|
137
|
+
if (issues.length && rejectUnknown)
|
|
138
|
+
return drop(issues.join(" / "));
|
|
139
|
+
seen.add(id);
|
|
140
|
+
events.push({ id, name: e.name, occurred_at: e.occurred_at, props: props });
|
|
141
|
+
if (issues.length)
|
|
142
|
+
marked.push({ id, name: e.name, reason: issues.join(" / ") });
|
|
143
|
+
});
|
|
144
|
+
return { ok: true, envelope, events, rejected, marked };
|
|
145
|
+
}
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
import { type TrackInput, type TypedProps } from "@appgrowstack/app-contract";
|
|
2
|
+
import type { AppEvent, Envelope } from "./envelope.js";
|
|
3
|
+
/** 先に渡すときの値 */
|
|
4
|
+
export interface DestinationContext {
|
|
5
|
+
/** 書いた封筒。install_id は小文字・uid は書いた値 */
|
|
6
|
+
envelope: Envelope;
|
|
7
|
+
/** internal_device を送ったことのある端末か(本人・テスターの端末)。初めて呼んだときに D1 を1回だけ読む */
|
|
8
|
+
internal: () => Promise<boolean>;
|
|
9
|
+
/** 受けた要求の通信の AS 番号(request.cf.asn)。Cloudflare の外から来た要求・テストでは null。appgrowstack が Apple・Google の AS を審査とロボットに分ける */
|
|
10
|
+
asn: number | null;
|
|
11
|
+
fetch: typeof fetch;
|
|
12
|
+
}
|
|
13
|
+
/** 転送先 */
|
|
14
|
+
export interface Destination {
|
|
15
|
+
/** ログに出す名前 */
|
|
16
|
+
readonly name: string;
|
|
17
|
+
/** この先に渡す出来事か */
|
|
18
|
+
accepts(event: AppEvent, envelope: Envelope): boolean;
|
|
19
|
+
/** accepts が true の出来事だけを渡す(1件以上)。投げてもログに1行残すだけ */
|
|
20
|
+
send(events: AppEvent[], ctx: DestinationContext): Promise<void>;
|
|
21
|
+
}
|
|
22
|
+
/** webhookDestination が既定で渡す出来事(入れた・オンボーディングを終えた・ペイウォールを見た・買った) */
|
|
23
|
+
export declare const DEFAULT_FORWARDED: readonly ["first_open", "onboarding_completed", "paywall_shown", "purchase_completed"];
|
|
24
|
+
/** first_open は新しく入れた(kind=fresh)ときだけ。更新して初めての起動は数えない */
|
|
25
|
+
export declare function shouldForward(e: Pick<AppEvent, "name" | "props">, forwarded: readonly string[]): boolean;
|
|
26
|
+
/** webhook の本文(1件ずつ) */
|
|
27
|
+
export interface HookBody {
|
|
28
|
+
id: string;
|
|
29
|
+
type: string;
|
|
30
|
+
occurred_at: string;
|
|
31
|
+
app_user_id: string;
|
|
32
|
+
internal: boolean;
|
|
33
|
+
payload: {
|
|
34
|
+
channel: string | null;
|
|
35
|
+
app_version: string | null;
|
|
36
|
+
build: string | null;
|
|
37
|
+
properties: Record<string, unknown>;
|
|
38
|
+
};
|
|
39
|
+
}
|
|
40
|
+
export declare function hookBody(envelope: Envelope, e: AppEvent, internal: boolean): HookBody;
|
|
41
|
+
export interface WebhookOptions {
|
|
42
|
+
/** 渡す出来事。既定は DEFAULT_FORWARDED(first_open は kind=fresh だけ) */
|
|
43
|
+
events?: readonly string[];
|
|
44
|
+
/** ログに出す名前。既定は webhook */
|
|
45
|
+
name?: string;
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* 任意の URL へ、決めた出来事を1件ずつ POST する(Authorization: Bearer <token>・本文は HookBody)。
|
|
49
|
+
* url か token が無ければ(ローカル・テスト)null を返す。null は destinations に入れてよい(何もしない)
|
|
50
|
+
*/
|
|
51
|
+
export declare function webhookDestination(url: string | null | undefined, token: string | null | undefined, opts?: WebhookOptions): Destination | null;
|
|
52
|
+
/** `env.APPGROWSTACK`(@appgrowstack/app-contract の AppGrowStackService)のうち、使う所だけ */
|
|
53
|
+
export interface AppGrowStackTrack {
|
|
54
|
+
track(input: TrackInput): Promise<unknown>;
|
|
55
|
+
}
|
|
56
|
+
export interface AppGrowStackDestinationOptions {
|
|
57
|
+
/** appgrowstack のプロジェクトの id(binding の props の project と同じ) */
|
|
58
|
+
project: string;
|
|
59
|
+
}
|
|
60
|
+
/** RPC の 1 回に入れる出来事の上限(track の schema の maxItems) */
|
|
61
|
+
export declare const MAX_TRACKED_PER_CALL = 100;
|
|
62
|
+
/** 封筒の install_id を appgrowstack の形(小文字の UUID)にする。合わなければ null(渡さない) */
|
|
63
|
+
export declare function trackInstallId(raw: string): string | null;
|
|
64
|
+
/** 封筒の端末の値。形の合わない物は書かない(書いた物だけ人の像を上書きする) */
|
|
65
|
+
export declare function deviceContextOf(envelope: Envelope): NonNullable<TrackInput["context"]>;
|
|
66
|
+
/** 出来事の中身を型のまま(数は数・真偽は真偽)。名前の合わない引数・有限でない数・200字を超える文字列は外し、40 まで */
|
|
67
|
+
export declare function typedPropsOf(props: AppEvent["props"]): TypedProps;
|
|
68
|
+
/**
|
|
69
|
+
* 書いた出来事から track の入力を作る(100 件ずつ)。actor は install_id だけ
|
|
70
|
+
* (封筒の uid は確かめていないことがあるので、install と uid のつなぎはアプリが identify で受け持つ)
|
|
71
|
+
*/
|
|
72
|
+
export declare function trackInputsOf(project: string, envelope: Envelope, events: readonly AppEvent[], asn?: number | null): TrackInput[];
|
|
73
|
+
/**
|
|
74
|
+
* appgrowstack-core の RPC track へ渡す先。書いた出来事を全部渡す(名前の選び分けをしない。debug・testflight のビルドも渡し、
|
|
75
|
+
* core が見分け(people.md 6節)を付ける)。渡さないのは、約束の形に合わない install_id の封筒と、名前が約束に合わない出来事だけ。
|
|
76
|
+
* binding が無い環境(テスト・ローカル・まだ結んでいない Worker)では null。
|
|
77
|
+
* 投げた誤り(code retry_later など)はログに1行(code と message)。送り直しは端末の次の封筒に任せず、ここでは捨てる
|
|
78
|
+
*/
|
|
79
|
+
export declare function appGrowStackDestination(binding: AppGrowStackTrack | null | undefined, opts: AppGrowStackDestinationOptions): Destination | null;
|
package/dist/forward.js
ADDED
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
// 書いた出来事を外へ渡す先(転送先)の一覧。受け口は D1 に書いた後、新しく入った出来事を、先ごとに選んで渡す。
|
|
2
|
+
// - appGrowStackDestination(env.APPGROWSTACK, { project }) … appgrowstack-core の RPC track へ(書いた出来事を全部。debug のビルドも)
|
|
3
|
+
// - webhookDestination(url, token) … 任意の URL へ1件ずつ POST する(本文は HookBody)
|
|
4
|
+
// どの先も、失敗はログに1行残すだけ(受けた出来事は D1 に残っている)。応答は待たない(waitUntil で走らせる)
|
|
5
|
+
import { rpcErrorCode } from "@appgrowstack/app-contract";
|
|
6
|
+
// --- webhook ------------------------------------------------------------------
|
|
7
|
+
/** webhookDestination が既定で渡す出来事(入れた・オンボーディングを終えた・ペイウォールを見た・買った) */
|
|
8
|
+
export const DEFAULT_FORWARDED = ["first_open", "onboarding_completed", "paywall_shown", "purchase_completed"];
|
|
9
|
+
/** first_open は新しく入れた(kind=fresh)ときだけ。更新して初めての起動は数えない */
|
|
10
|
+
export function shouldForward(e, forwarded) {
|
|
11
|
+
if (!forwarded.includes(e.name))
|
|
12
|
+
return false;
|
|
13
|
+
return e.name !== "first_open" || e.props.kind === "fresh";
|
|
14
|
+
}
|
|
15
|
+
export function hookBody(envelope, e, internal) {
|
|
16
|
+
return {
|
|
17
|
+
id: e.id,
|
|
18
|
+
type: e.name,
|
|
19
|
+
occurred_at: new Date(e.occurred_at).toISOString(),
|
|
20
|
+
app_user_id: envelope.install_id,
|
|
21
|
+
internal,
|
|
22
|
+
payload: { channel: envelope.channel, app_version: envelope.app_version, build: envelope.build, properties: e.props },
|
|
23
|
+
};
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* 任意の URL へ、決めた出来事を1件ずつ POST する(Authorization: Bearer <token>・本文は HookBody)。
|
|
27
|
+
* url か token が無ければ(ローカル・テスト)null を返す。null は destinations に入れてよい(何もしない)
|
|
28
|
+
*/
|
|
29
|
+
export function webhookDestination(url, token, opts = {}) {
|
|
30
|
+
if (!url || !token)
|
|
31
|
+
return null;
|
|
32
|
+
const events = opts.events ?? DEFAULT_FORWARDED;
|
|
33
|
+
const name = opts.name ?? "webhook";
|
|
34
|
+
return {
|
|
35
|
+
name,
|
|
36
|
+
accepts: (e) => shouldForward(e, events),
|
|
37
|
+
async send(list, ctx) {
|
|
38
|
+
const internal = await ctx.internal();
|
|
39
|
+
await Promise.all(list.map(async (e) => {
|
|
40
|
+
const body = hookBody(ctx.envelope, e, internal);
|
|
41
|
+
try {
|
|
42
|
+
const res = await ctx.fetch(url, {
|
|
43
|
+
method: "POST",
|
|
44
|
+
headers: { authorization: `Bearer ${token}`, "content-type": "application/json" },
|
|
45
|
+
body: JSON.stringify(body),
|
|
46
|
+
});
|
|
47
|
+
if (!res.ok)
|
|
48
|
+
console.error(JSON.stringify({ msg: "app_events: 転送が失敗", destination: name, type: body.type, status: res.status }));
|
|
49
|
+
}
|
|
50
|
+
catch (error) {
|
|
51
|
+
console.error(JSON.stringify({ msg: "app_events: 転送が失敗", destination: name, type: body.type, error: String(error) }));
|
|
52
|
+
}
|
|
53
|
+
}));
|
|
54
|
+
},
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
/** RPC の 1 回に入れる出来事の上限(track の schema の maxItems) */
|
|
58
|
+
export const MAX_TRACKED_PER_CALL = 100;
|
|
59
|
+
/** 1 つの出来事の引数の上限(common の typedProps の maxProperties) */
|
|
60
|
+
const MAX_TYPED_PROPS = 40;
|
|
61
|
+
/** 文字列の値の長さの上限(common の typedValue の maxLength) */
|
|
62
|
+
const MAX_TYPED_TEXT = 200;
|
|
63
|
+
const EVENT_NAME = /^[a-z][a-z0-9_]{0,63}$/;
|
|
64
|
+
const PROP_NAME = /^[a-z0-9_]{1,40}$/;
|
|
65
|
+
const INSTALL_ID = /^[a-z0-9-]{8,64}$/;
|
|
66
|
+
const APP_VERSION = /^\d+\.\d+(\.\d+)?$/;
|
|
67
|
+
const LANG = /^[a-z]{2,3}(-[A-Za-z0-9]{2,8})*$/;
|
|
68
|
+
const REGION = /^[A-Z]{2}$/;
|
|
69
|
+
/** 封筒の install_id を appgrowstack の形(小文字の UUID)にする。合わなければ null(渡さない) */
|
|
70
|
+
export function trackInstallId(raw) {
|
|
71
|
+
const id = raw.trim().toLowerCase();
|
|
72
|
+
return INSTALL_ID.test(id) ? id : null;
|
|
73
|
+
}
|
|
74
|
+
/** 封筒の端末の値。形の合わない物は書かない(書いた物だけ人の像を上書きする) */
|
|
75
|
+
export function deviceContextOf(envelope) {
|
|
76
|
+
const context = {};
|
|
77
|
+
const platform = envelope.channel === "appstore" || envelope.channel === "testflight" ? "ios" : envelope.channel === "play" || envelope.channel === "play_test" ? "android" : null;
|
|
78
|
+
if (platform)
|
|
79
|
+
context.platform = platform;
|
|
80
|
+
if (envelope.app_version && APP_VERSION.test(envelope.app_version))
|
|
81
|
+
context.app_version = envelope.app_version;
|
|
82
|
+
if (envelope.channel)
|
|
83
|
+
context.channel = envelope.channel;
|
|
84
|
+
if (envelope.lang && LANG.test(envelope.lang))
|
|
85
|
+
context.lang = envelope.lang;
|
|
86
|
+
if (envelope.region && REGION.test(envelope.region))
|
|
87
|
+
context.region = envelope.region;
|
|
88
|
+
return context;
|
|
89
|
+
}
|
|
90
|
+
/** 出来事の中身を型のまま(数は数・真偽は真偽)。名前の合わない引数・有限でない数・200字を超える文字列は外し、40 まで */
|
|
91
|
+
export function typedPropsOf(props) {
|
|
92
|
+
const typed = {};
|
|
93
|
+
let count = 0;
|
|
94
|
+
for (const [key, value] of Object.entries(props)) {
|
|
95
|
+
if (count >= MAX_TYPED_PROPS)
|
|
96
|
+
break;
|
|
97
|
+
if (!PROP_NAME.test(key))
|
|
98
|
+
continue;
|
|
99
|
+
if (typeof value === "number" && !Number.isFinite(value))
|
|
100
|
+
continue;
|
|
101
|
+
if (typeof value === "string" && value.length > MAX_TYPED_TEXT)
|
|
102
|
+
continue;
|
|
103
|
+
typed[key] = value;
|
|
104
|
+
count += 1;
|
|
105
|
+
}
|
|
106
|
+
return typed;
|
|
107
|
+
}
|
|
108
|
+
/**
|
|
109
|
+
* 書いた出来事から track の入力を作る(100 件ずつ)。actor は install_id だけ
|
|
110
|
+
* (封筒の uid は確かめていないことがあるので、install と uid のつなぎはアプリが identify で受け持つ)
|
|
111
|
+
*/
|
|
112
|
+
export function trackInputsOf(project, envelope, events, asn = null) {
|
|
113
|
+
const installId = trackInstallId(envelope.install_id);
|
|
114
|
+
if (!installId)
|
|
115
|
+
return [];
|
|
116
|
+
const tracked = events
|
|
117
|
+
.filter((e) => EVENT_NAME.test(e.name))
|
|
118
|
+
.map((e) => ({ id: e.id.slice(0, 64), name: e.name, at: Math.max(0, Math.floor(e.occurred_at)), props: typedPropsOf(e.props) }));
|
|
119
|
+
const context = deviceContextOf(envelope);
|
|
120
|
+
if (asn !== null && Number.isInteger(asn) && asn >= 0)
|
|
121
|
+
context.asn = asn;
|
|
122
|
+
const inputs = [];
|
|
123
|
+
for (let start = 0; start < tracked.length; start += MAX_TRACKED_PER_CALL) {
|
|
124
|
+
const [first, ...rest] = tracked.slice(start, start + MAX_TRACKED_PER_CALL);
|
|
125
|
+
if (!first)
|
|
126
|
+
break;
|
|
127
|
+
inputs.push({ project, actor: { install_id: installId }, ...(Object.keys(context).length ? { context } : {}), events: [first, ...rest] });
|
|
128
|
+
}
|
|
129
|
+
return inputs;
|
|
130
|
+
}
|
|
131
|
+
/**
|
|
132
|
+
* appgrowstack-core の RPC track へ渡す先。書いた出来事を全部渡す(名前の選び分けをしない。debug・testflight のビルドも渡し、
|
|
133
|
+
* core が見分け(people.md 6節)を付ける)。渡さないのは、約束の形に合わない install_id の封筒と、名前が約束に合わない出来事だけ。
|
|
134
|
+
* binding が無い環境(テスト・ローカル・まだ結んでいない Worker)では null。
|
|
135
|
+
* 投げた誤り(code retry_later など)はログに1行(code と message)。送り直しは端末の次の封筒に任せず、ここでは捨てる
|
|
136
|
+
*/
|
|
137
|
+
export function appGrowStackDestination(binding, opts) {
|
|
138
|
+
if (!binding)
|
|
139
|
+
return null;
|
|
140
|
+
return {
|
|
141
|
+
name: "appgrowstack",
|
|
142
|
+
accepts: (e, envelope) => trackInstallId(envelope.install_id) !== null && EVENT_NAME.test(e.name),
|
|
143
|
+
async send(events, ctx) {
|
|
144
|
+
for (const input of trackInputsOf(opts.project, ctx.envelope, events, ctx.asn)) {
|
|
145
|
+
try {
|
|
146
|
+
await binding.track(input);
|
|
147
|
+
}
|
|
148
|
+
catch (error) {
|
|
149
|
+
const e = error;
|
|
150
|
+
console.error(JSON.stringify({ msg: "app_events: APPGROWSTACK.track が失敗", project: opts.project, events: input.events.length, code: rpcErrorCode(error), error: String(e?.message ?? error) }));
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
},
|
|
154
|
+
};
|
|
155
|
+
}
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
import type { Catalog } from "./catalog.js";
|
|
2
|
+
import { type AppEvent, type Envelope, type Marked, type Rejected } from "./envelope.js";
|
|
3
|
+
import type { Destination } from "./forward.js";
|
|
4
|
+
import { type D1Like, type EventsTable } from "./store.js";
|
|
5
|
+
export interface AppEventsOptions<E> {
|
|
6
|
+
/** アプリの短い名前(封筒の app) */
|
|
7
|
+
app: string;
|
|
8
|
+
/** 書く D1(例 (env) => env.DB) */
|
|
9
|
+
db: (env: E) => D1Like;
|
|
10
|
+
/** 書く表と列の対応。既定は標準の表 app_events。前からある表(events・properties など)に書くときに渡す(store.ts の EventsTable) */
|
|
11
|
+
table?: EventsTable;
|
|
12
|
+
/** 照らすカタログ。既定は取り込んだ共通カタログ。アプリの生成器の catalog.json(analytics-gen.py generate --json)をそのまま渡す */
|
|
13
|
+
catalog?: Catalog;
|
|
14
|
+
/** 共通カタログに無いが送ってよい、アプリ固有の出来事の名前 */
|
|
15
|
+
extraEvents?: readonly string[];
|
|
16
|
+
/** カタログに無い名前と引数の合わない出来事を、外す(reject)か、書いて印を付ける(mark・既定)。reject は値までカタログに照らす */
|
|
17
|
+
unknown?: "reject" | "mark";
|
|
18
|
+
/**
|
|
19
|
+
* count・number・flag を文字列の形でも受ける("3"・"true")。値を全部文字列で送るアプリのため。既定は false(数・真偽だけ)。
|
|
20
|
+
* 書く値は届いたまま(文字列は文字列で書く)
|
|
21
|
+
*/
|
|
22
|
+
stringValues?: boolean;
|
|
23
|
+
/**
|
|
24
|
+
* 書く uid を決める。確かめた人(Firebase の ID トークンの uid など)を返す。渡すと封筒の uid より優先し、null なら null を書く
|
|
25
|
+
* (確かめられない uid を封筒から書かない)。本文を読む前に呼ぶ。投げれば受け口も投げる(Hono なら onError が 401 などにする)
|
|
26
|
+
*/
|
|
27
|
+
uid?: (req: Request, env: E) => string | null | Promise<string | null>;
|
|
28
|
+
/**
|
|
29
|
+
* 書いた後に呼ぶ。新しく入った出来事だけを渡す(送り直しで前に届いていた物は渡さない)。アプリが自分の通知・集計へ渡すため。
|
|
30
|
+
* 応答は待たない(waitUntil で走らせる)。投げてもログに1行残すだけで、書いた行と応答は変わらない
|
|
31
|
+
*/
|
|
32
|
+
onStored?: (events: AppEvent[], ctx: StoredContext<E>) => void | Promise<void>;
|
|
33
|
+
/**
|
|
34
|
+
* 転送先の一覧。例 (env) => [appGrowStackDestination(env.APPGROWSTACK, { project: "reading-memory" }), webhookDestination(env.HOOK_URL, env.HOOK_TOKEN)]。
|
|
35
|
+
* null・undefined は飛ばす(binding や宛先の無い環境)。無ければ転送しない
|
|
36
|
+
*/
|
|
37
|
+
destinations?: (env: E) => readonly (Destination | null | undefined)[];
|
|
38
|
+
/** 1つの封筒の出来事の上限(既定 200) */
|
|
39
|
+
maxEvents?: number;
|
|
40
|
+
/** 1つの出来事の引数の数の上限(既定 32)。超えた出来事は外す(rejected に載る)。Infinity で数えない */
|
|
41
|
+
maxProps?: number;
|
|
42
|
+
/** 引数の名前と文字列の値の長さの上限(既定 100 字)。超えた出来事は外す(rejected に載る)。Infinity で数えない */
|
|
43
|
+
maxText?: number;
|
|
44
|
+
/** 本文の上限のバイト数(既定 256KB) */
|
|
45
|
+
maxBytes?: number;
|
|
46
|
+
/**
|
|
47
|
+
* 1つの端末(install_id)が1時間に書いてよい行の数。無ければ数えない。
|
|
48
|
+
* 書く表のうち、この1時間に受けた(received_at)その端末の行を数え、超えた分は書かずに 200 で返す(BatchSink に送り直させない)。
|
|
49
|
+
* 同じ表に書くほかの受け口の行も数える。表は install_id と received_at を書くこと
|
|
50
|
+
*/
|
|
51
|
+
hourlyLimit?: number;
|
|
52
|
+
/** install_id の大小(envelope.ts の ParseOptions.installIdCase)。既定は lower。前からある表に大文字の行があるアプリは keep */
|
|
53
|
+
installIdCase?: "lower" | "keep";
|
|
54
|
+
/** app_version の形。渡すと合わない封筒を 400 で断る(例 NUMERIC_APP_VERSION)。既定は照らさない */
|
|
55
|
+
appVersion?: RegExp;
|
|
56
|
+
now?: () => number;
|
|
57
|
+
fetch?: typeof fetch;
|
|
58
|
+
}
|
|
59
|
+
/** onStored に渡すもの */
|
|
60
|
+
export interface StoredContext<E> {
|
|
61
|
+
/** 書いた封筒。uid は書いた値(uid を渡したならその値) */
|
|
62
|
+
envelope: Envelope;
|
|
63
|
+
env: E;
|
|
64
|
+
receivedAt: number;
|
|
65
|
+
}
|
|
66
|
+
export interface ReceiveResult {
|
|
67
|
+
accepted: number;
|
|
68
|
+
duplicates: number;
|
|
69
|
+
rejected: Rejected[];
|
|
70
|
+
marked: Marked[];
|
|
71
|
+
/** どれかの転送先に渡した出来事の数 */
|
|
72
|
+
forwarded: number;
|
|
73
|
+
/** 1時間あたりの上限(hourlyLimit)を超えて書かなかった出来事の数 */
|
|
74
|
+
limited: number;
|
|
75
|
+
}
|
|
76
|
+
/** 要求ごとの値。appEventsHandler は Hono の c.var から作る */
|
|
77
|
+
export interface RequestContext {
|
|
78
|
+
/** どのトークンで来たか(@appgrowstack/app-auth の auth_kind)。表の columns.auth_kind か extra の RowContext.authKind で書く */
|
|
79
|
+
authKind?: string | null;
|
|
80
|
+
/**
|
|
81
|
+
* 認証のミドルウェアが確かめた人(@appgrowstack/app-auth の authenticate が c.set する userId)。
|
|
82
|
+
* あれば封筒の uid でなくこれを書く(opts.uid を渡したときは opts.uid が勝つ)
|
|
83
|
+
*/
|
|
84
|
+
userId?: string;
|
|
85
|
+
}
|
|
86
|
+
export declare function receiveAppEvents<E>(req: Request, env: E, waitUntil: (p: Promise<unknown>) => void, opts: AppEventsOptions<E>, request?: RequestContext): Promise<Response>;
|
|
87
|
+
/** Hono の Context のうち、使う所だけ */
|
|
88
|
+
export interface HonoLikeContext<E> {
|
|
89
|
+
req: {
|
|
90
|
+
raw: Request;
|
|
91
|
+
};
|
|
92
|
+
env: E;
|
|
93
|
+
executionCtx: {
|
|
94
|
+
waitUntil(p: Promise<unknown>): void;
|
|
95
|
+
};
|
|
96
|
+
/** Hono の c.var。auth_kind と userId(@appgrowstack/app-auth の authenticate が入れる)を読む。無くてよい */
|
|
97
|
+
var?: unknown;
|
|
98
|
+
}
|
|
99
|
+
/**
|
|
100
|
+
* Hono のハンドラ。app.post("/v1/events", appEventsHandler({ app: "kotoakari", db: (env) => env.DB }))。
|
|
101
|
+
* 認証(@appgrowstack/app-auth の authenticate など)を掛けるなら、Hono のミドルウェアでこの前に置く。
|
|
102
|
+
* authenticate が c.set した auth_kind は、表の columns に auth_kind を書いたときその列に書く。
|
|
103
|
+
* authenticate が c.set した userId があれば、封筒の uid でなくその人を uid に書く(別の人の uid を名乗って書けないように)
|
|
104
|
+
*/
|
|
105
|
+
export declare function appEventsHandler<E>(opts: AppEventsOptions<E>): (c: HonoLikeContext<E>) => Promise<Response>;
|