blubblub-the-machine 0.0.0-stage → 0.1.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,50 @@
1
- # Temporary Holding Version
1
+ # blubblub-the-machine
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
+ The Machine's client for Blub Blub apps. Onboarding questions come first; cross-promo follows in
4
+ the same package. At the start of onboarding it asks The Machine for
5
+ up to three extra questions; the app shows them in its own screens and hands the answers back.
6
+
7
+ - **Onboarding never waits.** `start` resolves within 1.5 s, and any error, timeout or refusal is
8
+ "no questions". Nothing in the package throws.
9
+ - **Answers are never lost to a bad connection.** They, and the reports of which questions were shown,
10
+ are queued in storage and retried on every `flush` for 7 days.
11
+ - **The app key identifies the app; it is not a secret.** It ships inside the app.
12
+
13
+ ## Use (Capacitor)
14
+
15
+ ```ts
16
+ import { createOnboarding } from "blubblub-the-machine";
17
+ import { capacitorStorage } from "blubblub-the-machine/capacitor";
18
+ import { Preferences } from "@capacitor/preferences";
19
+
20
+ const machine = createOnboarding({
21
+ appKey: "<the app's key from The Machine>",
22
+ platform: "ios",
23
+ storage: capacitorStorage(Preferences),
24
+ });
25
+
26
+ // When the app starts and each time it comes back to the foreground:
27
+ void machine.flush();
28
+
29
+ // When onboarding begins:
30
+ const { sessionId, questions } = await machine.start({
31
+ locale: "en-US",
32
+ identifiers: { idfv, idfa, revenuecatAppUserId, posthogDistinctId, appUserId },
33
+ ownQuestions: ["babyBirthDate", "olderSiblings"], // the app's own questions, as it names their answers
34
+ });
35
+
36
+ // Show each question in the app's screens. As each one appears, without waiting:
37
+ if (sessionId) void machine.shown(sessionId, [questions[0].id]);
38
+ // Then the answers, also without waiting:
39
+ if (sessionId) void machine.answer(sessionId, [{ questionId: questions[0].id, value: "a" }, { questionId: questions[1].id, skipped: true }]);
40
+ ```
41
+
42
+ - `idfv` is required; without it `start` returns no questions. Send `idfa` only when the user allowed
43
+ tracking, and `email` only when the app already has it.
44
+ - A question's `type` is `single` or `multi` (answer with option `value`s), `number`, `date`
45
+ (`YYYY-MM-DD`) or `text`. `text` and option labels are already in the requested locale.
46
+ - Call `shown` when a question is actually on screen, not when it arrives: The Machine counts how many
47
+ of the questions it gives are seen, answered and skipped (from 0.1.1).
48
+ - `onError` (optional) is called with every failure, for the app's own logging.
49
+
50
+ The API contract is `docs/standards/SDK_API.md` in The Machine's repository.
@@ -0,0 +1,23 @@
1
+ import type { Storage } from "./index";
2
+ /**
3
+ * Capacitor glue. The plugin is passed in rather than imported, so the package has no native
4
+ * dependency and works with whichever Capacitor version the app ships:
5
+ *
6
+ * import { Preferences } from "@capacitor/preferences";
7
+ * createOnboarding({ appKey, platform: "ios", storage: capacitorStorage(Preferences) });
8
+ *
9
+ * Identifiers come from the app (Yummy Bites: its DeviceIdsBridge for the IDFV and, once tracking is
10
+ * allowed, the IDFA), since each app already reads them its own way.
11
+ */
12
+ export interface PreferencesPlugin {
13
+ get(options: {
14
+ key: string;
15
+ }): Promise<{
16
+ value: string | null;
17
+ }>;
18
+ set(options: {
19
+ key: string;
20
+ value: string;
21
+ }): Promise<void>;
22
+ }
23
+ export declare function capacitorStorage(preferences: PreferencesPlugin): Storage;
@@ -0,0 +1,6 @@
1
+ export function capacitorStorage(preferences) {
2
+ return {
3
+ get: async (key) => (await preferences.get({ key })).value,
4
+ set: (key, value) => preferences.set({ key, value }),
5
+ };
6
+ }
@@ -0,0 +1,91 @@
1
+ /**
2
+ * The Machine's onboarding SDK client: asks for up to three extra onboarding questions and sends the
3
+ * answers back (contract: docs/standards/SDK_API.md in the-machine2).
4
+ *
5
+ * Two promises hold for the app: `start` never throws and never takes longer than `timeoutMs`
6
+ * (any error, timeout or non-200 answer is "no questions"), and `answer` and `shown` never throw
7
+ * either: they are queued in `storage` and sent in the background, retried on the next `flush` while
8
+ * their session is open (7 days). An app calls `shown` as each question appears on screen, and
9
+ * `flush` when it starts and when it returns to the foreground.
10
+ */
11
+ export declare const SDK_VERSION = "0.1.1";
12
+ export declare const DEFAULT_BASE_URL = "https://the-machine-cy38u.ondigitalocean.app";
13
+ export declare const START_TIMEOUT_MS = 1500;
14
+ /** How long the server accepts answers for a session; older queued answers are dropped. */
15
+ export declare const SESSION_MS: number;
16
+ export type Platform = "ios" | "android";
17
+ /** Identifiers as the app has them. The ad id only when the user allowed tracking. */
18
+ export interface Identifiers {
19
+ idfv?: string | null;
20
+ idfa?: string | null;
21
+ revenuecatAppUserId?: string | null;
22
+ posthogDistinctId?: string | null;
23
+ appUserId?: string | null;
24
+ email?: string | null;
25
+ }
26
+ export interface Attribution {
27
+ network?: string;
28
+ campaign?: string;
29
+ adset?: string;
30
+ creative?: string;
31
+ }
32
+ export interface StartInput {
33
+ locale: string;
34
+ identifiers: Identifiers;
35
+ /** The app's own questions, named as the app stores their answers (`babyBirthDate`, …). */
36
+ ownQuestions?: string[];
37
+ attribution?: Attribution;
38
+ }
39
+ export type QuestionType = "single" | "multi" | "number" | "date" | "text";
40
+ export interface Question {
41
+ id: string;
42
+ key: string;
43
+ type: QuestionType;
44
+ text: string;
45
+ options?: {
46
+ value: string;
47
+ label: string;
48
+ }[];
49
+ }
50
+ /** `sessionId` is null when there are no questions to ask (including every failure). */
51
+ export interface OnboardingSession {
52
+ sessionId: string | null;
53
+ questions: Question[];
54
+ }
55
+ /** A value: an option's value (`single`), several (`multi`), a number, a `YYYY-MM-DD` day or text. */
56
+ export type Answer = {
57
+ questionId: string;
58
+ value: string | number | string[];
59
+ } | {
60
+ questionId: string;
61
+ skipped: true;
62
+ };
63
+ /** Where queued answers survive an app restart. Capacitor: `capacitorStorage` from `/capacitor`. */
64
+ export interface Storage {
65
+ get(key: string): Promise<string | null>;
66
+ set(key: string, value: string): Promise<void>;
67
+ }
68
+ export interface OnboardingOptions {
69
+ appKey: string;
70
+ platform: Platform;
71
+ baseUrl?: string;
72
+ timeoutMs?: number;
73
+ /** Without it answers are queued in memory only and lost when the app closes. */
74
+ storage?: Storage;
75
+ /** Told about failures, for the app's own logging; never needed for correctness. */
76
+ onError?: (where: "start" | "answers" | "storage", error: unknown) => void;
77
+ fetch?: typeof fetch;
78
+ now?: () => number;
79
+ }
80
+ export interface Onboarding {
81
+ start(input: StartInput): Promise<OnboardingSession>;
82
+ answer(sessionId: string, answers: Answer[]): Promise<void>;
83
+ /** Report questions the app has put on screen, by id; call it as each one appears. */
84
+ shown(sessionId: string, questionIds: string[]): Promise<void>;
85
+ flush(): Promise<void>;
86
+ }
87
+ /** Empty values and an all-zero ad id (tracking not allowed yet) are left out, as the server would. */
88
+ export declare function cleanIdentifiers(ids: Identifiers): Record<string, string>;
89
+ /** The questions of a 200 answer that the app can render; anything malformed is dropped, not thrown. */
90
+ export declare function readSession(body: unknown): OnboardingSession;
91
+ export declare function createOnboarding(options: OnboardingOptions): Onboarding;
package/dist/index.js ADDED
@@ -0,0 +1,200 @@
1
+ /**
2
+ * The Machine's onboarding SDK client: asks for up to three extra onboarding questions and sends the
3
+ * answers back (contract: docs/standards/SDK_API.md in the-machine2).
4
+ *
5
+ * Two promises hold for the app: `start` never throws and never takes longer than `timeoutMs`
6
+ * (any error, timeout or non-200 answer is "no questions"), and `answer` and `shown` never throw
7
+ * either: they are queued in `storage` and sent in the background, retried on the next `flush` while
8
+ * their session is open (7 days). An app calls `shown` as each question appears on screen, and
9
+ * `flush` when it starts and when it returns to the foreground.
10
+ */
11
+ export const SDK_VERSION = "0.1.1";
12
+ export const DEFAULT_BASE_URL = "https://the-machine-cy38u.ondigitalocean.app";
13
+ export const START_TIMEOUT_MS = 1500;
14
+ /** How long the server accepts answers for a session; older queued answers are dropped. */
15
+ export const SESSION_MS = 7 * 24 * 3600000;
16
+ const ANSWERS_TIMEOUT_MS = 10000;
17
+ const QUEUE_KEY = "machine-onboarding:answers:v1";
18
+ const ZERO_UUID = "00000000-0000-0000-0000-000000000000";
19
+ const NO_QUESTIONS = { sessionId: null, questions: [] };
20
+ const TYPES = ["single", "multi", "number", "date", "text"];
21
+ function memoryStorage() {
22
+ const m = new Map();
23
+ return { get: async (k) => m.get(k) ?? null, set: async (k, v) => void m.set(k, v) };
24
+ }
25
+ /** Empty values and an all-zero ad id (tracking not allowed yet) are left out, as the server would. */
26
+ export function cleanIdentifiers(ids) {
27
+ const out = {};
28
+ for (const [k, v] of Object.entries(ids)) {
29
+ const s = typeof v === "string" ? v.trim() : "";
30
+ if (!s || (k === "idfa" && s === ZERO_UUID))
31
+ continue;
32
+ out[k] = s;
33
+ }
34
+ return out;
35
+ }
36
+ /** The questions of a 200 answer that the app can render; anything malformed is dropped, not thrown. */
37
+ export function readSession(body) {
38
+ if (!body || typeof body !== "object")
39
+ return NO_QUESTIONS;
40
+ const { sessionId, questions } = body;
41
+ if (typeof sessionId !== "string" || !Array.isArray(questions))
42
+ return NO_QUESTIONS;
43
+ const valid = questions.filter((q) => {
44
+ if (!q || typeof q !== "object")
45
+ return false;
46
+ const { id, key, type, text, options } = q;
47
+ if (typeof id !== "string" || typeof key !== "string" || typeof text !== "string" || typeof type !== "string" || !TYPES.includes(type))
48
+ return false;
49
+ const choice = type === "single" || type === "multi";
50
+ if (!choice)
51
+ return options === undefined;
52
+ return Array.isArray(options) && options.length > 0 && options.every((o) => o && typeof o.value === "string" && typeof o.label === "string");
53
+ });
54
+ return valid.length ? { sessionId, questions: valid } : NO_QUESTIONS;
55
+ }
56
+ export function createOnboarding(options) {
57
+ const baseUrl = (options.baseUrl ?? DEFAULT_BASE_URL).replace(/\/+$/, "");
58
+ const timeoutMs = options.timeoutMs ?? START_TIMEOUT_MS;
59
+ const storage = options.storage ?? memoryStorage();
60
+ const doFetch = options.fetch ?? ((...a) => fetch(...a));
61
+ const now = options.now ?? Date.now;
62
+ const report = (where, e) => {
63
+ try {
64
+ options.onError?.(where, e);
65
+ }
66
+ catch {
67
+ // the app's logger must not break onboarding
68
+ }
69
+ };
70
+ /** A POST that gives up after `ms`, also where the fetch ignores the abort signal. */
71
+ async function post(path, body, ms) {
72
+ const abort = typeof AbortController === "function" ? new AbortController() : null;
73
+ let timer;
74
+ const timeout = new Promise((_, reject) => {
75
+ timer = setTimeout(() => {
76
+ abort?.abort();
77
+ reject(new Error(`timed out after ${ms} ms`));
78
+ }, ms);
79
+ });
80
+ try {
81
+ return await Promise.race([
82
+ doFetch(`${baseUrl}${path}`, {
83
+ method: "POST",
84
+ headers: { "content-type": "application/json", "x-machine-app-key": options.appKey },
85
+ body: JSON.stringify(body),
86
+ signal: abort?.signal,
87
+ }),
88
+ timeout,
89
+ ]);
90
+ }
91
+ finally {
92
+ clearTimeout(timer);
93
+ }
94
+ }
95
+ // Every read-modify-write of the queue runs one after another, so a flush and an answer never
96
+ // overwrite each other's change.
97
+ let lock = Promise.resolve();
98
+ function locked(fn) {
99
+ const run = lock.then(fn, fn);
100
+ lock = run.catch(() => undefined);
101
+ return run;
102
+ }
103
+ async function readQueue() {
104
+ try {
105
+ const raw = await storage.get(QUEUE_KEY);
106
+ const q = raw ? JSON.parse(raw) : [];
107
+ return Array.isArray(q) ? q : [];
108
+ }
109
+ catch (e) {
110
+ report("storage", e);
111
+ return [];
112
+ }
113
+ }
114
+ async function writeQueue(q) {
115
+ try {
116
+ await storage.set(QUEUE_KEY, JSON.stringify(q));
117
+ }
118
+ catch (e) {
119
+ report("storage", e);
120
+ }
121
+ }
122
+ async function start(input) {
123
+ try {
124
+ const identifiers = cleanIdentifiers(input.identifiers);
125
+ if (!identifiers["idfv"])
126
+ return NO_QUESTIONS; // the contract needs the vendor id (iOS only for now)
127
+ const res = await post("/api/sdk/v1/onboarding/start", { sdkVersion: SDK_VERSION, platform: options.platform, locale: input.locale, identifiers, ownQuestions: input.ownQuestions ?? [], attribution: input.attribution }, timeoutMs);
128
+ if (res.status !== 200) {
129
+ report("start", new Error(`HTTP ${res.status}`));
130
+ return NO_QUESTIONS;
131
+ }
132
+ return readSession(await res.json());
133
+ }
134
+ catch (e) {
135
+ report("start", e);
136
+ return NO_QUESTIONS;
137
+ }
138
+ }
139
+ async function enqueue(item) {
140
+ await locked(async () => {
141
+ const q = await readQueue();
142
+ q.push({ ...item, queuedAt: now() });
143
+ await writeQueue(q);
144
+ });
145
+ await flush();
146
+ }
147
+ async function answer(sessionId, answers) {
148
+ if (!sessionId || !answers.length)
149
+ return;
150
+ await enqueue({ sessionId, answers });
151
+ }
152
+ async function shown(sessionId, questionIds) {
153
+ const ids = [...new Set(questionIds.filter((id) => typeof id === "string" && id))];
154
+ if (!sessionId || !ids.length)
155
+ return;
156
+ await enqueue({ sessionId, answers: [], shown: ids });
157
+ }
158
+ async function send() {
159
+ const keep = [];
160
+ for (const item of await readQueue()) {
161
+ if (now() - item.queuedAt > SESSION_MS)
162
+ continue; // the session is closed on the server
163
+ try {
164
+ const body = { sessionId: item.sessionId, answers: item.answers ?? [], ...(item.shown?.length ? { shown: item.shown } : {}) };
165
+ const res = await post("/api/sdk/v1/onboarding/answers", body, ANSWERS_TIMEOUT_MS);
166
+ if (res.status === 200)
167
+ continue;
168
+ report("answers", new Error(`HTTP ${res.status}`));
169
+ // 400, 401 and 404 will not change on a retry; 429 and 5xx may.
170
+ if (res.status === 429 || res.status >= 500)
171
+ keep.push(item);
172
+ }
173
+ catch (e) {
174
+ report("answers", e);
175
+ keep.push(item);
176
+ }
177
+ }
178
+ await writeQueue(keep);
179
+ }
180
+ // One flush at a time; a flush asked for while one runs makes it go round once more, so answers
181
+ // queued meanwhile are not left until the next app start.
182
+ let flushing = null;
183
+ let again = false;
184
+ function flush() {
185
+ if (flushing) {
186
+ again = true;
187
+ return flushing;
188
+ }
189
+ flushing = (async () => {
190
+ do {
191
+ again = false;
192
+ await locked(send);
193
+ } while (again);
194
+ })().finally(() => {
195
+ flushing = null;
196
+ });
197
+ return flushing;
198
+ }
199
+ return { start, answer, shown, flush };
200
+ }
package/package.json CHANGED
@@ -1,6 +1,35 @@
1
1
  {
2
2
  "name": "blubblub-the-machine",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.1",
4
+ "description": "The Machine's client for Blub Blub apps: extra onboarding questions now, cross-promo next.",
5
+ "type": "module",
6
+ "main": "./dist/index.js",
7
+ "types": "./dist/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./dist/index.d.ts",
11
+ "import": "./dist/index.js"
12
+ },
13
+ "./capacitor": {
14
+ "types": "./dist/capacitor.d.ts",
15
+ "import": "./dist/capacitor.js"
16
+ }
17
+ },
18
+ "typesVersions": {
19
+ "*": {
20
+ "capacitor": [
21
+ "./dist/capacitor.d.ts"
22
+ ]
23
+ }
24
+ },
25
+ "files": [
26
+ "dist",
27
+ "README.md"
28
+ ],
29
+ "sideEffects": false,
30
+ "scripts": {
31
+ "build": "tsc -p tsconfig.json",
32
+ "prepublishOnly": "npm run build"
33
+ },
34
+ "license": "UNLICENSED"
35
+ }