@koolbase/react-native 9.2.0 → 10.0.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.
Files changed (69) hide show
  1. package/CHANGELOG.md +1342 -0
  2. package/README.md +403 -568
  3. package/dist/{auth-storage.d.ts → cjs/auth-storage.d.ts} +1 -1
  4. package/dist/cjs/index.d.ts +19 -0
  5. package/dist/cjs/index.js +125 -0
  6. package/dist/cjs/package.json +3 -0
  7. package/dist/cjs/platform.d.ts +2 -0
  8. package/dist/cjs/platform.js +43 -0
  9. package/dist/esm/auth-storage.d.ts +26 -0
  10. package/dist/esm/auth-storage.js +100 -0
  11. package/dist/esm/index.d.ts +19 -0
  12. package/dist/esm/index.js +106 -0
  13. package/dist/esm/package.json +3 -0
  14. package/dist/esm/platform.d.ts +2 -0
  15. package/dist/esm/platform.js +37 -0
  16. package/package.json +30 -30
  17. package/dist/analytics.d.ts +0 -24
  18. package/dist/analytics.js +0 -114
  19. package/dist/apple-auth.d.ts +0 -22
  20. package/dist/apple-auth.js +0 -74
  21. package/dist/auth-errors.d.ts +0 -117
  22. package/dist/auth-errors.js +0 -250
  23. package/dist/auth.d.ts +0 -213
  24. package/dist/auth.js +0 -810
  25. package/dist/cache-store.d.ts +0 -50
  26. package/dist/cache-store.js +0 -197
  27. package/dist/code-push.d.ts +0 -59
  28. package/dist/code-push.js +0 -255
  29. package/dist/conflict.d.ts +0 -80
  30. package/dist/conflict.js +0 -84
  31. package/dist/database-errors.d.ts +0 -101
  32. package/dist/database-errors.js +0 -200
  33. package/dist/database.d.ts +0 -298
  34. package/dist/database.js +0 -852
  35. package/dist/device-id.d.ts +0 -1
  36. package/dist/device-id.js +0 -60
  37. package/dist/device-metadata.d.ts +0 -36
  38. package/dist/device-metadata.js +0 -102
  39. package/dist/errors.d.ts +0 -64
  40. package/dist/errors.js +0 -85
  41. package/dist/flags.d.ts +0 -15
  42. package/dist/flags.js +0 -76
  43. package/dist/function-errors.d.ts +0 -51
  44. package/dist/function-errors.js +0 -103
  45. package/dist/functions.d.ts +0 -15
  46. package/dist/functions.js +0 -83
  47. package/dist/index.d.ts +0 -49
  48. package/dist/index.js +0 -204
  49. package/dist/logic-engine.d.ts +0 -17
  50. package/dist/logic-engine.js +0 -193
  51. package/dist/messaging.d.ts +0 -13
  52. package/dist/messaging.js +0 -36
  53. package/dist/offline-state.d.ts +0 -97
  54. package/dist/offline-state.js +0 -200
  55. package/dist/pending-write.d.ts +0 -47
  56. package/dist/pending-write.js +0 -22
  57. package/dist/realtime.d.ts +0 -44
  58. package/dist/realtime.js +0 -195
  59. package/dist/record.d.ts +0 -2
  60. package/dist/record.js +0 -23
  61. package/dist/storage-errors.d.ts +0 -163
  62. package/dist/storage-errors.js +0 -253
  63. package/dist/storage.d.ts +0 -198
  64. package/dist/storage.js +0 -451
  65. package/dist/sync-engine.d.ts +0 -30
  66. package/dist/sync-engine.js +0 -290
  67. package/dist/types.d.ts +0 -487
  68. package/dist/types.js +0 -40
  69. /package/dist/{auth-storage.js → cjs/auth-storage.js} +0 -0
