@koolbase/core 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 (104) hide show
  1. package/README.md +19 -0
  2. package/dist/cjs/analytics.d.ts +24 -0
  3. package/dist/cjs/analytics.js +110 -0
  4. package/dist/cjs/auth-errors.d.ts +117 -0
  5. package/dist/cjs/auth-errors.js +250 -0
  6. package/dist/cjs/auth.d.ts +213 -0
  7. package/dist/cjs/auth.js +813 -0
  8. package/dist/cjs/cache-store.d.ts +50 -0
  9. package/dist/cjs/cache-store.js +194 -0
  10. package/dist/cjs/conflict.d.ts +80 -0
  11. package/dist/cjs/conflict.js +84 -0
  12. package/dist/cjs/database-errors.d.ts +101 -0
  13. package/dist/cjs/database-errors.js +200 -0
  14. package/dist/cjs/database.d.ts +298 -0
  15. package/dist/cjs/database.js +852 -0
  16. package/dist/cjs/device-id.d.ts +1 -0
  17. package/dist/cjs/device-id.js +57 -0
  18. package/dist/cjs/device-metadata.d.ts +36 -0
  19. package/dist/cjs/device-metadata.js +94 -0
  20. package/dist/cjs/errors.d.ts +64 -0
  21. package/dist/cjs/errors.js +85 -0
  22. package/dist/cjs/flags.d.ts +15 -0
  23. package/dist/cjs/flags.js +76 -0
  24. package/dist/cjs/function-errors.d.ts +51 -0
  25. package/dist/cjs/function-errors.js +103 -0
  26. package/dist/cjs/functions.d.ts +15 -0
  27. package/dist/cjs/functions.js +83 -0
  28. package/dist/cjs/index.d.ts +22 -0
  29. package/dist/cjs/index.js +56 -0
  30. package/dist/cjs/messaging.d.ts +13 -0
  31. package/dist/cjs/messaging.js +36 -0
  32. package/dist/cjs/offline-state.d.ts +97 -0
  33. package/dist/cjs/offline-state.js +198 -0
  34. package/dist/cjs/package.json +3 -0
  35. package/dist/cjs/pending-write.d.ts +47 -0
  36. package/dist/cjs/pending-write.js +22 -0
  37. package/dist/cjs/platform.d.ts +51 -0
  38. package/dist/cjs/platform.js +41 -0
  39. package/dist/cjs/realtime.d.ts +44 -0
  40. package/dist/cjs/realtime.js +195 -0
  41. package/dist/cjs/record.d.ts +2 -0
  42. package/dist/cjs/record.js +23 -0
  43. package/dist/cjs/shared.d.ts +9 -0
  44. package/dist/cjs/shared.js +43 -0
  45. package/dist/cjs/storage-errors.d.ts +163 -0
  46. package/dist/cjs/storage-errors.js +253 -0
  47. package/dist/cjs/storage.d.ts +198 -0
  48. package/dist/cjs/storage.js +451 -0
  49. package/dist/cjs/sync-engine.d.ts +30 -0
  50. package/dist/cjs/sync-engine.js +286 -0
  51. package/dist/cjs/types.d.ts +487 -0
  52. package/dist/cjs/types.js +40 -0
  53. package/dist/esm/analytics.d.ts +24 -0
  54. package/dist/esm/analytics.js +106 -0
  55. package/dist/esm/auth-errors.d.ts +117 -0
  56. package/dist/esm/auth-errors.js +222 -0
  57. package/dist/esm/auth.d.ts +213 -0
  58. package/dist/esm/auth.js +809 -0
  59. package/dist/esm/cache-store.d.ts +50 -0
  60. package/dist/esm/cache-store.js +179 -0
  61. package/dist/esm/conflict.d.ts +80 -0
  62. package/dist/esm/conflict.js +80 -0
  63. package/dist/esm/database-errors.d.ts +101 -0
  64. package/dist/esm/database-errors.js +189 -0
  65. package/dist/esm/database.d.ts +298 -0
  66. package/dist/esm/database.js +848 -0
  67. package/dist/esm/device-id.d.ts +1 -0
  68. package/dist/esm/device-id.js +54 -0
  69. package/dist/esm/device-metadata.d.ts +36 -0
  70. package/dist/esm/device-metadata.js +90 -0
  71. package/dist/esm/errors.d.ts +64 -0
  72. package/dist/esm/errors.js +79 -0
  73. package/dist/esm/flags.d.ts +15 -0
  74. package/dist/esm/flags.js +72 -0
  75. package/dist/esm/function-errors.d.ts +51 -0
  76. package/dist/esm/function-errors.js +93 -0
  77. package/dist/esm/functions.d.ts +15 -0
  78. package/dist/esm/functions.js +79 -0
  79. package/dist/esm/index.d.ts +22 -0
  80. package/dist/esm/index.js +25 -0
  81. package/dist/esm/messaging.d.ts +13 -0
  82. package/dist/esm/messaging.js +32 -0
  83. package/dist/esm/offline-state.d.ts +97 -0
  84. package/dist/esm/offline-state.js +189 -0
  85. package/dist/esm/package.json +3 -0
  86. package/dist/esm/pending-write.d.ts +47 -0
  87. package/dist/esm/pending-write.js +19 -0
  88. package/dist/esm/platform.d.ts +51 -0
  89. package/dist/esm/platform.js +36 -0
  90. package/dist/esm/realtime.d.ts +44 -0
  91. package/dist/esm/realtime.js +191 -0
  92. package/dist/esm/record.d.ts +2 -0
  93. package/dist/esm/record.js +20 -0
  94. package/dist/esm/shared.d.ts +9 -0
  95. package/dist/esm/shared.js +39 -0
  96. package/dist/esm/storage-errors.d.ts +163 -0
  97. package/dist/esm/storage-errors.js +239 -0
  98. package/dist/esm/storage.d.ts +198 -0
  99. package/dist/esm/storage.js +447 -0
  100. package/dist/esm/sync-engine.d.ts +30 -0
  101. package/dist/esm/sync-engine.js +282 -0
  102. package/dist/esm/types.d.ts +487 -0
  103. package/dist/esm/types.js +37 -0
  104. package/package.json +45 -0
@@ -0,0 +1 @@
1
+ export declare function getOrCreateDeviceId(): Promise<string>;
@@ -0,0 +1,57 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getOrCreateDeviceId = getOrCreateDeviceId;
4
+ const platform_js_1 = require("./platform.js");
5
+ // Single source of the anonymous device identifier for the whole SDK.
6
+ // Generated once, persisted, and shared by messaging (registration keying),
7
+ // feature flags (rollout bucketing: stableHash(deviceId + ":" + key) % 100),
8
+ // code push (targeting), and analytics. Previously each subsystem was handed a
9
+ // hardcoded 'rn-device' literal, so every RN device collided on one messaging
10
+ // registration row and bucketed identically for every rollout — a 10% flag was
11
+ // on for everyone or no one, never 10%.
12
+ //
13
+ // The id is anonymous, not a secret: what matters is uniform DISTRIBUTION so
14
+ // hash(id) % 100 is even, not unpredictability. We use crypto.getRandomValues
15
+ // when the runtime provides it (best distribution, no modulo bias) and fall
16
+ // back to Math.random otherwise — mirroring the runtime-guarded crypto use
17
+ // already in code-push.ts, and adding no dependency (per the SDK's stated
18
+ // preference against a crypto-grade UUID dependency for non-security ids).
19
+ const DEVICE_ID_KEY = 'koolbase:device_id';
20
+ let _cached = null;
21
+ async function getOrCreateDeviceId() {
22
+ if (_cached)
23
+ return _cached;
24
+ try {
25
+ const existing = await (0, platform_js_1.getPlatform)().storage.getItem(DEVICE_ID_KEY);
26
+ if (existing) {
27
+ _cached = existing;
28
+ return existing;
29
+ }
30
+ const newId = generateUUID();
31
+ await (0, platform_js_1.getPlatform)().storage.setItem(DEVICE_ID_KEY, newId);
32
+ _cached = newId;
33
+ return newId;
34
+ }
35
+ catch {
36
+ // Storage unavailable — return an ephemeral (unpersisted) id so the SDK
37
+ // stays functional rather than throwing. Not stable across launches.
38
+ return generateUUID();
39
+ }
40
+ }
41
+ // UUID v4. Uses crypto.getRandomValues where available for uniform,
42
+ // modulo-bias-free bytes; Math.random fallback keeps it dependency-free.
43
+ function generateUUID() {
44
+ const bytes = new Uint8Array(16);
45
+ const c = typeof crypto !== 'undefined' ? crypto : undefined;
46
+ if (c && typeof c.getRandomValues === 'function') {
47
+ c.getRandomValues(bytes);
48
+ }
49
+ else {
50
+ for (let i = 0; i < 16; i++)
51
+ bytes[i] = (Math.random() * 256) | 0;
52
+ }
53
+ bytes[6] = (bytes[6] & 0x0f) | 0x40; // version 4
54
+ bytes[8] = (bytes[8] & 0x3f) | 0x80; // variant
55
+ const hex = Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('');
56
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
57
+ }
@@ -0,0 +1,36 @@
1
+ /**
2
+ * Koolbase React Native SDK version. Sent in the `x-koolbase-sdk-version`
3
+ * header on every authenticated request so the server can route
4
+ * version-conditional logic (deprecation warnings, schema migrations,
5
+ * feature flags). Must match the `version` field in package.json.
6
+ */
7
+ export declare const koolbaseSdkVersion = "10.0.0";
8
+ /**
9
+ * Builds device-identifying headers attached to every Koolbase auth
10
+ * request. Mirrors the Flutter SDK's `DeviceMetadata` for parity. Apps
11
+ * with privacy concerns can swap in a custom storage adapter to avoid
12
+ * persisting the device label.
13
+ *
14
+ * Headers emitted:
15
+ * - User-Agent: koolbase-react-native/<sdk> (<platform> <version>)
16
+ * - x-koolbase-sdk: react-native
17
+ * - x-koolbase-sdk-version: <koolbaseSdkVersion>
18
+ * - x-koolbase-platform: ios | android | web | etc.
19
+ * - x-koolbase-platform-version: numeric SDK level or OS version string
20
+ * - x-koolbase-app-version: from KoolbaseConfig.appVersion or 'unknown'
21
+ * - x-koolbase-device-label: persistent UUID per install
22
+ */
23
+ export declare class DeviceMetadata {
24
+ private cached;
25
+ private ephemeralLabel;
26
+ private readonly appVersion;
27
+ constructor(appVersion?: string);
28
+ /**
29
+ * Build (or return cached) device headers. The first call may perform
30
+ * an async keychain read to look up the persisted device label;
31
+ * subsequent calls return the in-memory cache synchronously via the
32
+ * returned Promise.
33
+ */
34
+ build(): Promise<Record<string, string>>;
35
+ private getOrCreateDeviceLabel;
36
+ }
@@ -0,0 +1,94 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.DeviceMetadata = exports.koolbaseSdkVersion = void 0;
4
+ const platform_js_1 = require("./platform.js");
5
+ /**
6
+ * Koolbase React Native SDK version. Sent in the `x-koolbase-sdk-version`
7
+ * header on every authenticated request so the server can route
8
+ * version-conditional logic (deprecation warnings, schema migrations,
9
+ * feature flags). Must match the `version` field in package.json.
10
+ */
11
+ exports.koolbaseSdkVersion = '10.0.0';
12
+ /**
13
+ * Generate a UUIDv4-shaped string for use as a stable per-install
14
+ * device label. Not cryptographically secure — this is a label, not a
15
+ * security primitive. Avoids pulling in a crypto-grade UUID dependency.
16
+ */
17
+ function generateDeviceLabel() {
18
+ return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
19
+ const r = (Math.random() * 16) | 0;
20
+ const v = c === 'x' ? r : (r & 0x3) | 0x8;
21
+ return v.toString(16);
22
+ });
23
+ }
24
+ /**
25
+ * Builds device-identifying headers attached to every Koolbase auth
26
+ * request. Mirrors the Flutter SDK's `DeviceMetadata` for parity. Apps
27
+ * with privacy concerns can swap in a custom storage adapter to avoid
28
+ * persisting the device label.
29
+ *
30
+ * Headers emitted:
31
+ * - User-Agent: koolbase-react-native/<sdk> (<platform> <version>)
32
+ * - x-koolbase-sdk: react-native
33
+ * - x-koolbase-sdk-version: <koolbaseSdkVersion>
34
+ * - x-koolbase-platform: ios | android | web | etc.
35
+ * - x-koolbase-platform-version: numeric SDK level or OS version string
36
+ * - x-koolbase-app-version: from KoolbaseConfig.appVersion or 'unknown'
37
+ * - x-koolbase-device-label: persistent UUID per install
38
+ */
39
+ class DeviceMetadata {
40
+ constructor(appVersion) {
41
+ this.cached = null;
42
+ this.ephemeralLabel = null;
43
+ this.appVersion = appVersion ?? 'unknown';
44
+ }
45
+ /**
46
+ * Build (or return cached) device headers. The first call may perform
47
+ * an async keychain read to look up the persisted device label;
48
+ * subsequent calls return the in-memory cache synchronously via the
49
+ * returned Promise.
50
+ */
51
+ async build() {
52
+ if (this.cached)
53
+ return this.cached;
54
+ const platform = (0, platform_js_1.getPlatform)().info.os;
55
+ const platformVersion = (0, platform_js_1.getPlatform)().info.version;
56
+ const deviceLabel = await this.getOrCreateDeviceLabel();
57
+ // No User-Agent: a browser forbids setting it, and the same header set
58
+ // now goes out from both hosts. The platform and version below carry
59
+ // what it used to say.
60
+ this.cached = {
61
+ 'x-koolbase-sdk': (0, platform_js_1.getPlatform)().info.os === 'web' ? 'js' : 'react-native',
62
+ 'x-koolbase-sdk-version': exports.koolbaseSdkVersion,
63
+ 'x-koolbase-platform': platform,
64
+ 'x-koolbase-platform-version': platformVersion,
65
+ 'x-koolbase-app-version': this.appVersion,
66
+ 'x-koolbase-device-label': deviceLabel,
67
+ };
68
+ return this.cached;
69
+ }
70
+ async getOrCreateDeviceLabel() {
71
+ // A stable per-install label, kept in the platform's storage. On a host
72
+ // with nothing persistent (the in-memory adapter) it lives for the
73
+ // session, which is still useful for in-session debugging.
74
+ const key = 'koolbase_device_label_v1';
75
+ const storage = (0, platform_js_1.getPlatform)().storage;
76
+ try {
77
+ const existing = await storage.getItem(key);
78
+ if (existing)
79
+ return existing;
80
+ }
81
+ catch {
82
+ // fall through to create
83
+ }
84
+ const newLabel = generateDeviceLabel();
85
+ try {
86
+ await storage.setItem(key, newLabel);
87
+ }
88
+ catch {
89
+ // storage refused; the label still serves this session
90
+ }
91
+ return newLabel;
92
+ }
93
+ }
94
+ exports.DeviceMetadata = DeviceMetadata;
@@ -0,0 +1,64 @@
1
+ /**
2
+ * The root of every error the SDK raises.
3
+ *
4
+ * Each subsystem has its own family beneath this — data, storage, auth — so an
5
+ * application can catch narrowly where it wants to and broadly where it does
6
+ * not:
7
+ *
8
+ * ```ts
9
+ * try {
10
+ * await Koolbase.storage.upload(...);
11
+ * } catch (e) {
12
+ * if (e instanceof KoolbaseUnauthenticatedError) return goToLogin();
13
+ * if (e instanceof KoolbaseStorageError) return showError(e.message);
14
+ * throw e;
15
+ * }
16
+ * ```
17
+ *
18
+ * The families used to be unrelated roots, which meant a failure belonging to no
19
+ * single subsystem — a rejected credential, discovered by whichever call
20
+ * happened to make it — had to be redefined in each one.
21
+ */
22
+ export declare class KoolbaseError extends Error {
23
+ code?: string;
24
+ constructor(message: string, code?: string);
25
+ }
26
+ /**
27
+ * The server would not accept the caller's credentials.
28
+ *
29
+ * Raised by any surface — a query, an upload, a Function invoke — because a
30
+ * session stops working for the whole SDK at once, not one subsystem at a time.
31
+ *
32
+ * Named for what the server actually reports. A 401 covers an expired session, a
33
+ * revoked key, a malformed header, and no credentials at all, and the server
34
+ * does not distinguish them: calling this "session expired" would claim a
35
+ * precision that does not exist, and an app that signed a user out on a revoked
36
+ * API key would be acting on it.
37
+ *
38
+ * When the SDK holds a session it clears it before throwing, so by the time an
39
+ * application catches this the user is already signed out.
40
+ */
41
+ export declare class KoolbaseUnauthenticatedError extends KoolbaseError {
42
+ constructor(message: string);
43
+ }
44
+ /**
45
+ * An offline update or delete could not be queued, because the SDK has no
46
+ * record of what the change was composed against.
47
+ *
48
+ * Replaying a mutation without knowing the state it was based on means applying
49
+ * it blindly: whatever changed on the server in the meantime is overwritten,
50
+ * silently, with nobody able to tell it happened.
51
+ *
52
+ * A baseline is available when the record is in the local cache — read through
53
+ * a query, a single fetch, or seen over the socket — or when it was created
54
+ * offline and its insert is still queued. It is unavailable when the record has
55
+ * never been seen on this device, so read it first, or make the change while
56
+ * online where the server arbitrates directly.
57
+ *
58
+ * Deliberate rather than lenient. Queueing these anyway would mean most offline
59
+ * updates are conflict-safe and some quietly are not, which is a worse guarantee
60
+ * than a clear refusal.
61
+ */
62
+ export declare class KoolbaseOfflineBaselineUnavailableError extends KoolbaseError {
63
+ constructor(message: string);
64
+ }
@@ -0,0 +1,85 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.KoolbaseOfflineBaselineUnavailableError = exports.KoolbaseUnauthenticatedError = exports.KoolbaseError = void 0;
4
+ /**
5
+ * The root of every error the SDK raises.
6
+ *
7
+ * Each subsystem has its own family beneath this — data, storage, auth — so an
8
+ * application can catch narrowly where it wants to and broadly where it does
9
+ * not:
10
+ *
11
+ * ```ts
12
+ * try {
13
+ * await Koolbase.storage.upload(...);
14
+ * } catch (e) {
15
+ * if (e instanceof KoolbaseUnauthenticatedError) return goToLogin();
16
+ * if (e instanceof KoolbaseStorageError) return showError(e.message);
17
+ * throw e;
18
+ * }
19
+ * ```
20
+ *
21
+ * The families used to be unrelated roots, which meant a failure belonging to no
22
+ * single subsystem — a rejected credential, discovered by whichever call
23
+ * happened to make it — had to be redefined in each one.
24
+ */
25
+ class KoolbaseError extends Error {
26
+ constructor(message, code) {
27
+ super(message);
28
+ this.code = code;
29
+ this.name = 'KoolbaseError';
30
+ // Required for `instanceof` to work across the prototype chain when
31
+ // targeting ES5-era output, which TypeScript's class extension otherwise
32
+ // breaks. Every subclass repeats it for the same reason.
33
+ Object.setPrototypeOf(this, new.target.prototype);
34
+ }
35
+ }
36
+ exports.KoolbaseError = KoolbaseError;
37
+ /**
38
+ * The server would not accept the caller's credentials.
39
+ *
40
+ * Raised by any surface — a query, an upload, a Function invoke — because a
41
+ * session stops working for the whole SDK at once, not one subsystem at a time.
42
+ *
43
+ * Named for what the server actually reports. A 401 covers an expired session, a
44
+ * revoked key, a malformed header, and no credentials at all, and the server
45
+ * does not distinguish them: calling this "session expired" would claim a
46
+ * precision that does not exist, and an app that signed a user out on a revoked
47
+ * API key would be acting on it.
48
+ *
49
+ * When the SDK holds a session it clears it before throwing, so by the time an
50
+ * application catches this the user is already signed out.
51
+ */
52
+ class KoolbaseUnauthenticatedError extends KoolbaseError {
53
+ constructor(message) {
54
+ super(message, 'unauthenticated');
55
+ this.name = 'KoolbaseUnauthenticatedError';
56
+ Object.setPrototypeOf(this, new.target.prototype);
57
+ }
58
+ }
59
+ exports.KoolbaseUnauthenticatedError = KoolbaseUnauthenticatedError;
60
+ /**
61
+ * An offline update or delete could not be queued, because the SDK has no
62
+ * record of what the change was composed against.
63
+ *
64
+ * Replaying a mutation without knowing the state it was based on means applying
65
+ * it blindly: whatever changed on the server in the meantime is overwritten,
66
+ * silently, with nobody able to tell it happened.
67
+ *
68
+ * A baseline is available when the record is in the local cache — read through
69
+ * a query, a single fetch, or seen over the socket — or when it was created
70
+ * offline and its insert is still queued. It is unavailable when the record has
71
+ * never been seen on this device, so read it first, or make the change while
72
+ * online where the server arbitrates directly.
73
+ *
74
+ * Deliberate rather than lenient. Queueing these anyway would mean most offline
75
+ * updates are conflict-safe and some quietly are not, which is a worse guarantee
76
+ * than a clear refusal.
77
+ */
78
+ class KoolbaseOfflineBaselineUnavailableError extends KoolbaseError {
79
+ constructor(message) {
80
+ super(message, 'offline_baseline_unavailable');
81
+ this.name = 'KoolbaseOfflineBaselineUnavailableError';
82
+ Object.setPrototypeOf(this, new.target.prototype);
83
+ }
84
+ }
85
+ exports.KoolbaseOfflineBaselineUnavailableError = KoolbaseOfflineBaselineUnavailableError;
@@ -0,0 +1,15 @@
1
+ import { KoolbaseConfig, VersionCheckResult } from './types.js';
2
+ export declare class KoolbaseFlags {
3
+ private config;
4
+ private payload;
5
+ private deviceId;
6
+ constructor(config: KoolbaseConfig, deviceId: string);
7
+ fetch(appVersion: string, platform: string): Promise<void>;
8
+ isEnabled(key: string): boolean;
9
+ getString(key: string, fallback?: string): string;
10
+ getNumber(key: string, fallback?: number): number;
11
+ getBool(key: string, fallback?: boolean): boolean;
12
+ checkVersion(currentVersion: string): VersionCheckResult;
13
+ private parseVersion;
14
+ private stableHash;
15
+ }
@@ -0,0 +1,76 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.KoolbaseFlags = void 0;
4
+ class KoolbaseFlags {
5
+ constructor(config, deviceId) {
6
+ this.payload = null;
7
+ this.config = config;
8
+ this.deviceId = deviceId;
9
+ }
10
+ async fetch(appVersion, platform) {
11
+ try {
12
+ const res = await fetch(`${this.config.baseUrl}/v1/bootstrap?public_key=${this.config.publicKey}&device_id=${this.deviceId}&app_version=${appVersion}&platform=${platform}`);
13
+ if (res.ok) {
14
+ this.payload = await res.json();
15
+ }
16
+ }
17
+ catch (_) { }
18
+ }
19
+ isEnabled(key) {
20
+ const flag = this.payload?.flags[key];
21
+ if (!flag || !flag.enabled || flag.kill_switch)
22
+ return false;
23
+ const bucket = this.stableHash(`${this.deviceId}:${key}`) % 100;
24
+ return bucket < flag.rollout_percentage;
25
+ }
26
+ getString(key, fallback = '') {
27
+ const val = this.payload?.config[key];
28
+ return val !== undefined ? String(val) : fallback;
29
+ }
30
+ getNumber(key, fallback = 0) {
31
+ const val = this.payload?.config[key];
32
+ return typeof val === 'number' ? val : Number(val) || fallback;
33
+ }
34
+ getBool(key, fallback = false) {
35
+ const val = this.payload?.config[key];
36
+ if (typeof val === 'boolean')
37
+ return val;
38
+ return val === 'true' ? true : fallback;
39
+ }
40
+ checkVersion(currentVersion) {
41
+ const policy = this.payload?.version;
42
+ if (!policy?.min_version) {
43
+ return { status: 'up_to_date', message: '', latestVersion: '' };
44
+ }
45
+ const current = this.parseVersion(currentVersion);
46
+ const min = this.parseVersion(policy.min_version);
47
+ const latest = this.parseVersion(policy.latest_version);
48
+ if (current < min) {
49
+ return {
50
+ status: 'force_update',
51
+ message: policy.update_message,
52
+ latestVersion: policy.latest_version,
53
+ };
54
+ }
55
+ if (policy.latest_version && current < latest) {
56
+ return {
57
+ status: policy.force_update ? 'force_update' : 'soft_update',
58
+ message: policy.update_message,
59
+ latestVersion: policy.latest_version,
60
+ };
61
+ }
62
+ return { status: 'up_to_date', message: '', latestVersion: policy.latest_version };
63
+ }
64
+ parseVersion(v) {
65
+ const parts = v.split('.').map(Number);
66
+ return (parts[0] ?? 0) * 10000 + (parts[1] ?? 0) * 100 + (parts[2] ?? 0);
67
+ }
68
+ stableHash(s) {
69
+ let hash = 0;
70
+ for (let i = 0; i < s.length; i++) {
71
+ hash = (Math.imul(31, hash) + s.charCodeAt(i)) | 0;
72
+ }
73
+ return Math.abs(hash);
74
+ }
75
+ }
76
+ exports.KoolbaseFlags = KoolbaseFlags;
@@ -0,0 +1,51 @@
1
+ import { KoolbaseError } from './errors.js';
2
+ /**
3
+ * A Function call did not succeed.
4
+ *
5
+ * Every failure used to be a bare `Error`, so an application could only match on
6
+ * message text — and a missing Function, a caller without permission, a Function
7
+ * that threw, and an exhausted plan limit all looked alike, though they call for
8
+ * entirely different responses.
9
+ */
10
+ export declare class FunctionInvokeError extends KoolbaseError {
11
+ statusCode?: number;
12
+ constructor(message: string, statusCode?: number, code?: string);
13
+ }
14
+ /** No Function by that name is deployed to this project. */
15
+ export declare class FunctionNotFoundError extends FunctionInvokeError {
16
+ constructor(message: string);
17
+ }
18
+ /**
19
+ * The caller may not invoke this Function.
20
+ *
21
+ * Distinct from an authentication failure: the credentials were accepted and
22
+ * this caller is not permitted. Retrying will not help, and signing the user out
23
+ * would be wrong.
24
+ */
25
+ export declare class FunctionPermissionError extends FunctionInvokeError {
26
+ constructor(message: string);
27
+ }
28
+ /** The Function rejected its arguments. */
29
+ export declare class FunctionValidationError extends FunctionInvokeError {
30
+ constructor(message: string);
31
+ }
32
+ /**
33
+ * The project's Function invocations are used up.
34
+ *
35
+ * Nothing about the call is wrong — retrying will not help until the plan
36
+ * allows it. The one failure here fixed by changing a plan rather than code.
37
+ */
38
+ export declare class FunctionQuotaExceededError extends FunctionInvokeError {
39
+ constructor(message: string);
40
+ }
41
+ /**
42
+ * The Function ran and threw.
43
+ *
44
+ * The message is the Function's own, not the platform's — it comes from the code
45
+ * that was deployed.
46
+ */
47
+ export declare class FunctionExecutionError extends FunctionInvokeError {
48
+ constructor(message: string, statusCode?: number);
49
+ }
50
+ /** Builds the right error for a failed invocation. */
51
+ export declare function functionInvokeError(status: number, message: string): KoolbaseError;
@@ -0,0 +1,103 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.FunctionExecutionError = exports.FunctionQuotaExceededError = exports.FunctionValidationError = exports.FunctionPermissionError = exports.FunctionNotFoundError = exports.FunctionInvokeError = void 0;
4
+ exports.functionInvokeError = functionInvokeError;
5
+ const errors_js_1 = require("./errors.js");
6
+ /**
7
+ * A Function call did not succeed.
8
+ *
9
+ * Every failure used to be a bare `Error`, so an application could only match on
10
+ * message text — and a missing Function, a caller without permission, a Function
11
+ * that threw, and an exhausted plan limit all looked alike, though they call for
12
+ * entirely different responses.
13
+ */
14
+ class FunctionInvokeError extends errors_js_1.KoolbaseError {
15
+ constructor(message, statusCode, code) {
16
+ super(message, code);
17
+ this.statusCode = statusCode;
18
+ this.name = 'FunctionInvokeError';
19
+ Object.setPrototypeOf(this, new.target.prototype);
20
+ }
21
+ }
22
+ exports.FunctionInvokeError = FunctionInvokeError;
23
+ /** No Function by that name is deployed to this project. */
24
+ class FunctionNotFoundError extends FunctionInvokeError {
25
+ constructor(message) {
26
+ super(message, 404, 'not_found');
27
+ this.name = 'FunctionNotFoundError';
28
+ Object.setPrototypeOf(this, new.target.prototype);
29
+ }
30
+ }
31
+ exports.FunctionNotFoundError = FunctionNotFoundError;
32
+ /**
33
+ * The caller may not invoke this Function.
34
+ *
35
+ * Distinct from an authentication failure: the credentials were accepted and
36
+ * this caller is not permitted. Retrying will not help, and signing the user out
37
+ * would be wrong.
38
+ */
39
+ class FunctionPermissionError extends FunctionInvokeError {
40
+ constructor(message) {
41
+ super(message, 403, 'permission_denied');
42
+ this.name = 'FunctionPermissionError';
43
+ Object.setPrototypeOf(this, new.target.prototype);
44
+ }
45
+ }
46
+ exports.FunctionPermissionError = FunctionPermissionError;
47
+ /** The Function rejected its arguments. */
48
+ class FunctionValidationError extends FunctionInvokeError {
49
+ constructor(message) {
50
+ super(message, 400, 'validation_error');
51
+ this.name = 'FunctionValidationError';
52
+ Object.setPrototypeOf(this, new.target.prototype);
53
+ }
54
+ }
55
+ exports.FunctionValidationError = FunctionValidationError;
56
+ /**
57
+ * The project's Function invocations are used up.
58
+ *
59
+ * Nothing about the call is wrong — retrying will not help until the plan
60
+ * allows it. The one failure here fixed by changing a plan rather than code.
61
+ */
62
+ class FunctionQuotaExceededError extends FunctionInvokeError {
63
+ constructor(message) {
64
+ super(message, 402, 'limit_reached');
65
+ this.name = 'FunctionQuotaExceededError';
66
+ Object.setPrototypeOf(this, new.target.prototype);
67
+ }
68
+ }
69
+ exports.FunctionQuotaExceededError = FunctionQuotaExceededError;
70
+ /**
71
+ * The Function ran and threw.
72
+ *
73
+ * The message is the Function's own, not the platform's — it comes from the code
74
+ * that was deployed.
75
+ */
76
+ class FunctionExecutionError extends FunctionInvokeError {
77
+ constructor(message, statusCode) {
78
+ super(message, statusCode, 'execution_failed');
79
+ this.name = 'FunctionExecutionError';
80
+ Object.setPrototypeOf(this, new.target.prototype);
81
+ }
82
+ }
83
+ exports.FunctionExecutionError = FunctionExecutionError;
84
+ /** Builds the right error for a failed invocation. */
85
+ function functionInvokeError(status, message) {
86
+ switch (status) {
87
+ case 401:
88
+ // Not a Function failure. A rejected credential stops the whole SDK
89
+ // working, so it raises the shared type.
90
+ return new errors_js_1.KoolbaseUnauthenticatedError(message);
91
+ case 403:
92
+ return new FunctionPermissionError(message);
93
+ case 404:
94
+ return new FunctionNotFoundError(message);
95
+ case 400:
96
+ return new FunctionValidationError(message);
97
+ case 402:
98
+ return new FunctionQuotaExceededError(message);
99
+ }
100
+ if (status >= 500)
101
+ return new FunctionExecutionError(message, status);
102
+ return new FunctionInvokeError(message, status);
103
+ }
@@ -0,0 +1,15 @@
1
+ import { KoolbaseConfig, FunctionInvokeResult, DeployOptions, DeployResult } from './types.js';
2
+ export declare class KoolbaseFunctions {
3
+ private config;
4
+ private getUserAccessToken?;
5
+ /**
6
+ * Called when the server rejects the caller's credentials.
7
+ *
8
+ * A session stops working for the whole SDK at once, so an app whose failing
9
+ * call happens to be a Function invoke must not keep believing it is signed in.
10
+ */
11
+ private onSessionExpired?;
12
+ constructor(config: KoolbaseConfig, getUserAccessToken?: () => Promise<string | null>, onSessionExpired?: () => Promise<void>);
13
+ deploy(options: DeployOptions): Promise<DeployResult>;
14
+ invoke(name: string, body?: Record<string, unknown>): Promise<FunctionInvokeResult>;
15
+ }