package/dist/functions.js DELETED
@@ -1,83 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.KoolbaseFunctions = void 0;
4
- const function_errors_1 = require("./function-errors");
5
- const errors_1 = require("./errors");
6
- const types_1 = require("./types");
7
- class KoolbaseFunctions {
8
- constructor(config, getUserAccessToken, onSessionExpired) {
9
- this.config = config;
10
- this.onSessionExpired = onSessionExpired;
11
- this.getUserAccessToken = getUserAccessToken;
12
- }
13
- // ─── Deploy ────────────────────────────────────────────────────────────────
14
- async deploy(options) {
15
- const runtime = options.runtime ?? types_1.FunctionRuntime.Deno;
16
- const res = await fetch(`${this.config.baseUrl}/v1/sdk/functions/deploy`, {
17
- method: 'POST',
18
- headers: {
19
- 'Content-Type': 'application/json',
20
- 'x-api-key': this.config.publicKey,
21
- },
22
- body: JSON.stringify({
23
- name: options.name,
24
- code: options.code,
25
- runtime,
26
- timeout_ms: options.timeoutMs ?? 10000,
27
- }),
28
- });
29
- const data = await res.json().catch(() => null);
30
- if (!res.ok) {
31
- const message = data?.error ??
32
- 'Function deploy failed';
33
- const err = (0, function_errors_1.functionInvokeError)(res.status, message);
34
- if (err instanceof errors_1.KoolbaseUnauthenticatedError) {
35
- await this.onSessionExpired?.();
36
- }
37
- throw err;
38
- }
39
- const d = data;
40
- return {
41
- id: d.id,
42
- name: d.name,
43
- runtime: d.runtime,
44
- version: d.version,
45
- isActive: d.is_active,
46
- timeoutMs: d.timeout_ms,
47
- lastDeployedAt: d.last_deployed_at,
48
- };
49
- }
50
- // ─── Invoke ────────────────────────────────────────────────────────────────
51
- async invoke(name, body) {
52
- const headers = {
53
- 'Content-Type': 'application/json',
54
- 'x-api-key': this.config.publicKey,
55
- };
56
- const userToken = await this.getUserAccessToken?.();
57
- if (userToken) {
58
- headers['Authorization'] = `Bearer ${userToken}`;
59
- }
60
- const res = await fetch(`${this.config.baseUrl}/v1/sdk/functions/${name}`, {
61
- method: 'POST',
62
- headers,
63
- body: JSON.stringify({ body: body ?? {} }),
64
- });
65
- const data = await res.json().catch(() => null);
66
- const success = res.status >= 200 && res.status < 300;
67
- if (!success) {
68
- const message = data?.error ??
69
- 'Function invocation failed';
70
- const err = (0, function_errors_1.functionInvokeError)(res.status, message);
71
- if (err instanceof errors_1.KoolbaseUnauthenticatedError) {
72
- await this.onSessionExpired?.();
73
- }
74
- throw err;
75
- }
76
- return {
77
- statusCode: res.status,
78
- data: data,
79
- success,
80
- };
81
- }
82
- }
83
- exports.KoolbaseFunctions = KoolbaseFunctions;
package/dist/index.d.ts DELETED
@@ -1,49 +0,0 @@
1
- import { KoolbaseAuth } from './auth';
2
- import { KoolbaseCodePush } from './code-push';
3
- import { KoolbaseAnalytics } from './analytics';
4
- import { KoolbaseMessaging } from './messaging';
5
- export { KoolbaseMessaging } from './messaging';
6
- export { KoolbaseAppleAuth } from './apple-auth';
7
- export type { RegisterTokenOptions } from './messaging';
8
- import { FlowResult } from './logic-engine';
9
- export { KoolbaseAnalytics } from './analytics';
10
- export type { FlowResult } from './logic-engine';
11
- export { KoolbaseCodePush } from './code-push';
12
- export type { BundleManifest, BundlePayload } from './code-push';
13
- import { KoolbaseDatabase } from './database';
14
- import { KoolbaseFlags } from './flags';
15
- import { KoolbaseFunctions } from './functions';
16
- import { KoolbaseRealtime } from './realtime';
17
- import { KoolbaseStorage } from './storage';
18
- import { KoolbaseConfig, VersionCheckResult } from './types';
19
- export * from './types';
20
- export * from './errors';
21
- export * from './conflict';
22
- export * from './pending-write';
23
- export * from './function-errors';
24
- export * from './auth-errors';
25
- export * from './database-errors';
26
- export * from './storage-errors';
27
- export { KoolbaseAuth, KoolbaseDatabase, KoolbaseFlags, KoolbaseFunctions, KoolbaseRealtime, KoolbaseStorage };
28
- export declare const Koolbase: {
29
- initialize(config: KoolbaseConfig): Promise<void>;
30
- readonly auth: KoolbaseAuth;
31
- readonly db: KoolbaseDatabase;
32
- readonly storage: KoolbaseStorage;
33
- readonly realtime: KoolbaseRealtime;
34
- readonly functions: KoolbaseFunctions;
35
- isEnabled(key: string): boolean;
36
- configString(key: string, fallback?: string): string;
37
- configNumber(key: string, fallback?: number): number;
38
- configBool(key: string, fallback?: boolean): boolean;
39
- readonly codePush: KoolbaseCodePush;
40
- readonly analytics: KoolbaseAnalytics;
41
- executeFlow(flowId: string, context?: Record<string, unknown>): FlowResult;
42
- readonly messaging: KoolbaseMessaging;
43
- checkVersion(currentVersion: string): VersionCheckResult;
44
- };
45
- export { koolbaseSdkVersion } from './device-metadata';
46
- export { RestoreResult } from './types';
47
- export type { AuthStateListener, FetchLike, KoolbaseAuthStorage } from './types';
48
- export { SecureAuthStorage } from './auth-storage';
49
- export { KoolbaseAuthError, InvalidCredentialsError, EmailAlreadyInUseError, UserDisabledError, WeakPasswordError, SessionExpiredError, TokenRevokedError, AccountLockedError, UnlockTokenInvalidError, RateLimitError, NetworkError, InvalidPhoneNumberError, OtpExpiredError, OtpInvalidError, OtpMaxAttemptsError, OtpRateLimitError, PhoneAlreadyLinkedError, SmsConfigMissingError, } from './auth-errors';
package/dist/index.js DELETED
@@ -1,204 +0,0 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
- for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
- };
16
- Object.defineProperty(exports, "__esModule", { value: true });
17
- exports.SmsConfigMissingError = exports.PhoneAlreadyLinkedError = exports.OtpRateLimitError = exports.OtpMaxAttemptsError = exports.OtpInvalidError = exports.OtpExpiredError = exports.InvalidPhoneNumberError = exports.NetworkError = exports.RateLimitError = exports.UnlockTokenInvalidError = exports.AccountLockedError = exports.TokenRevokedError = exports.SessionExpiredError = exports.WeakPasswordError = exports.UserDisabledError = exports.EmailAlreadyInUseError = exports.InvalidCredentialsError = exports.KoolbaseAuthError = exports.SecureAuthStorage = exports.RestoreResult = exports.koolbaseSdkVersion = exports.Koolbase = exports.KoolbaseStorage = exports.KoolbaseRealtime = exports.KoolbaseFunctions = exports.KoolbaseFlags = exports.KoolbaseDatabase = exports.KoolbaseAuth = exports.KoolbaseCodePush = exports.KoolbaseAnalytics = exports.KoolbaseAppleAuth = exports.KoolbaseMessaging = void 0;
18
- const auth_1 = require("./auth");
19
- Object.defineProperty(exports, "KoolbaseAuth", { enumerable: true, get: function () { return auth_1.KoolbaseAuth; } });
20
- const code_push_1 = require("./code-push");
21
- const analytics_1 = require("./analytics");
22
- const messaging_1 = require("./messaging");
23
- var messaging_2 = require("./messaging");
24
- Object.defineProperty(exports, "KoolbaseMessaging", { enumerable: true, get: function () { return messaging_2.KoolbaseMessaging; } });
25
- var apple_auth_1 = require("./apple-auth");
26
- Object.defineProperty(exports, "KoolbaseAppleAuth", { enumerable: true, get: function () { return apple_auth_1.KoolbaseAppleAuth; } });
27
- const logic_engine_1 = require("./logic-engine");
28
- var analytics_2 = require("./analytics");
29
- Object.defineProperty(exports, "KoolbaseAnalytics", { enumerable: true, get: function () { return analytics_2.KoolbaseAnalytics; } });
30
- var code_push_2 = require("./code-push");
31
- Object.defineProperty(exports, "KoolbaseCodePush", { enumerable: true, get: function () { return code_push_2.KoolbaseCodePush; } });
32
- const database_1 = require("./database");
33
- Object.defineProperty(exports, "KoolbaseDatabase", { enumerable: true, get: function () { return database_1.KoolbaseDatabase; } });
34
- const flags_1 = require("./flags");
35
- Object.defineProperty(exports, "KoolbaseFlags", { enumerable: true, get: function () { return flags_1.KoolbaseFlags; } });
36
- const functions_1 = require("./functions");
37
- Object.defineProperty(exports, "KoolbaseFunctions", { enumerable: true, get: function () { return functions_1.KoolbaseFunctions; } });
38
- const realtime_1 = require("./realtime");
39
- Object.defineProperty(exports, "KoolbaseRealtime", { enumerable: true, get: function () { return realtime_1.KoolbaseRealtime; } });
40
- const storage_1 = require("./storage");
41
- Object.defineProperty(exports, "KoolbaseStorage", { enumerable: true, get: function () { return storage_1.KoolbaseStorage; } });
42
- const device_id_1 = require("./device-id");
43
- __exportStar(require("./types"), exports);
44
- // The root, and the authentication failure any surface can raise. Listed
45
- // first: an application catching broadly needs these more than it needs any
46
- // single subsystem's types.
47
- __exportStar(require("./errors"), exports);
48
- __exportStar(require("./conflict"), exports);
49
- __exportStar(require("./pending-write"), exports);
50
- __exportStar(require("./function-errors"), exports);
51
- __exportStar(require("./auth-errors"), exports);
52
- __exportStar(require("./database-errors"), exports);
53
- __exportStar(require("./storage-errors"), exports);
54
- let _auth = null;
55
- let _db = null;
56
- let _storage = null;
57
- let _realtime = null;
58
- let _functions = null;
59
- let _flags = null;
60
- let _codePush = null;
61
- let _analytics = null;
62
- let _messaging = null;
63
- const _logicEngine = new logic_engine_1.KoolbaseLogicEngine();
64
- let _initialized = false;
65
- function ensureInitialized() {
66
- if (!_initialized) {
67
- throw new Error('Koolbase not initialized. Call Koolbase.initialize() first.');
68
- }
69
- }
70
- exports.Koolbase = {
71
- async initialize(config) {
72
- if (_initialized)
73
- return;
74
- _auth = new auth_1.KoolbaseAuth(config);
75
- _db = new database_1.KoolbaseDatabase(config, () => _auth?.currentUser?.id ?? null, () => _auth?.validAccessToken() ?? Promise.resolve(null),
76
- // A session the server refuses is not a session. Clearing it here means an
77
- // app catching KoolbaseUnauthenticatedError is already signed out and can
78
- // route to login, rather than looping on a dead token.
79
- async () => { await _auth?.clearStoredSession(); });
80
- _storage = new storage_1.KoolbaseStorage(config, () => _auth?.validAccessToken() ?? Promise.resolve(null), async () => { await _auth?.clearStoredSession(); });
81
- _realtime = new realtime_1.KoolbaseRealtime(config, () => _auth?.validAccessToken() ?? Promise.resolve(null), () => _auth?.currentUser?.id ?? null);
82
- _functions = new functions_1.KoolbaseFunctions(config, () => _auth?.validAccessToken() ?? Promise.resolve(null), async () => { await _auth?.clearStoredSession(); });
83
- // One anonymous device id for the whole SDK — bucketing (flags), targeting
84
- // (code push), and registration keying (messaging) must all agree on it.
85
- const deviceId = await (0, device_id_1.getOrCreateDeviceId)();
86
- _flags = new flags_1.KoolbaseFlags(config, deviceId);
87
- _codePush = new code_push_1.KoolbaseCodePush(config, config.codePushChannel ?? 'stable');
88
- // Initialize code push — loads cached bundle then checks in background
89
- await _codePush.init({
90
- appVersion: '1.0.0', // override with your app version
91
- platform: 'react-native',
92
- deviceId,
93
- });
94
- // Initialize analytics
95
- if (config.analyticsEnabled !== false) {
96
- _analytics = new analytics_1.KoolbaseAnalytics(config);
97
- await _analytics.init(config.appVersion);
98
- }
99
- // Initialize messaging
100
- if (config.messagingEnabled !== false) {
101
- _messaging = new messaging_1.KoolbaseMessaging(config);
102
- _messaging.setDeviceId(deviceId);
103
- }
104
- _initialized = true;
105
- },
106
- get auth() {
107
- ensureInitialized();
108
- return _auth;
109
- },
110
- get db() {
111
- ensureInitialized();
112
- return _db;
113
- },
114
- get storage() {
115
- ensureInitialized();
116
- return _storage;
117
- },
118
- get realtime() {
119
- ensureInitialized();
120
- return _realtime;
121
- },
122
- get functions() {
123
- ensureInitialized();
124
- return _functions;
125
- },
126
- isEnabled(key) {
127
- ensureInitialized();
128
- // Bundle flag wins over remote flag
129
- const bundleFlag = _codePush?.getBundleFlag(key);
130
- if (bundleFlag !== undefined)
131
- return bundleFlag;
132
- return _flags.isEnabled(key);
133
- },
134
- configString(key, fallback = '') {
135
- ensureInitialized();
136
- const bundleVal = _codePush?.getBundleConfig(key);
137
- if (bundleVal !== undefined)
138
- return String(bundleVal);
139
- return _flags.getString(key, fallback);
140
- },
141
- configNumber(key, fallback = 0) {
142
- ensureInitialized();
143
- const bundleVal = _codePush?.getBundleConfig(key);
144
- if (bundleVal !== undefined)
145
- return typeof bundleVal === 'number' ? bundleVal : Number(bundleVal) || fallback;
146
- return _flags.getNumber(key, fallback);
147
- },
148
- configBool(key, fallback = false) {
149
- ensureInitialized();
150
- const bundleVal = _codePush?.getBundleConfig(key);
151
- if (bundleVal !== undefined)
152
- return typeof bundleVal === 'boolean' ? bundleVal : bundleVal === 'true';
153
- return _flags.getBool(key, fallback);
154
- },
155
- get codePush() {
156
- ensureInitialized();
157
- return _codePush;
158
- },
159
- get analytics() {
160
- ensureInitialized();
161
- return _analytics;
162
- },
163
- executeFlow(flowId, context) {
164
- ensureInitialized();
165
- const manifest = _codePush?.manifest;
166
- if (!manifest)
167
- return { hasEvent: false, args: {}, completed: true };
168
- return _logicEngine.execute(flowId, manifest.payload.flows ?? {}, context ?? {}, manifest.payload.config ?? {}, manifest.payload.flags ?? {});
169
- },
170
- get messaging() {
171
- ensureInitialized();
172
- return _messaging;
173
- },
174
- checkVersion(currentVersion) {
175
- ensureInitialized();
176
- return _flags.checkVersion(currentVersion);
177
- },
178
- };
179
- // v1.9.0 additions
180
- var device_metadata_1 = require("./device-metadata");
181
- Object.defineProperty(exports, "koolbaseSdkVersion", { enumerable: true, get: function () { return device_metadata_1.koolbaseSdkVersion; } });
182
- var types_1 = require("./types");
183
- Object.defineProperty(exports, "RestoreResult", { enumerable: true, get: function () { return types_1.RestoreResult; } });
184
- var auth_storage_1 = require("./auth-storage");
185
- Object.defineProperty(exports, "SecureAuthStorage", { enumerable: true, get: function () { return auth_storage_1.SecureAuthStorage; } });
186
- var auth_errors_1 = require("./auth-errors");
187
- Object.defineProperty(exports, "KoolbaseAuthError", { enumerable: true, get: function () { return auth_errors_1.KoolbaseAuthError; } });
188
- Object.defineProperty(exports, "InvalidCredentialsError", { enumerable: true, get: function () { return auth_errors_1.InvalidCredentialsError; } });
189
- Object.defineProperty(exports, "EmailAlreadyInUseError", { enumerable: true, get: function () { return auth_errors_1.EmailAlreadyInUseError; } });
190
- Object.defineProperty(exports, "UserDisabledError", { enumerable: true, get: function () { return auth_errors_1.UserDisabledError; } });
191
- Object.defineProperty(exports, "WeakPasswordError", { enumerable: true, get: function () { return auth_errors_1.WeakPasswordError; } });
192
- Object.defineProperty(exports, "SessionExpiredError", { enumerable: true, get: function () { return auth_errors_1.SessionExpiredError; } });
193
- Object.defineProperty(exports, "TokenRevokedError", { enumerable: true, get: function () { return auth_errors_1.TokenRevokedError; } });
194
- Object.defineProperty(exports, "AccountLockedError", { enumerable: true, get: function () { return auth_errors_1.AccountLockedError; } });
195
- Object.defineProperty(exports, "UnlockTokenInvalidError", { enumerable: true, get: function () { return auth_errors_1.UnlockTokenInvalidError; } });
196
- Object.defineProperty(exports, "RateLimitError", { enumerable: true, get: function () { return auth_errors_1.RateLimitError; } });
197
- Object.defineProperty(exports, "NetworkError", { enumerable: true, get: function () { return auth_errors_1.NetworkError; } });
198
- Object.defineProperty(exports, "InvalidPhoneNumberError", { enumerable: true, get: function () { return auth_errors_1.InvalidPhoneNumberError; } });
199
- Object.defineProperty(exports, "OtpExpiredError", { enumerable: true, get: function () { return auth_errors_1.OtpExpiredError; } });
200
- Object.defineProperty(exports, "OtpInvalidError", { enumerable: true, get: function () { return auth_errors_1.OtpInvalidError; } });
201
- Object.defineProperty(exports, "OtpMaxAttemptsError", { enumerable: true, get: function () { return auth_errors_1.OtpMaxAttemptsError; } });
202
- Object.defineProperty(exports, "OtpRateLimitError", { enumerable: true, get: function () { return auth_errors_1.OtpRateLimitError; } });
203
- Object.defineProperty(exports, "PhoneAlreadyLinkedError", { enumerable: true, get: function () { return auth_errors_1.PhoneAlreadyLinkedError; } });
204
- Object.defineProperty(exports, "SmsConfigMissingError", { enumerable: true, get: function () { return auth_errors_1.SmsConfigMissingError; } });
@@ -1,17 +0,0 @@
1
- export interface FlowResult {
2
- hasEvent: boolean;
3
- eventName?: string;
4
- args: Record<string, unknown>;
5
- completed: boolean;
6
- error?: string;
7
- }
8
- export declare class KoolbaseLogicEngine {
9
- execute(flowId: string, flows: Record<string, unknown>, context: Record<string, unknown>, config: Record<string, unknown>, flags: Record<string, boolean>): FlowResult;
10
- private evalNode;
11
- private evalIf;
12
- private evalSequence;
13
- private evalCondition;
14
- private resolve;
15
- private getNested;
16
- private setNested;
17
- }
@@ -1,193 +0,0 @@
1
- "use strict";
2
- // ─── Logic Engine ────────────────────────────────────────────────────────
3
- Object.defineProperty(exports, "__esModule", { value: true });
4
- exports.KoolbaseLogicEngine = void 0;
5
- class KoolbaseLogicEngine {
6
- // ─── Public API ───────────────────────────────────────────────────────────
7
- execute(flowId, flows, context, config, flags) {
8
- try {
9
- const flowJson = flows[flowId];
10
- if (!flowJson) {
11
- return { hasEvent: false, args: {}, completed: true };
12
- }
13
- const ctx = {
14
- context: { ...context },
15
- config,
16
- flags,
17
- };
18
- return this.evalNode(flowJson, ctx);
19
- }
20
- catch (e) {
21
- return {
22
- hasEvent: false,
23
- args: {},
24
- completed: false,
25
- error: String(e),
26
- };
27
- }
28
- }
29
- // ─── Node evaluation ──────────────────────────────────────────────────────
30
- evalNode(node, ctx) {
31
- switch (node.type) {
32
- case 'if':
33
- return this.evalIf(node, ctx);
34
- case 'sequence':
35
- return this.evalSequence(node, ctx);
36
- case 'event':
37
- return { hasEvent: true, eventName: node.name, args: node.args ?? {}, completed: true };
38
- case 'set':
39
- this.setNested(ctx.context, node.key, node.value);
40
- return { hasEvent: false, args: {}, completed: true };
41
- default:
42
- return { hasEvent: false, args: {}, completed: true };
43
- }
44
- }
45
- evalIf(node, ctx) {
46
- const result = this.evalCondition(node.condition, ctx);
47
- if (result)
48
- return this.evalNode(node.then, ctx);
49
- if (node.else)
50
- return this.evalNode(node.else, ctx);
51
- return { hasEvent: false, args: {}, completed: true };
52
- }
53
- evalSequence(node, ctx) {
54
- for (const step of node.steps) {
55
- const result = this.evalNode(step, ctx);
56
- if (result.hasEvent)
57
- return result;
58
- }
59
- return { hasEvent: false, args: {}, completed: true };
60
- }
61
- // ─── Condition evaluation ─────────────────────────────────────────────────
62
- evalCondition(condition, ctx) {
63
- switch (condition.op) {
64
- case 'eq': {
65
- const left = condition.left ? this.resolve(condition.left.from, ctx) : undefined;
66
- return String(left) === String(condition.right);
67
- }
68
- case 'neq': {
69
- const left = condition.left ? this.resolve(condition.left.from, ctx) : undefined;
70
- return String(left) !== String(condition.right);
71
- }
72
- case 'gt': {
73
- const left = Number(condition.left ? this.resolve(condition.left.from, ctx) : undefined);
74
- const right = Number(condition.right);
75
- return !isNaN(left) && !isNaN(right) && left > right;
76
- }
77
- case 'lt': {
78
- const left = Number(condition.left ? this.resolve(condition.left.from, ctx) : undefined);
79
- const right = Number(condition.right);
80
- return !isNaN(left) && !isNaN(right) && left < right;
81
- }
82
- case 'and':
83
- return (condition.conditions ?? []).every((c) => this.evalCondition(c, ctx));
84
- case 'or':
85
- return (condition.conditions ?? []).some((c) => this.evalCondition(c, ctx));
86
- case 'exists': {
87
- const val = condition.value ? this.resolve(condition.value.from, ctx) : undefined;
88
- return val !== null && val !== undefined;
89
- }
90
- case 'not_exists': {
91
- const val = condition.value ? this.resolve(condition.value.from, ctx) : undefined;
92
- return val === null || val === undefined;
93
- }
94
- case 'gte': {
95
- const left = Number(condition.left ? this.resolve(condition.left.from, ctx) : undefined);
96
- const right = Number(condition.right);
97
- return !isNaN(left) && !isNaN(right) && left >= right;
98
- }
99
- case 'lte': {
100
- const left = Number(condition.left ? this.resolve(condition.left.from, ctx) : undefined);
101
- const right = Number(condition.right);
102
- return !isNaN(left) && !isNaN(right) && left <= right;
103
- }
104
- case 'contains': {
105
- const left = condition.left ? this.resolve(condition.left.from, ctx) : undefined;
106
- const right = condition.right;
107
- if (typeof left === 'string' && typeof right === 'string')
108
- return left.includes(right);
109
- if (Array.isArray(left))
110
- return left.includes(right);
111
- return false;
112
- }
113
- case 'starts_with': {
114
- const left = condition.left ? this.resolve(condition.left.from, ctx) : undefined;
115
- const right = String(condition.right ?? '');
116
- return typeof left === 'string' && left.startsWith(right);
117
- }
118
- case 'ends_with': {
119
- const left = condition.left ? this.resolve(condition.left.from, ctx) : undefined;
120
- const right = String(condition.right ?? '');
121
- return typeof left === 'string' && left.endsWith(right);
122
- }
123
- case 'in_list': {
124
- const left = condition.left ? this.resolve(condition.left.from, ctx) : undefined;
125
- const list = condition.right;
126
- if (!Array.isArray(list))
127
- return false;
128
- return list.some((item) => String(item) === String(left));
129
- }
130
- case 'not_in_list': {
131
- const left = condition.left ? this.resolve(condition.left.from, ctx) : undefined;
132
- const list = condition.right;
133
- if (!Array.isArray(list))
134
- return true;
135
- return !list.some((item) => String(item) === String(left));
136
- }
137
- case 'between': {
138
- const left = Number(condition.left ? this.resolve(condition.left.from, ctx) : undefined);
139
- const range = condition.right;
140
- if (!Array.isArray(range) || range.length < 2)
141
- return false;
142
- const min = Number(range[0]);
143
- const max = Number(range[1]);
144
- return !isNaN(left) && !isNaN(min) && !isNaN(max) && left >= min && left <= max;
145
- }
146
- case 'is_true': {
147
- const left = condition.left ? this.resolve(condition.left.from, ctx) : undefined;
148
- return left === true || left === 'true';
149
- }
150
- case 'is_false': {
151
- const left = condition.left ? this.resolve(condition.left.from, ctx) : undefined;
152
- return left === false || left === 'false';
153
- }
154
- default:
155
- return false;
156
- }
157
- }
158
- // ─── Data resolution ──────────────────────────────────────────────────────
159
- resolve(from, ctx) {
160
- const dotIdx = from.indexOf('.');
161
- if (dotIdx === -1)
162
- return undefined;
163
- const source = from.substring(0, dotIdx);
164
- const key = from.substring(dotIdx + 1);
165
- switch (source) {
166
- case 'context': return this.getNested(ctx.context, key);
167
- case 'config': return this.getNested(ctx.config, key);
168
- case 'flags': return ctx.flags[key];
169
- default: return undefined;
170
- }
171
- }
172
- getNested(obj, key) {
173
- const parts = key.split('.');
174
- let current = obj;
175
- for (const part of parts) {
176
- if (current == null || typeof current !== 'object')
177
- return undefined;
178
- current = current[part];
179
- }
180
- return current;
181
- }
182
- setNested(obj, key, value) {
183
- const parts = key.split('.');
184
- let current = obj;
185
- for (let i = 0; i < parts.length - 1; i++) {
186
- if (!(parts[i] in current))
187
- current[parts[i]] = {};
188
- current = current[parts[i]];
189
- }
190
- current[parts[parts.length - 1]] = value;
191
- }
192
- }
193
- exports.KoolbaseLogicEngine = KoolbaseLogicEngine;
@@ -1,13 +0,0 @@
1
- import { KoolbaseConfig } from './types';
2
- export interface RegisterTokenOptions {
3
- token: string;
4
- platform: 'android' | 'ios';
5
- userId?: string;
6
- }
7
- export declare class KoolbaseMessaging {
8
- private config;
9
- private deviceId;
10
- constructor(config: KoolbaseConfig);
11
- setDeviceId(deviceId: string): void;
12
- registerToken(options: RegisterTokenOptions): Promise<boolean>;
13
- }
package/dist/messaging.js DELETED
@@ -1,36 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.KoolbaseMessaging = void 0;
4
- // ─── KoolbaseMessaging ────────────────────────────────────────────────────────
5
- class KoolbaseMessaging {
6
- constructor(config) {
7
- this.deviceId = '';
8
- this.config = config;
9
- }
10
- setDeviceId(deviceId) {
11
- this.deviceId = deviceId;
12
- }
13
- // ─── Register token ───────────────────────────────────────────────────────
14
- async registerToken(options) {
15
- try {
16
- const response = await fetch(`${this.config.baseUrl}/v1/messaging/register`, {
17
- method: 'POST',
18
- headers: {
19
- 'Content-Type': 'application/json',
20
- 'x-api-key': this.config.publicKey,
21
- },
22
- body: JSON.stringify({
23
- device_id: this.deviceId,
24
- token: options.token,
25
- platform: options.platform,
26
- ...(options.userId && { user_id: options.userId }),
27
- }),
28
- });
29
- return response.ok;
30
- }
31
- catch {
32
- return false;
33
- }
34
- }
35
- }
36
- exports.KoolbaseMessaging = KoolbaseMessaging;