@qafka/react-native-cms 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/AGENTS.md +510 -0
- package/README.md +244 -2
- package/android/build.gradle +41 -0
- package/android/src/main/AndroidManifest.xml +2 -0
- package/android/src/main/java/com/qafkacms/QafkaCmsPackage.kt +21 -0
- package/android/src/main/java/com/qafkacms/attestation/QafkaCmsAttestationModule.kt +92 -0
- package/android/src/main/java/com/qafkacms/push/QafkaCmsPushModule.kt +162 -0
- package/android/src/main/java/com/qafkacms/storage/QafkaCmsStorageModule.kt +80 -0
- package/app.plugin.js +1 -0
- package/dist/index.d.ts +2373 -0
- package/dist/index.js +4468 -0
- package/dist/index.js.map +1 -0
- package/expo-plugin/apnsForwarding.js +48 -0
- package/expo-plugin/withQafkaCms.js +23 -0
- package/expo-plugin/withQafkaCmsAttestation.js +27 -0
- package/expo-plugin/withQafkaCmsPush.js +53 -0
- package/ios/QafkaCmsAttestation.m +25 -0
- package/ios/QafkaCmsAttestation.swift +128 -0
- package/ios/QafkaCmsPush.m +22 -0
- package/ios/QafkaCmsPush.swift +143 -0
- package/ios/QafkaCmsReactImports.h +2 -0
- package/ios/QafkaCmsStorage.m +26 -0
- package/ios/QafkaCmsStorage.swift +118 -0
- package/package.json +42 -4
- package/qafkacms.config.d.ts +9 -0
- package/qafkacms.config.js +13 -0
- package/react-native-qafkacms.podspec +20 -0
- package/react-native.config.js +17 -0
package/dist/index.js
ADDED
|
@@ -0,0 +1,4468 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
|
|
7
|
+
var __export = (target, all) => {
|
|
8
|
+
for (var name in all)
|
|
9
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
10
|
+
};
|
|
11
|
+
var __copyProps = (to, from, except, desc) => {
|
|
12
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
13
|
+
for (let key of __getOwnPropNames(from))
|
|
14
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
15
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
16
|
+
}
|
|
17
|
+
return to;
|
|
18
|
+
};
|
|
19
|
+
var __toCommonJS = (mod3) => __copyProps(__defProp({}, "__esModule", { value: true }), mod3);
|
|
20
|
+
var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
|
|
21
|
+
|
|
22
|
+
// src/index.ts
|
|
23
|
+
var src_exports = {};
|
|
24
|
+
__export(src_exports, {
|
|
25
|
+
AttestationManager: () => AttestationManager,
|
|
26
|
+
AuthClient: () => AuthClient,
|
|
27
|
+
CURRENT_USER: () => CURRENT_USER,
|
|
28
|
+
ConfigSyncClient: () => ConfigSyncClient,
|
|
29
|
+
ContentClient: () => ContentClient,
|
|
30
|
+
DeviceRegistrationManager: () => DeviceRegistrationManager,
|
|
31
|
+
LanguageManager: () => LanguageManager,
|
|
32
|
+
NOW: () => NOW,
|
|
33
|
+
ProblemError: () => ProblemError,
|
|
34
|
+
QafkaCmsClient: () => QafkaCmsClient,
|
|
35
|
+
QafkaCmsProvider: () => QafkaCmsProvider2,
|
|
36
|
+
QueryCache: () => QueryCache,
|
|
37
|
+
SDK_VERSION: () => SDK_VERSION,
|
|
38
|
+
UnlockTokenStore: () => UnlockTokenStore,
|
|
39
|
+
createClient: () => createClient,
|
|
40
|
+
createMemoryCacheStorage: () => createMemoryCacheStorage,
|
|
41
|
+
getVersion: () => getVersion,
|
|
42
|
+
now: () => now,
|
|
43
|
+
parseDuration: () => parseDuration,
|
|
44
|
+
resolveColor: () => resolveColor,
|
|
45
|
+
serializeKey: () => serializeKey,
|
|
46
|
+
useAuth: () => useAuth,
|
|
47
|
+
useBundle: () => useBundle,
|
|
48
|
+
useBundleItem: () => useBundleItem,
|
|
49
|
+
useContent: () => useContent,
|
|
50
|
+
useContentItem: () => useContentItem,
|
|
51
|
+
useLocale: () => useLocale,
|
|
52
|
+
useLookup: () => useLookup,
|
|
53
|
+
useMutation: () => useMutation2,
|
|
54
|
+
usePush: () => usePush,
|
|
55
|
+
useQafkaCms: () => useQafkaCms2,
|
|
56
|
+
useQafkaCmsCache: () => useQafkaCmsCache,
|
|
57
|
+
useQafkaCmsClient: () => useQafkaCmsClient2,
|
|
58
|
+
useQuery: () => useQuery2,
|
|
59
|
+
useResolvedColor: () => useResolvedColor,
|
|
60
|
+
useTranslation: () => useTranslation
|
|
61
|
+
});
|
|
62
|
+
module.exports = __toCommonJS(src_exports);
|
|
63
|
+
|
|
64
|
+
// ../core/src/constants.ts
|
|
65
|
+
var SDK_VERSION = "0.0.0";
|
|
66
|
+
var END_USER_BASE_PATH = "/v1/end-user";
|
|
67
|
+
var STORAGE_PREFIX = "@qafka/cms/";
|
|
68
|
+
var STORAGE_KEY_ATTESTATION_KEY_ID = `${STORAGE_PREFIX}attestation_key_id`;
|
|
69
|
+
var STORAGE_KEY_DEVICE_ID = `${STORAGE_PREFIX}device_id`;
|
|
70
|
+
var STORAGE_KEY_REFRESH_TOKEN = `${STORAGE_PREFIX}refresh_token`;
|
|
71
|
+
var STORAGE_KEY_EXTERNAL_SESSION = `${STORAGE_PREFIX}external_session`;
|
|
72
|
+
var STORAGE_KEY_ANONYMOUS_SESSION = `${STORAGE_PREFIX}anonymous_session`;
|
|
73
|
+
var STORAGE_KEY_CONFIG_PREFIX = `${STORAGE_PREFIX}config:`;
|
|
74
|
+
var STORAGE_KEY_LOCALE = `${STORAGE_PREFIX}locale`;
|
|
75
|
+
var STORAGE_KEY_QUERY_PREFIX = `${STORAGE_PREFIX}query:`;
|
|
76
|
+
var STORAGE_KEY_QUERY_INDEX = `${STORAGE_PREFIX}query-index`;
|
|
77
|
+
var ANDROID_ATTEST_ALIAS = "qafkacms_attest";
|
|
78
|
+
var STORAGE_KEY_UNLOCK_TOKENS = `${STORAGE_PREFIX}unlock_tokens`;
|
|
79
|
+
|
|
80
|
+
// ../core/src/app-version.ts
|
|
81
|
+
var APP_VERSION_RE = /^\d{1,9}(\.\d{1,9}){0,3}$/;
|
|
82
|
+
function parseAppVersion(s) {
|
|
83
|
+
if (typeof s !== "string" || !APP_VERSION_RE.test(s)) return null;
|
|
84
|
+
const parts = s.split(".").map(Number);
|
|
85
|
+
return [parts[0], parts[1] ?? 0, parts[2] ?? 0, parts[3] ?? 0];
|
|
86
|
+
}
|
|
87
|
+
function compareAppVersion(a, b) {
|
|
88
|
+
const x = typeof a === "string" ? parseAppVersion(a) : a;
|
|
89
|
+
const y = typeof b === "string" ? parseAppVersion(b) : b;
|
|
90
|
+
if (!x || !y) throw new Error(`QafkaCMS: invalid app version "${String(x ? b : a)}"`);
|
|
91
|
+
for (let i = 0; i < 4; i++) if (x[i] !== y[i]) return x[i] - y[i];
|
|
92
|
+
return 0;
|
|
93
|
+
}
|
|
94
|
+
function validAppVersion(s) {
|
|
95
|
+
return parseAppVersion(s) ? s : null;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
// ../core/src/transport/problem-details.ts
|
|
99
|
+
var ProblemError = class extends Error {
|
|
100
|
+
constructor(status, problem) {
|
|
101
|
+
super(problem.detail || problem.title || `HTTP ${status}`);
|
|
102
|
+
__publicField(this, "status");
|
|
103
|
+
__publicField(this, "type");
|
|
104
|
+
__publicField(this, "title");
|
|
105
|
+
__publicField(this, "detail");
|
|
106
|
+
__publicField(this, "instance");
|
|
107
|
+
/** Machine-readable error code from the problem body (e.g. `EMAIL_NOT_VERIFIED`). */
|
|
108
|
+
__publicField(this, "code");
|
|
109
|
+
__publicField(this, "raw");
|
|
110
|
+
this.name = "ProblemError";
|
|
111
|
+
this.status = status;
|
|
112
|
+
this.type = problem.type;
|
|
113
|
+
this.title = problem.title;
|
|
114
|
+
this.detail = problem.detail;
|
|
115
|
+
this.instance = problem.instance;
|
|
116
|
+
this.code = problem.code;
|
|
117
|
+
this.raw = problem;
|
|
118
|
+
}
|
|
119
|
+
};
|
|
120
|
+
async function toProblemError(response) {
|
|
121
|
+
let problem = {};
|
|
122
|
+
try {
|
|
123
|
+
problem = await response.json();
|
|
124
|
+
} catch {
|
|
125
|
+
problem = { title: response.statusText || "Request failed" };
|
|
126
|
+
}
|
|
127
|
+
return new ProblemError(response.status, problem ?? {});
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
// ../core/src/transport/proof.ts
|
|
131
|
+
function identityHeaders(identity, ctx) {
|
|
132
|
+
const headers = {};
|
|
133
|
+
if (identity.projectId) headers["X-Project-Id"] = identity.projectId;
|
|
134
|
+
if (ctx.withProjectKey && identity.publishableKey) headers["X-Project-Key"] = identity.publishableKey;
|
|
135
|
+
const slug = ctx.projectSlug ?? identity.projectSlug;
|
|
136
|
+
if (slug) headers["X-Project-Slug"] = slug;
|
|
137
|
+
return headers;
|
|
138
|
+
}
|
|
139
|
+
var AttestationProof = class {
|
|
140
|
+
constructor(identity, deps) {
|
|
141
|
+
__publicField(this, "identity", identity);
|
|
142
|
+
__publicField(this, "deps", deps);
|
|
143
|
+
__publicField(this, "refresh");
|
|
144
|
+
__publicField(this, "ready", null);
|
|
145
|
+
const renew = deps.refresh;
|
|
146
|
+
if (renew) {
|
|
147
|
+
this.refresh = async () => {
|
|
148
|
+
const token = await renew();
|
|
149
|
+
return token ? { "X-Session-Token": token } : null;
|
|
150
|
+
};
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
async headers(ctx) {
|
|
154
|
+
const headers = identityHeaders(this.identity, ctx);
|
|
155
|
+
if (this.deps.getSessionToken) {
|
|
156
|
+
const session = await this.deps.getSessionToken();
|
|
157
|
+
if (session) headers["X-Session-Token"] = session;
|
|
158
|
+
}
|
|
159
|
+
const devKey = this.deps.getDevApiKey?.();
|
|
160
|
+
if (devKey) headers["x-api-key"] = devKey;
|
|
161
|
+
return headers;
|
|
162
|
+
}
|
|
163
|
+
/**
|
|
164
|
+
* Run the first attestation exactly once; concurrent callers await the same
|
|
165
|
+
* promise. A failed attempt is forgotten so the next call retries.
|
|
166
|
+
*/
|
|
167
|
+
initialize() {
|
|
168
|
+
if (!this.ready) {
|
|
169
|
+
const attempt = this.deps.initialize ? this.deps.initialize() : Promise.resolve();
|
|
170
|
+
this.ready = attempt;
|
|
171
|
+
attempt.catch(() => {
|
|
172
|
+
if (this.ready === attempt) this.ready = null;
|
|
173
|
+
});
|
|
174
|
+
}
|
|
175
|
+
return this.ready;
|
|
176
|
+
}
|
|
177
|
+
/** True once {@link initialize} has started (and not failed). */
|
|
178
|
+
hasStarted() {
|
|
179
|
+
return this.ready !== null;
|
|
180
|
+
}
|
|
181
|
+
};
|
|
182
|
+
|
|
183
|
+
// ../core/src/transport/HttpClient.ts
|
|
184
|
+
var BUDGET_REFRESH_THRESHOLD = 1e3;
|
|
185
|
+
var HttpClient = class {
|
|
186
|
+
constructor(config, deps) {
|
|
187
|
+
__publicField(this, "config");
|
|
188
|
+
__publicField(this, "d");
|
|
189
|
+
__publicField(this, "proof");
|
|
190
|
+
/** The configured app version when valid (sent as `X-App-Version`), else `null`. */
|
|
191
|
+
__publicField(this, "appVersion");
|
|
192
|
+
this.config = config;
|
|
193
|
+
this.d = deps;
|
|
194
|
+
this.appVersion = validAppVersion(config.appVersion);
|
|
195
|
+
this.proof = deps.proof ?? new AttestationProof(
|
|
196
|
+
{ projectId: config.projectId, publishableKey: config.publishableKey, projectSlug: config.projectSlug },
|
|
197
|
+
{ getSessionToken: deps.getSessionToken, refresh: deps.onRefreshRequired, getDevApiKey: deps.getDevApiKey }
|
|
198
|
+
);
|
|
199
|
+
}
|
|
200
|
+
async request(method, path, options = {}) {
|
|
201
|
+
const res = await this.send(method, path, options);
|
|
202
|
+
if (!res.ok) throw await toProblemError(res);
|
|
203
|
+
if (res.status === 204) return void 0;
|
|
204
|
+
return await res.json();
|
|
205
|
+
}
|
|
206
|
+
/**
|
|
207
|
+
* {@link request} with HTTP conditional-GET support (QFK2-E59 D3). Sends
|
|
208
|
+
* `If-None-Match` only when `options.ifNoneMatch` is a non-empty string; a
|
|
209
|
+
* 304 counts as "not modified" only then. A 304 to a request without it is
|
|
210
|
+
* an error, exactly as in {@link request}. Same headers, refresh and retry.
|
|
211
|
+
*/
|
|
212
|
+
async requestConditional(method, path, options = {}) {
|
|
213
|
+
const { ifNoneMatch, ...rest } = options;
|
|
214
|
+
const tag = typeof ifNoneMatch === "string" && ifNoneMatch.length > 0 ? ifNoneMatch : null;
|
|
215
|
+
const res = await this.send(method, path, rest, tag ? { "If-None-Match": tag } : void 0);
|
|
216
|
+
if (tag && res.status === 304) return { notModified: true };
|
|
217
|
+
if (!res.ok) throw await toProblemError(res);
|
|
218
|
+
const etag = res.headers?.get?.("ETag") || null;
|
|
219
|
+
if (res.status === 204) return { notModified: false, data: void 0, etag };
|
|
220
|
+
return { notModified: false, data: await res.json(), etag };
|
|
221
|
+
}
|
|
222
|
+
/** Build the URL + headers, send through the refresh path; status handling is the caller's. */
|
|
223
|
+
async send(method, path, options, extraHeaders) {
|
|
224
|
+
const url = this.buildUrl(path, options.query);
|
|
225
|
+
const headers = await this.securityHeaders(options, { method, path });
|
|
226
|
+
if (extraHeaders) Object.assign(headers, extraHeaders);
|
|
227
|
+
const init = { method, headers };
|
|
228
|
+
if (options.body !== void 0) init.body = JSON.stringify(options.body);
|
|
229
|
+
return this.fetchWithRefresh(url, init);
|
|
230
|
+
}
|
|
231
|
+
/**
|
|
232
|
+
* Exposed for clients that need the resolved security headers (e.g. SSE).
|
|
233
|
+
* `target` (method + end-user path) lets the proof provider scope
|
|
234
|
+
* request-specific headers (e.g. a captcha token on auth POSTs).
|
|
235
|
+
*/
|
|
236
|
+
async securityHeaders(options = {}, target) {
|
|
237
|
+
const headers = { "Content-Type": "application/json" };
|
|
238
|
+
if (this.config.platformOS) headers["x-platform"] = this.config.platformOS;
|
|
239
|
+
headers["x-sdk-version"] = this.config.sdkVersion ?? SDK_VERSION;
|
|
240
|
+
if (this.appVersion) headers["X-App-Version"] = this.appVersion;
|
|
241
|
+
if (!options.anonymous && this.d.getAccessToken) {
|
|
242
|
+
const token = await this.d.getAccessToken();
|
|
243
|
+
if (token) headers["Authorization"] = `Bearer ${token}`;
|
|
244
|
+
}
|
|
245
|
+
const authenticated = Boolean(headers["Authorization"]);
|
|
246
|
+
Object.assign(
|
|
247
|
+
headers,
|
|
248
|
+
await this.proof.headers({
|
|
249
|
+
authenticated,
|
|
250
|
+
withProjectKey: !authenticated,
|
|
251
|
+
projectSlug: options.projectSlug,
|
|
252
|
+
method: target?.method,
|
|
253
|
+
path: target?.path
|
|
254
|
+
})
|
|
255
|
+
);
|
|
256
|
+
const locale = this.d.getLocale?.();
|
|
257
|
+
if (locale) headers["Accept-Language"] = locale;
|
|
258
|
+
const unlock = options.withUnlockTokens ? this.d.getUnlockTokens?.() : void 0;
|
|
259
|
+
if (unlock && unlock.length) headers["X-Unlock-Token"] = unlock.join(",");
|
|
260
|
+
return headers;
|
|
261
|
+
}
|
|
262
|
+
/**
|
|
263
|
+
* Project + proof headers: `X-Project-Id`, `X-Project-Key` (when
|
|
264
|
+
* `withProjectKey`), `X-Project-Slug`, and `X-Session-Token` (release) or
|
|
265
|
+
* `x-api-key` (dev-bypass). {@link securityHeaders} sends the key only on
|
|
266
|
+
* requests without a Bearer; `getRequestHeaders()` (no Authorization, the
|
|
267
|
+
* caller decides) always does.
|
|
268
|
+
*/
|
|
269
|
+
async projectProofHeaders(options) {
|
|
270
|
+
return this.proof.headers({
|
|
271
|
+
authenticated: false,
|
|
272
|
+
withProjectKey: options.withProjectKey,
|
|
273
|
+
projectSlug: options.projectSlug
|
|
274
|
+
});
|
|
275
|
+
}
|
|
276
|
+
/** The proof provider (for `initialize()` / own-client header helpers). */
|
|
277
|
+
getProof() {
|
|
278
|
+
return this.proof;
|
|
279
|
+
}
|
|
280
|
+
async fetchWithRefresh(url, init, retries = 1) {
|
|
281
|
+
const res = await this.d.fetch(url, init);
|
|
282
|
+
const refreshRequired = res.headers.get("X-Token-Refresh-Required") === "true";
|
|
283
|
+
const remainingStr = res.headers.get("X-Token-Budget-Remaining");
|
|
284
|
+
const remaining = remainingStr != null ? parseInt(remainingStr, 10) : NaN;
|
|
285
|
+
const refresh = this.proof.refresh ? () => this.proof.refresh() : null;
|
|
286
|
+
if (res.status === 429 && refreshRequired && retries > 0 && refresh) {
|
|
287
|
+
const overlay = await refresh();
|
|
288
|
+
if (overlay) {
|
|
289
|
+
const headers = { ...init.headers, ...overlay };
|
|
290
|
+
return this.fetchWithRefresh(url, { ...init, headers }, retries - 1);
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
if (res.status === 401 && retries > 0 && refresh && await problemCode(res) === "ATTESTATION_SESSION_EXPIRED") {
|
|
294
|
+
const overlay = await refresh();
|
|
295
|
+
if (overlay) {
|
|
296
|
+
const headers = { ...init.headers, ...overlay };
|
|
297
|
+
return this.fetchWithRefresh(url, { ...init, headers }, retries - 1);
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
if (refresh && (refreshRequired || !isNaN(remaining) && remaining < BUDGET_REFRESH_THRESHOLD)) {
|
|
301
|
+
void refresh();
|
|
302
|
+
}
|
|
303
|
+
return res;
|
|
304
|
+
}
|
|
305
|
+
buildUrl(path, query) {
|
|
306
|
+
const base = `${this.config.apiUrl.replace(/\/$/, "")}${END_USER_BASE_PATH}${path}`;
|
|
307
|
+
if (!query) return base;
|
|
308
|
+
const parts = [];
|
|
309
|
+
for (const [key, value] of Object.entries(query)) {
|
|
310
|
+
if (value === void 0 || value === null) continue;
|
|
311
|
+
parts.push(`${encodeURIComponent(key)}=${encodeURIComponent(String(value))}`);
|
|
312
|
+
}
|
|
313
|
+
return parts.length ? `${base}?${parts.join("&")}` : base;
|
|
314
|
+
}
|
|
315
|
+
};
|
|
316
|
+
async function problemCode(res) {
|
|
317
|
+
try {
|
|
318
|
+
if (typeof res.clone !== "function") return void 0;
|
|
319
|
+
const body = await res.clone().json();
|
|
320
|
+
return typeof body?.code === "string" ? body.code : void 0;
|
|
321
|
+
} catch {
|
|
322
|
+
return void 0;
|
|
323
|
+
}
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
// ../core/src/auth/jwt-decode.ts
|
|
327
|
+
function base64UrlDecode(input) {
|
|
328
|
+
const b64 = input.replace(/-/g, "+").replace(/_/g, "/");
|
|
329
|
+
const pad = b64.length % 4 === 0 ? 0 : 4 - b64.length % 4;
|
|
330
|
+
const padded = b64 + "=".repeat(pad);
|
|
331
|
+
const binary = atob(padded);
|
|
332
|
+
try {
|
|
333
|
+
return decodeURIComponent(
|
|
334
|
+
binary.split("").map((c) => "%" + c.charCodeAt(0).toString(16).padStart(2, "0")).join("")
|
|
335
|
+
);
|
|
336
|
+
} catch {
|
|
337
|
+
return binary;
|
|
338
|
+
}
|
|
339
|
+
}
|
|
340
|
+
function decodeAccessToken(token) {
|
|
341
|
+
if (!token) return null;
|
|
342
|
+
const parts = token.split(".");
|
|
343
|
+
if (parts.length < 2 || !parts[1]) return null;
|
|
344
|
+
try {
|
|
345
|
+
const claims = JSON.parse(base64UrlDecode(parts[1]));
|
|
346
|
+
if (!claims || typeof claims !== "object") return null;
|
|
347
|
+
return claims;
|
|
348
|
+
} catch {
|
|
349
|
+
return null;
|
|
350
|
+
}
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
// ../core/src/auth/AuthClient.ts
|
|
354
|
+
var AUTH = "/auth";
|
|
355
|
+
var EXTERNAL_MARKER_DEFAULT = "1";
|
|
356
|
+
var UPGRADE_OUTCOMES = ["upgraded", "switched"];
|
|
357
|
+
function isSessionRejected(e) {
|
|
358
|
+
if (!(e instanceof ProblemError) || e.status !== 401) return false;
|
|
359
|
+
const code = e.raw.code;
|
|
360
|
+
return !(typeof code === "string" && code.startsWith("ATTESTATION_"));
|
|
361
|
+
}
|
|
362
|
+
var AuthClient = class {
|
|
363
|
+
constructor(http, store, now2 = Date.now, options = {}) {
|
|
364
|
+
__publicField(this, "http", http);
|
|
365
|
+
__publicField(this, "store", store);
|
|
366
|
+
__publicField(this, "now", now2);
|
|
367
|
+
__publicField(this, "options", options);
|
|
368
|
+
/** Shared in-flight refresh, so concurrent requests trigger a single `/refresh`. */
|
|
369
|
+
__publicField(this, "refreshing", null);
|
|
370
|
+
__publicField(this, "authStateCache", null);
|
|
371
|
+
__publicField(this, "authStateVersion", -1);
|
|
372
|
+
/** Shared in-flight anonymous sign-in (QFK2-T322). */
|
|
373
|
+
__publicField(this, "anonymousSigningIn", null);
|
|
374
|
+
/** `anonymousAuth: 'auto'`: create an anonymous user on the next token need (set by logout/deleteAccount). */
|
|
375
|
+
__publicField(this, "autoAnonymousArmed", false);
|
|
376
|
+
__publicField(this, "lastUpgradeOutcome", null);
|
|
377
|
+
/** Mirror of the persisted anonymous-session marker; null = not read/written yet. */
|
|
378
|
+
__publicField(this, "anonymousMarker", null);
|
|
379
|
+
}
|
|
380
|
+
async register(input) {
|
|
381
|
+
return this.http.request("POST", `${AUTH}/register`, { body: input, anonymous: true });
|
|
382
|
+
}
|
|
383
|
+
async login(input) {
|
|
384
|
+
const tokens = await this.http.request("POST", `${AUTH}/login`, { body: input, anonymous: true });
|
|
385
|
+
await this.storeCmsTokens(tokens);
|
|
386
|
+
return tokens;
|
|
387
|
+
}
|
|
388
|
+
/**
|
|
389
|
+
* Sign in with a token from the customer's own identity provider (E44).
|
|
390
|
+
* For a `sessionMode: 'external'` provider the CMS issues an access token
|
|
391
|
+
* only; it is renewed through `externalTokenProvider`. For `'cms'` providers
|
|
392
|
+
* the response carries a refresh token and the session behaves exactly like
|
|
393
|
+
* a normal login (E72). `opts.provider` selects the provider by key.
|
|
394
|
+
*
|
|
395
|
+
* `opts.nonce` is the RAW nonce. Generate a random raw nonce, pass
|
|
396
|
+
* `sha256(raw)` (hex) to BOTH Apple's and Google's request and the **raw**
|
|
397
|
+
* value here (a token whose nonce claim equals the raw value is rejected).
|
|
398
|
+
* The provider must have `nonce`
|
|
399
|
+
* set to `optional` or `required`; `required` is meant for `cms` session mode
|
|
400
|
+
* (silent re-exchange through `externalTokenProvider` carries no nonce).
|
|
401
|
+
*/
|
|
402
|
+
async signInWithExternalToken(token, opts) {
|
|
403
|
+
const provider = opts?.provider ?? this.options.externalProvider;
|
|
404
|
+
const result = await this.exchange(token, provider, opts?.nonce);
|
|
405
|
+
await this.applyExchange(result, provider);
|
|
406
|
+
return { endUser: result.endUser, created: result.created };
|
|
407
|
+
}
|
|
408
|
+
/** The signed-in member as the server sees it (Bearer session); `linkedProviders` is filled here. */
|
|
409
|
+
async me() {
|
|
410
|
+
return this.http.request("GET", `${AUTH}/me`);
|
|
411
|
+
}
|
|
412
|
+
/** Attach an external identity to the signed-in member. `opts.nonce`: raw nonce; give the provider sha256(raw), see `signInWithExternalToken`. */
|
|
413
|
+
async linkExternal(token, opts) {
|
|
414
|
+
if (this.isAnonymous()) {
|
|
415
|
+
throw new ProblemError(409, {
|
|
416
|
+
status: 409,
|
|
417
|
+
title: "Upgrade required",
|
|
418
|
+
code: "UPGRADE_REQUIRED",
|
|
419
|
+
detail: "An anonymous end-user cannot link an identity; use auth.upgrade({ method: 'external', token })."
|
|
420
|
+
});
|
|
421
|
+
}
|
|
422
|
+
const provider = opts?.provider ?? this.options.externalProvider;
|
|
423
|
+
return this.http.request("POST", `${AUTH}/external/link`, {
|
|
424
|
+
body: { token, ...provider ? { provider } : {}, ...opts?.nonce ? { nonce: opts.nonce } : {} }
|
|
425
|
+
});
|
|
426
|
+
}
|
|
427
|
+
/** Detach external identities from the signed-in member (all, or only `opts.provider`). */
|
|
428
|
+
async unlinkExternal(opts) {
|
|
429
|
+
const query = opts?.provider ? `?provider=${encodeURIComponent(opts.provider)}` : "";
|
|
430
|
+
return this.http.request("DELETE", `${AUTH}/external/link${query}`);
|
|
431
|
+
}
|
|
432
|
+
/**
|
|
433
|
+
* QFK2-T322 — sign in as a new anonymous end-user (`POST /auth/anonymous`,
|
|
434
|
+
* attestation proof required). Idempotent: when a session already exists
|
|
435
|
+
* (anonymous, registered or external) it returns the current identity
|
|
436
|
+
* without a request. Concurrent calls share one request.
|
|
437
|
+
*/
|
|
438
|
+
async signInAnonymously() {
|
|
439
|
+
if (this.anonymousSigningIn) return this.anonymousSigningIn;
|
|
440
|
+
this.anonymousSigningIn = this.runSignInAnonymously().finally(() => {
|
|
441
|
+
this.anonymousSigningIn = null;
|
|
442
|
+
});
|
|
443
|
+
return this.anonymousSigningIn;
|
|
444
|
+
}
|
|
445
|
+
async runSignInAnonymously() {
|
|
446
|
+
if (this.isAuthenticated() || await this.hasExternalSession()) {
|
|
447
|
+
const claims2 = this.getClaims();
|
|
448
|
+
return { userId: claims2?.sub ?? null, isAnonymous: claims2?.anon === true, created: false, endUser: null };
|
|
449
|
+
}
|
|
450
|
+
const result = await this.http.request("POST", `${AUTH}/anonymous`, { anonymous: true });
|
|
451
|
+
await this.storeCmsTokens({
|
|
452
|
+
accessToken: result.accessToken,
|
|
453
|
+
refreshToken: result.refreshToken,
|
|
454
|
+
expiresIn: result.expiresIn
|
|
455
|
+
});
|
|
456
|
+
const claims = this.getClaims();
|
|
457
|
+
return {
|
|
458
|
+
userId: claims?.sub ?? result.endUser?.id ?? null,
|
|
459
|
+
isAnonymous: claims?.anon === true,
|
|
460
|
+
created: true,
|
|
461
|
+
endUser: result.endUser
|
|
462
|
+
};
|
|
463
|
+
}
|
|
464
|
+
/** QFK2-T322 — true when the current access token carries `anon: true`. */
|
|
465
|
+
isAnonymous() {
|
|
466
|
+
return this.getClaims()?.anon === true;
|
|
467
|
+
}
|
|
468
|
+
async upgrade(input) {
|
|
469
|
+
if (input.method === "magic_link") {
|
|
470
|
+
return this.http.request("POST", `${AUTH}/upgrade`, {
|
|
471
|
+
body: { method: "magic_link", email: input.email }
|
|
472
|
+
});
|
|
473
|
+
}
|
|
474
|
+
let body;
|
|
475
|
+
let provider;
|
|
476
|
+
if (input.method === "email") {
|
|
477
|
+
body = { method: "email", email: input.email, password: input.password };
|
|
478
|
+
} else {
|
|
479
|
+
provider = input.provider ?? this.options.externalProvider;
|
|
480
|
+
body = { method: "external", token: input.token, ...provider ? { provider } : {}, ...input.nonce ? { nonce: input.nonce } : {} };
|
|
481
|
+
}
|
|
482
|
+
const result = await this.http.request("POST", `${AUTH}/upgrade`, { body });
|
|
483
|
+
if (!result.accessToken) {
|
|
484
|
+
await this.endLocalSession(false);
|
|
485
|
+
return {
|
|
486
|
+
accessToken: "",
|
|
487
|
+
expiresIn: 0,
|
|
488
|
+
endUser: result.endUser,
|
|
489
|
+
verificationRequired: result.verificationRequired === true,
|
|
490
|
+
signedIn: false
|
|
491
|
+
};
|
|
492
|
+
}
|
|
493
|
+
const session = { ...result, accessToken: result.accessToken, expiresIn: result.expiresIn ?? 900 };
|
|
494
|
+
await this.applySession(session, provider);
|
|
495
|
+
return { ...session, signedIn: true };
|
|
496
|
+
}
|
|
497
|
+
/** QFK2-T322 — outcome of the last magic-link callback that carried `upgrade=`; null otherwise. */
|
|
498
|
+
getLastUpgradeOutcome() {
|
|
499
|
+
return this.lastUpgradeOutcome;
|
|
500
|
+
}
|
|
501
|
+
/**
|
|
502
|
+
* QFK2-T322 — delete the signed-in end-user's account (`DELETE /auth/me`,
|
|
503
|
+
* anonymous or registered) and clear the local session. On an error the
|
|
504
|
+
* session is kept and the `ProblemError` is thrown.
|
|
505
|
+
*/
|
|
506
|
+
async deleteAccount() {
|
|
507
|
+
await this.http.request("DELETE", `${AUTH}/me`);
|
|
508
|
+
await this.clearExternalMarker();
|
|
509
|
+
await this.endLocalSession(true);
|
|
510
|
+
}
|
|
511
|
+
/** Which sign-in options the project offers (`GET /auth/methods`, anonymous; cache-friendly). */
|
|
512
|
+
async methods() {
|
|
513
|
+
return this.http.request("GET", `${AUTH}/methods`, { anonymous: true });
|
|
514
|
+
}
|
|
515
|
+
/** Request a password-reset e-mail. Always resolves `{ ok: true }` for existing/unknown addresses alike. */
|
|
516
|
+
async requestPasswordReset(email) {
|
|
517
|
+
return this.http.request("POST", `${AUTH}/password-reset/request`, {
|
|
518
|
+
body: { email },
|
|
519
|
+
anonymous: true
|
|
520
|
+
});
|
|
521
|
+
}
|
|
522
|
+
/** Set a new password with the token from the reset e-mail. Does not sign in. */
|
|
523
|
+
async confirmPasswordReset(token, newPassword) {
|
|
524
|
+
return this.http.request("POST", `${AUTH}/password-reset/confirm`, {
|
|
525
|
+
body: { token, newPassword },
|
|
526
|
+
anonymous: true
|
|
527
|
+
});
|
|
528
|
+
}
|
|
529
|
+
async exchange(token, provider, nonce) {
|
|
530
|
+
return this.http.request("POST", `${AUTH}/external/exchange`, {
|
|
531
|
+
body: { token, ...provider ? { provider } : {}, ...nonce ? { nonce } : {} },
|
|
532
|
+
anonymous: true
|
|
533
|
+
});
|
|
534
|
+
}
|
|
535
|
+
/** Persist an exchange result: cms mode (refresh token) = normal login, else external session. */
|
|
536
|
+
async applyExchange(result, provider) {
|
|
537
|
+
await this.applySession(result, provider);
|
|
538
|
+
}
|
|
539
|
+
async applySession(result, provider) {
|
|
540
|
+
if (result.refreshToken) {
|
|
541
|
+
await this.storeCmsTokens({
|
|
542
|
+
accessToken: result.accessToken,
|
|
543
|
+
refreshToken: result.refreshToken,
|
|
544
|
+
expiresIn: result.expiresIn
|
|
545
|
+
});
|
|
546
|
+
return;
|
|
547
|
+
}
|
|
548
|
+
await this.options.storage?.setItem(STORAGE_KEY_EXTERNAL_SESSION, provider ?? EXTERNAL_MARKER_DEFAULT);
|
|
549
|
+
this.autoAnonymousArmed = false;
|
|
550
|
+
await this.store.setExternalAccess(result.accessToken, result.expiresIn);
|
|
551
|
+
await this.syncAnonymousMarker(false);
|
|
552
|
+
}
|
|
553
|
+
/** Keep the persisted anonymous-session marker in line with the session (writes only on change). */
|
|
554
|
+
async syncAnonymousMarker(anonymous) {
|
|
555
|
+
if (this.anonymousMarker === anonymous || !this.options.storage) return;
|
|
556
|
+
if (anonymous) await this.options.storage.setItem(STORAGE_KEY_ANONYMOUS_SESSION, "1");
|
|
557
|
+
else await this.options.storage.removeItem(STORAGE_KEY_ANONYMOUS_SESSION);
|
|
558
|
+
this.anonymousMarker = anonymous;
|
|
559
|
+
}
|
|
560
|
+
/** Whether the stored session is anonymous: the token claim, else (cold start) the persisted marker. */
|
|
561
|
+
async storedSessionIsAnonymous() {
|
|
562
|
+
if (this.isAnonymous()) return true;
|
|
563
|
+
if (this.anonymousMarker !== null || !this.options.storage) return this.anonymousMarker === true;
|
|
564
|
+
return await this.options.storage.getItem(STORAGE_KEY_ANONYMOUS_SESSION) === "1";
|
|
565
|
+
}
|
|
566
|
+
async hasExternalSession() {
|
|
567
|
+
if (!this.options.storage) return false;
|
|
568
|
+
return await this.options.storage.getItem(STORAGE_KEY_EXTERNAL_SESSION) !== null;
|
|
569
|
+
}
|
|
570
|
+
async clearExternalMarker() {
|
|
571
|
+
await this.options.storage?.removeItem(STORAGE_KEY_EXTERNAL_SESSION);
|
|
572
|
+
}
|
|
573
|
+
/** Re-exchange through the host's provider. Null = no session (and it is ended when the provider says so). */
|
|
574
|
+
async runExternalReExchange() {
|
|
575
|
+
const provider = this.options.externalTokenProvider;
|
|
576
|
+
const token = provider ? await provider() : null;
|
|
577
|
+
if (!token) {
|
|
578
|
+
await this.store.clear();
|
|
579
|
+
await this.clearExternalMarker();
|
|
580
|
+
return null;
|
|
581
|
+
}
|
|
582
|
+
try {
|
|
583
|
+
const marker = await this.options.storage?.getItem(STORAGE_KEY_EXTERNAL_SESSION);
|
|
584
|
+
const provider2 = marker && marker !== EXTERNAL_MARKER_DEFAULT ? marker : this.options.externalProvider;
|
|
585
|
+
const result = await this.exchange(token, provider2);
|
|
586
|
+
if (result.refreshToken) {
|
|
587
|
+
await this.applyExchange(result, provider2);
|
|
588
|
+
} else {
|
|
589
|
+
this.store.setAccessToken(result.accessToken, result.expiresIn);
|
|
590
|
+
}
|
|
591
|
+
return result.accessToken;
|
|
592
|
+
} catch (e) {
|
|
593
|
+
const code = e instanceof ProblemError ? e.raw.code : void 0;
|
|
594
|
+
if (code === "INVALID_EXTERNAL_TOKEN" || code === "IDENTITY_DEACTIVATED" || code === "ACCOUNT_DEACTIVATED") {
|
|
595
|
+
await this.store.clear();
|
|
596
|
+
await this.clearExternalMarker();
|
|
597
|
+
}
|
|
598
|
+
throw e;
|
|
599
|
+
}
|
|
600
|
+
}
|
|
601
|
+
/**
|
|
602
|
+
* Returns a valid access token, refreshing transparently when it is near
|
|
603
|
+
* expiry. Returns null when there is no session (anonymous). This is the
|
|
604
|
+
* function wired into `HttpClient.getAccessToken`.
|
|
605
|
+
*/
|
|
606
|
+
async getValidAccessToken() {
|
|
607
|
+
if (this.store.isAccessValid()) return this.store.getAccessToken();
|
|
608
|
+
if (this.store.getRefreshToken()) {
|
|
609
|
+
try {
|
|
610
|
+
return await this.refresh();
|
|
611
|
+
} catch {
|
|
612
|
+
return null;
|
|
613
|
+
}
|
|
614
|
+
}
|
|
615
|
+
if (await this.hasExternalSession()) {
|
|
616
|
+
try {
|
|
617
|
+
return await this.refresh();
|
|
618
|
+
} catch {
|
|
619
|
+
return null;
|
|
620
|
+
}
|
|
621
|
+
}
|
|
622
|
+
if (this.autoAnonymousArmed) return this.autoSignInAnonymously();
|
|
623
|
+
return null;
|
|
624
|
+
}
|
|
625
|
+
/** `anonymousAuth: 'auto'` lazy creation; a failure disarms it until the next logout. */
|
|
626
|
+
async autoSignInAnonymously() {
|
|
627
|
+
try {
|
|
628
|
+
await this.signInAnonymously();
|
|
629
|
+
return this.store.getAccessToken();
|
|
630
|
+
} catch {
|
|
631
|
+
return null;
|
|
632
|
+
} finally {
|
|
633
|
+
this.autoAnonymousArmed = false;
|
|
634
|
+
}
|
|
635
|
+
}
|
|
636
|
+
/**
|
|
637
|
+
* Local session end (no server call), shared by logout, deleteAccount, a lost
|
|
638
|
+
* anonymous identity and a verification-pending upgrade. `rearmAuto`: in
|
|
639
|
+
* `anonymousAuth: 'auto'` the next token need creates a new anonymous user.
|
|
640
|
+
*/
|
|
641
|
+
async endLocalSession(rearmAuto) {
|
|
642
|
+
this.lastUpgradeOutcome = null;
|
|
643
|
+
this.autoAnonymousArmed = rearmAuto && this.options.anonymousAuth === "auto";
|
|
644
|
+
await this.syncAnonymousMarker(false);
|
|
645
|
+
await this.store.clear();
|
|
646
|
+
}
|
|
647
|
+
/** Rotate the access token. De-duplicated: concurrent callers share one `/refresh`. */
|
|
648
|
+
async refresh() {
|
|
649
|
+
if (this.refreshing) return this.refreshing;
|
|
650
|
+
this.refreshing = this.runRefresh().finally(() => {
|
|
651
|
+
this.refreshing = null;
|
|
652
|
+
});
|
|
653
|
+
return this.refreshing;
|
|
654
|
+
}
|
|
655
|
+
async runRefresh(allowRotatedRetry = true) {
|
|
656
|
+
const refreshToken = this.store.getRefreshToken();
|
|
657
|
+
if (!refreshToken) return await this.hasExternalSession() ? this.runExternalReExchange() : null;
|
|
658
|
+
const wasAnonymous = this.isAnonymous();
|
|
659
|
+
let result;
|
|
660
|
+
try {
|
|
661
|
+
result = await this.http.request("POST", `${AUTH}/refresh`, {
|
|
662
|
+
body: { refreshToken },
|
|
663
|
+
anonymous: true
|
|
664
|
+
});
|
|
665
|
+
} catch (e) {
|
|
666
|
+
const code = e instanceof ProblemError && e.status === 401 ? e.raw.code : void 0;
|
|
667
|
+
if (code === "REFRESH_TOKEN_ROTATED" && allowRotatedRetry) {
|
|
668
|
+
await this.store.waitForRotation(refreshToken);
|
|
669
|
+
if (this.store.isAccessValid()) return this.store.getAccessToken();
|
|
670
|
+
if (!this.store.getRefreshToken()) return null;
|
|
671
|
+
return this.runRefresh(false);
|
|
672
|
+
}
|
|
673
|
+
if (code === "REFRESH_TOKEN_REUSED" && this.store.getRefreshToken() === refreshToken) {
|
|
674
|
+
await this.endLocalSession(true);
|
|
675
|
+
throw e;
|
|
676
|
+
}
|
|
677
|
+
if (isSessionRejected(e) && code !== "REFRESH_TOKEN_ROTATED" && this.store.getRefreshToken() === refreshToken && (wasAnonymous || await this.storedSessionIsAnonymous())) {
|
|
678
|
+
await this.endLocalSession(true);
|
|
679
|
+
}
|
|
680
|
+
throw e;
|
|
681
|
+
}
|
|
682
|
+
if (typeof result.refreshToken === "string" && result.refreshToken) {
|
|
683
|
+
await this.store.setTokens({
|
|
684
|
+
accessToken: result.accessToken,
|
|
685
|
+
refreshToken: result.refreshToken,
|
|
686
|
+
expiresIn: result.expiresIn
|
|
687
|
+
});
|
|
688
|
+
} else {
|
|
689
|
+
this.store.setAccessToken(result.accessToken, result.expiresIn);
|
|
690
|
+
}
|
|
691
|
+
await this.syncAnonymousMarker(this.isAnonymous());
|
|
692
|
+
return result.accessToken;
|
|
693
|
+
}
|
|
694
|
+
async logout() {
|
|
695
|
+
const refreshToken = this.store.getRefreshToken();
|
|
696
|
+
await this.clearExternalMarker();
|
|
697
|
+
if (refreshToken) {
|
|
698
|
+
try {
|
|
699
|
+
await this.http.request("POST", `${AUTH}/logout`, { body: { refreshToken }, anonymous: true });
|
|
700
|
+
} catch {
|
|
701
|
+
}
|
|
702
|
+
}
|
|
703
|
+
await this.endLocalSession(true);
|
|
704
|
+
}
|
|
705
|
+
async requestMagicLink(email) {
|
|
706
|
+
return this.http.request("POST", `${AUTH}/magic-link/request`, {
|
|
707
|
+
body: { email },
|
|
708
|
+
anonymous: true
|
|
709
|
+
});
|
|
710
|
+
}
|
|
711
|
+
/**
|
|
712
|
+
* Ask the backend to (re)send the account's verification e-mail. Only sends
|
|
713
|
+
* when the project enabled verification e-mails; always resolves `{ ok: true }`
|
|
714
|
+
* (no account enumeration).
|
|
715
|
+
*/
|
|
716
|
+
async requestEmailVerification(email) {
|
|
717
|
+
return this.http.request("POST", `${AUTH}/verify-email/request`, {
|
|
718
|
+
body: { email },
|
|
719
|
+
anonymous: true
|
|
720
|
+
});
|
|
721
|
+
}
|
|
722
|
+
/**
|
|
723
|
+
* Parse the deep-link the backend redirects to after a magic-link confirm
|
|
724
|
+
* (`…#access_token=&refresh_token=&expires_in=`), store the tokens, and
|
|
725
|
+
* return them. Returns null when the URL carries no token fragment. An
|
|
726
|
+
* `upgrade=upgraded|switched` parameter (anonymous upgrade, QFK2-T322) is
|
|
727
|
+
* exposed through `getLastUpgradeOutcome()`.
|
|
728
|
+
*/
|
|
729
|
+
async handleMagicLinkCallback(urlOrFragment) {
|
|
730
|
+
const hashIndex = urlOrFragment.indexOf("#");
|
|
731
|
+
const fragment = hashIndex >= 0 ? urlOrFragment.slice(hashIndex + 1) : urlOrFragment;
|
|
732
|
+
const params = new URLSearchParams(fragment);
|
|
733
|
+
const accessToken = params.get("access_token");
|
|
734
|
+
const refreshToken = params.get("refresh_token");
|
|
735
|
+
const expiresIn = params.get("expires_in");
|
|
736
|
+
if (!accessToken || !refreshToken) return null;
|
|
737
|
+
const tokens = {
|
|
738
|
+
accessToken,
|
|
739
|
+
refreshToken,
|
|
740
|
+
expiresIn: expiresIn ? parseInt(expiresIn, 10) : 900
|
|
741
|
+
};
|
|
742
|
+
const outcome = params.get("upgrade");
|
|
743
|
+
this.lastUpgradeOutcome = UPGRADE_OUTCOMES.find((o) => o === outcome) ?? null;
|
|
744
|
+
await this.storeCmsTokens(tokens);
|
|
745
|
+
return tokens;
|
|
746
|
+
}
|
|
747
|
+
/** Every CMS-token session replaces (and so ends) an external one. */
|
|
748
|
+
async storeCmsTokens(tokens) {
|
|
749
|
+
this.autoAnonymousArmed = false;
|
|
750
|
+
await this.store.setTokens(tokens);
|
|
751
|
+
await this.clearExternalMarker();
|
|
752
|
+
await this.syncAnonymousMarker(this.isAnonymous());
|
|
753
|
+
}
|
|
754
|
+
/** Decode the current access token's claims (project id, subject, …). */
|
|
755
|
+
getClaims() {
|
|
756
|
+
return decodeAccessToken(this.store.getAccessToken());
|
|
757
|
+
}
|
|
758
|
+
/**
|
|
759
|
+
* E54 — consumer-tier role ids carried by the current token (premium/special).
|
|
760
|
+
* Empty when anonymous or untiered. Use it to branch UI on tier; the backend
|
|
761
|
+
* still enforces what each tier can actually read/write.
|
|
762
|
+
*/
|
|
763
|
+
getRoles() {
|
|
764
|
+
return this.getClaims()?.roles ?? [];
|
|
765
|
+
}
|
|
766
|
+
isAuthenticated() {
|
|
767
|
+
return this.store.getAccessToken() !== null || this.store.getRefreshToken() !== null;
|
|
768
|
+
}
|
|
769
|
+
/** Subscribe to auth-state changes (login / refresh / logout). Returns unsubscribe. */
|
|
770
|
+
subscribe(listener) {
|
|
771
|
+
return this.store.subscribe(listener);
|
|
772
|
+
}
|
|
773
|
+
/**
|
|
774
|
+
* Reactive session snapshot for `useAuth`. Memoized on the store's version so
|
|
775
|
+
* the reference is stable between changes (safe for `useSyncExternalStore`).
|
|
776
|
+
*/
|
|
777
|
+
getAuthState() {
|
|
778
|
+
const version = this.store.getVersion();
|
|
779
|
+
if (this.authStateCache === null || version !== this.authStateVersion) {
|
|
780
|
+
const claims = this.getClaims();
|
|
781
|
+
this.authStateCache = {
|
|
782
|
+
isAuthenticated: this.isAuthenticated(),
|
|
783
|
+
userId: claims?.sub ?? null,
|
|
784
|
+
roles: claims?.roles ?? [],
|
|
785
|
+
isAnonymous: claims?.anon === true
|
|
786
|
+
};
|
|
787
|
+
this.authStateVersion = version;
|
|
788
|
+
}
|
|
789
|
+
return this.authStateCache;
|
|
790
|
+
}
|
|
791
|
+
};
|
|
792
|
+
|
|
793
|
+
// ../core/src/auth/token-store.ts
|
|
794
|
+
var TokenStore = class {
|
|
795
|
+
constructor(storage2, now2 = Date.now) {
|
|
796
|
+
__publicField(this, "storage", storage2);
|
|
797
|
+
__publicField(this, "now", now2);
|
|
798
|
+
__publicField(this, "accessToken", null);
|
|
799
|
+
__publicField(this, "accessExpiresAt", 0);
|
|
800
|
+
__publicField(this, "refreshToken", null);
|
|
801
|
+
__publicField(this, "version", 0);
|
|
802
|
+
__publicField(this, "listeners", /* @__PURE__ */ new Set());
|
|
803
|
+
/**
|
|
804
|
+
* QFK2-E73 — how long a `REFRESH_TOKEN_ROTATED` answer waits for another
|
|
805
|
+
* tab's successor token (storage write or a cross-tab sync `adopt`) before
|
|
806
|
+
* the single retry.
|
|
807
|
+
*/
|
|
808
|
+
__publicField(this, "rotationWaitMs", 2e3);
|
|
809
|
+
}
|
|
810
|
+
/** Load the persisted refresh token (call once at SDK init). */
|
|
811
|
+
async hydrate() {
|
|
812
|
+
this.refreshToken = await this.storage.getItem(STORAGE_KEY_REFRESH_TOKEN);
|
|
813
|
+
this.emit();
|
|
814
|
+
}
|
|
815
|
+
async setTokens(tokens) {
|
|
816
|
+
this.applyAccess(tokens.accessToken, tokens.expiresIn);
|
|
817
|
+
this.refreshToken = tokens.refreshToken;
|
|
818
|
+
await this.storage.setItem(STORAGE_KEY_REFRESH_TOKEN, tokens.refreshToken);
|
|
819
|
+
this.emit();
|
|
820
|
+
}
|
|
821
|
+
/** External session: access token only. Drops any CMS refresh token (memory + storage); one notification. */
|
|
822
|
+
async setExternalAccess(accessToken, expiresIn) {
|
|
823
|
+
await this.storage.removeItem(STORAGE_KEY_REFRESH_TOKEN);
|
|
824
|
+
this.refreshToken = null;
|
|
825
|
+
this.applyAccess(accessToken, expiresIn);
|
|
826
|
+
this.emit();
|
|
827
|
+
}
|
|
828
|
+
/**
|
|
829
|
+
* QFK2-E73 — re-read the persisted refresh token (another tab/process may
|
|
830
|
+
* have rotated it in shared storage). Emits only when it changed.
|
|
831
|
+
*/
|
|
832
|
+
async reload() {
|
|
833
|
+
const stored = await this.storage.getItem(STORAGE_KEY_REFRESH_TOKEN);
|
|
834
|
+
if (stored === this.refreshToken) return;
|
|
835
|
+
this.refreshToken = stored;
|
|
836
|
+
this.emit();
|
|
837
|
+
}
|
|
838
|
+
/**
|
|
839
|
+
* QFK2-E73 — take over a session state pushed by another tab (web
|
|
840
|
+
* BroadcastChannel sync): `null` = signed out there. Persists the refresh
|
|
841
|
+
* token like {@link setTokens}; one notification.
|
|
842
|
+
*/
|
|
843
|
+
async adopt(state) {
|
|
844
|
+
if (!state || !state.accessToken && !state.refreshToken) {
|
|
845
|
+
await this.clear();
|
|
846
|
+
return;
|
|
847
|
+
}
|
|
848
|
+
if (state.refreshToken) await this.storage.setItem(STORAGE_KEY_REFRESH_TOKEN, state.refreshToken);
|
|
849
|
+
else await this.storage.removeItem(STORAGE_KEY_REFRESH_TOKEN);
|
|
850
|
+
this.refreshToken = state.refreshToken;
|
|
851
|
+
this.accessToken = state.accessToken;
|
|
852
|
+
this.accessExpiresAt = state.accessToken ? state.accessExpiresAt : 0;
|
|
853
|
+
this.emit();
|
|
854
|
+
}
|
|
855
|
+
/**
|
|
856
|
+
* QFK2-E73 — resolve once the session moved past `staleRefreshToken`: the
|
|
857
|
+
* stored token changed (re-read first), or a valid access token arrived
|
|
858
|
+
* (another tab's sync), or the session ended. Gives up after
|
|
859
|
+
* {@link rotationWaitMs} (re-reading storage once more).
|
|
860
|
+
*/
|
|
861
|
+
async waitForRotation(staleRefreshToken) {
|
|
862
|
+
const moved = () => this.refreshToken !== staleRefreshToken || this.isAccessValid();
|
|
863
|
+
await this.reload();
|
|
864
|
+
if (moved()) return;
|
|
865
|
+
await new Promise((resolve) => {
|
|
866
|
+
let unsubscribe = () => {
|
|
867
|
+
};
|
|
868
|
+
const timer = setTimeout(() => {
|
|
869
|
+
unsubscribe();
|
|
870
|
+
resolve();
|
|
871
|
+
}, this.rotationWaitMs);
|
|
872
|
+
unsubscribe = this.subscribe(() => {
|
|
873
|
+
if (!moved()) return;
|
|
874
|
+
clearTimeout(timer);
|
|
875
|
+
unsubscribe();
|
|
876
|
+
resolve();
|
|
877
|
+
});
|
|
878
|
+
});
|
|
879
|
+
if (!moved()) await this.reload();
|
|
880
|
+
}
|
|
881
|
+
setAccessToken(accessToken, expiresIn) {
|
|
882
|
+
this.applyAccess(accessToken, expiresIn);
|
|
883
|
+
this.emit();
|
|
884
|
+
}
|
|
885
|
+
applyAccess(accessToken, expiresIn) {
|
|
886
|
+
this.accessToken = accessToken;
|
|
887
|
+
this.accessExpiresAt = this.now() + expiresIn * 1e3;
|
|
888
|
+
}
|
|
889
|
+
getAccessToken() {
|
|
890
|
+
return this.accessToken;
|
|
891
|
+
}
|
|
892
|
+
/** Epoch ms when the access token expires (0 = none). */
|
|
893
|
+
getAccessExpiresAt() {
|
|
894
|
+
return this.accessExpiresAt;
|
|
895
|
+
}
|
|
896
|
+
isAccessValid(marginMs = 3e4) {
|
|
897
|
+
return this.accessToken !== null && this.now() < this.accessExpiresAt - marginMs;
|
|
898
|
+
}
|
|
899
|
+
getRefreshToken() {
|
|
900
|
+
return this.refreshToken;
|
|
901
|
+
}
|
|
902
|
+
async clear() {
|
|
903
|
+
this.accessToken = null;
|
|
904
|
+
this.accessExpiresAt = 0;
|
|
905
|
+
this.refreshToken = null;
|
|
906
|
+
await this.storage.removeItem(STORAGE_KEY_REFRESH_TOKEN);
|
|
907
|
+
this.emit();
|
|
908
|
+
}
|
|
909
|
+
/** Observe auth-state changes. Returns an unsubscribe function. */
|
|
910
|
+
subscribe(listener) {
|
|
911
|
+
this.listeners.add(listener);
|
|
912
|
+
return () => {
|
|
913
|
+
this.listeners.delete(listener);
|
|
914
|
+
};
|
|
915
|
+
}
|
|
916
|
+
/** Monotonic change counter — bumps on every mutation. */
|
|
917
|
+
getVersion() {
|
|
918
|
+
return this.version;
|
|
919
|
+
}
|
|
920
|
+
emit() {
|
|
921
|
+
this.version += 1;
|
|
922
|
+
for (const listener of this.listeners) listener();
|
|
923
|
+
}
|
|
924
|
+
};
|
|
925
|
+
|
|
926
|
+
// ../core/src/content/filter-serialize.ts
|
|
927
|
+
function serializeFilter(filter) {
|
|
928
|
+
return JSON.stringify(filter);
|
|
929
|
+
}
|
|
930
|
+
|
|
931
|
+
// ../core/src/content/ContentClient.ts
|
|
932
|
+
function joinKeys(keys) {
|
|
933
|
+
if (keys === void 0) return void 0;
|
|
934
|
+
const list = (typeof keys === "string" ? keys.split(",") : keys).map((k) => k.trim()).filter(Boolean);
|
|
935
|
+
return list.length ? list.join(",") : void 0;
|
|
936
|
+
}
|
|
937
|
+
var ContentClient = class {
|
|
938
|
+
constructor(http, opts = {}) {
|
|
939
|
+
__publicField(this, "http", http);
|
|
940
|
+
__publicField(this, "opts", opts);
|
|
941
|
+
}
|
|
942
|
+
list(collection, params = {}) {
|
|
943
|
+
return this.http.request("GET", `/content/${collection}`, this.listOptions(params));
|
|
944
|
+
}
|
|
945
|
+
get(collection, id, params = {}) {
|
|
946
|
+
return this.http.request("GET", `/content/${collection}/${id}`, this.getOptions(params));
|
|
947
|
+
}
|
|
948
|
+
/**
|
|
949
|
+
* {@link list} as a conditional GET (QFK2-E59 D4): the identical request plus
|
|
950
|
+
* `If-None-Match` when `opts.ifNoneMatch` is set. Resolves
|
|
951
|
+
* `{ notModified: true }` on 304, otherwise the page and its ETag.
|
|
952
|
+
*/
|
|
953
|
+
listConditional(collection, params = {}, opts = {}) {
|
|
954
|
+
return this.http.requestConditional("GET", `/content/${collection}`, {
|
|
955
|
+
...this.listOptions(params),
|
|
956
|
+
ifNoneMatch: opts.ifNoneMatch
|
|
957
|
+
});
|
|
958
|
+
}
|
|
959
|
+
/** {@link get} as a conditional GET; see {@link listConditional}. */
|
|
960
|
+
getConditional(collection, id, params = {}, opts = {}) {
|
|
961
|
+
return this.http.requestConditional("GET", `/content/${collection}/${id}`, {
|
|
962
|
+
...this.getOptions(params),
|
|
963
|
+
ifNoneMatch: opts.ifNoneMatch
|
|
964
|
+
});
|
|
965
|
+
}
|
|
966
|
+
create(collection, data) {
|
|
967
|
+
return this.http.request("POST", `/content/${collection}`, {
|
|
968
|
+
body: data,
|
|
969
|
+
withUnlockTokens: true
|
|
970
|
+
});
|
|
971
|
+
}
|
|
972
|
+
update(collection, id, data) {
|
|
973
|
+
return this.http.request("PATCH", `/content/${collection}/${id}`, {
|
|
974
|
+
body: data,
|
|
975
|
+
withUnlockTokens: true
|
|
976
|
+
});
|
|
977
|
+
}
|
|
978
|
+
delete(collection, id) {
|
|
979
|
+
return this.http.request("DELETE", `/content/${collection}/${id}`, { withUnlockTokens: true });
|
|
980
|
+
}
|
|
981
|
+
/**
|
|
982
|
+
* Unlock a code-locked record (QFK2-E78). Wrong/unknown codes reject with a
|
|
983
|
+
* `ProblemError` (404 `LOOKUP_NOT_FOUND`, 400 `LOOKUP_BAD_REQUEST`, 429
|
|
984
|
+
* `LOOKUP_RATE_LIMITED`). On success the token is persisted and sent on every
|
|
985
|
+
* later content request.
|
|
986
|
+
*/
|
|
987
|
+
async lookup(collection, code, params = {}) {
|
|
988
|
+
const res = await this.http.request("POST", `/lookup/${collection}`, {
|
|
989
|
+
body: { code },
|
|
990
|
+
withUnlockTokens: true,
|
|
991
|
+
query: {
|
|
992
|
+
locale: this.resolveLocale(params.locale),
|
|
993
|
+
locale_fallback: this.resolveFallback(params.localeFallback),
|
|
994
|
+
expand: joinKeys(params.expand),
|
|
995
|
+
with_title: params.withTitle ? "true" : void 0
|
|
996
|
+
}
|
|
997
|
+
});
|
|
998
|
+
const id = res.data?.id;
|
|
999
|
+
if (this.opts.unlockTokens && typeof id === "string" && res.unlockToken) {
|
|
1000
|
+
await this.opts.unlockTokens.add(collection, id, res.unlockToken);
|
|
1001
|
+
}
|
|
1002
|
+
return res;
|
|
1003
|
+
}
|
|
1004
|
+
/** Forget all stored unlock tokens (e.g. on sign-out); locked rows lock again. */
|
|
1005
|
+
async clearUnlockTokens() {
|
|
1006
|
+
await this.opts.unlockTokens?.clear();
|
|
1007
|
+
}
|
|
1008
|
+
/** Subscribe to unlock-token changes (lookup / clear). Returns unsubscribe. */
|
|
1009
|
+
onUnlockChange(listener) {
|
|
1010
|
+
return this.opts.unlockTokens?.subscribe(listener) ?? (() => {
|
|
1011
|
+
});
|
|
1012
|
+
}
|
|
1013
|
+
/** Request options of a list read (shared by {@link list} and {@link listConditional}). */
|
|
1014
|
+
listOptions(params) {
|
|
1015
|
+
return {
|
|
1016
|
+
withUnlockTokens: true,
|
|
1017
|
+
query: {
|
|
1018
|
+
filter: params.filter ? serializeFilter(params.filter) : void 0,
|
|
1019
|
+
limit: params.limit,
|
|
1020
|
+
cursor: params.cursor,
|
|
1021
|
+
page: params.page,
|
|
1022
|
+
locale: this.resolveLocale(params.locale),
|
|
1023
|
+
locale_fallback: this.resolveFallback(params.localeFallback),
|
|
1024
|
+
sort: joinKeys(params.sort),
|
|
1025
|
+
expand: joinKeys(params.expand),
|
|
1026
|
+
with_title: params.withTitle ? "true" : void 0
|
|
1027
|
+
}
|
|
1028
|
+
};
|
|
1029
|
+
}
|
|
1030
|
+
/** Request options of a single-record read (shared by {@link get} and {@link getConditional}). */
|
|
1031
|
+
getOptions(params) {
|
|
1032
|
+
return {
|
|
1033
|
+
withUnlockTokens: true,
|
|
1034
|
+
query: {
|
|
1035
|
+
locale: this.resolveLocale(params.locale),
|
|
1036
|
+
locale_fallback: this.resolveFallback(params.localeFallback),
|
|
1037
|
+
expand: joinKeys(params.expand),
|
|
1038
|
+
with_title: params.withTitle ? "true" : void 0
|
|
1039
|
+
}
|
|
1040
|
+
};
|
|
1041
|
+
}
|
|
1042
|
+
/** Explicit param wins over the ambient locale; both absent → omit the query. */
|
|
1043
|
+
resolveLocale(explicit) {
|
|
1044
|
+
return explicit ?? this.opts.getLocale?.() ?? void 0;
|
|
1045
|
+
}
|
|
1046
|
+
/** Emit `locale_fallback=true` only when truthy; otherwise omit it. */
|
|
1047
|
+
resolveFallback(explicit) {
|
|
1048
|
+
return explicit ?? this.opts.getLocaleFallback?.() ? true : void 0;
|
|
1049
|
+
}
|
|
1050
|
+
};
|
|
1051
|
+
|
|
1052
|
+
// ../core/src/content/unlock-token-store.ts
|
|
1053
|
+
var MAX_TOKENS = 20;
|
|
1054
|
+
var UnlockTokenStore = class {
|
|
1055
|
+
constructor(storage2) {
|
|
1056
|
+
__publicField(this, "storage", storage2);
|
|
1057
|
+
__publicField(this, "entries", []);
|
|
1058
|
+
/** Serializes storage writes so the last persisted snapshot equals the in-memory state. */
|
|
1059
|
+
__publicField(this, "writeChain", Promise.resolve());
|
|
1060
|
+
__publicField(this, "listeners", /* @__PURE__ */ new Set());
|
|
1061
|
+
/** Memoized load: initialize(), getRequestHeaders(), add() and clear() share one read. */
|
|
1062
|
+
__publicField(this, "hydration", null);
|
|
1063
|
+
}
|
|
1064
|
+
/**
|
|
1065
|
+
* Load persisted tokens. Idempotent: every caller awaits the same read, so it
|
|
1066
|
+
* is safe from initialize() and from getRequestHeaders() before initialize().
|
|
1067
|
+
* Corrupt storage → empty.
|
|
1068
|
+
*/
|
|
1069
|
+
hydrate() {
|
|
1070
|
+
if (!this.hydration) this.hydration = this.load();
|
|
1071
|
+
return this.hydration;
|
|
1072
|
+
}
|
|
1073
|
+
async load() {
|
|
1074
|
+
try {
|
|
1075
|
+
const raw = await this.storage.getItem(STORAGE_KEY_UNLOCK_TOKENS);
|
|
1076
|
+
const parsed = raw ? JSON.parse(raw) : [];
|
|
1077
|
+
this.entries = Array.isArray(parsed) ? parsed.filter(
|
|
1078
|
+
(e) => !!e && typeof e.collection === "string" && typeof e.id === "string" && typeof e.token === "string"
|
|
1079
|
+
).slice(-MAX_TOKENS) : [];
|
|
1080
|
+
} catch {
|
|
1081
|
+
this.entries = [];
|
|
1082
|
+
}
|
|
1083
|
+
}
|
|
1084
|
+
/** Newest-last token list, as sent in `X-Unlock-Token`. */
|
|
1085
|
+
tokens() {
|
|
1086
|
+
return this.entries.map((e) => e.token);
|
|
1087
|
+
}
|
|
1088
|
+
async add(collection, id, token) {
|
|
1089
|
+
await this.hydrate();
|
|
1090
|
+
this.entries = [
|
|
1091
|
+
...this.entries.filter(
|
|
1092
|
+
(e) => !(e.collection === collection && e.id === id)
|
|
1093
|
+
),
|
|
1094
|
+
{ collection, id, token }
|
|
1095
|
+
].slice(-MAX_TOKENS);
|
|
1096
|
+
const snapshot = JSON.stringify(this.entries);
|
|
1097
|
+
await this.enqueue(
|
|
1098
|
+
() => this.storage.setItem(STORAGE_KEY_UNLOCK_TOKENS, snapshot)
|
|
1099
|
+
);
|
|
1100
|
+
this.emit();
|
|
1101
|
+
}
|
|
1102
|
+
async clear() {
|
|
1103
|
+
await this.hydrate();
|
|
1104
|
+
this.entries = [];
|
|
1105
|
+
await this.enqueue(
|
|
1106
|
+
() => this.storage.removeItem(STORAGE_KEY_UNLOCK_TOKENS)
|
|
1107
|
+
);
|
|
1108
|
+
this.emit();
|
|
1109
|
+
}
|
|
1110
|
+
subscribe(listener) {
|
|
1111
|
+
this.listeners.add(listener);
|
|
1112
|
+
return () => this.listeners.delete(listener);
|
|
1113
|
+
}
|
|
1114
|
+
enqueue(op) {
|
|
1115
|
+
const next = this.writeChain.then(op);
|
|
1116
|
+
this.writeChain = next.catch(() => void 0);
|
|
1117
|
+
return next;
|
|
1118
|
+
}
|
|
1119
|
+
emit() {
|
|
1120
|
+
for (const l of [...this.listeners]) l();
|
|
1121
|
+
}
|
|
1122
|
+
};
|
|
1123
|
+
|
|
1124
|
+
// ../core/src/sync/VersionPoller.ts
|
|
1125
|
+
var MIN_POLL_INTERVAL_MS = 3e4;
|
|
1126
|
+
var DEFAULT_POLL_INTERVAL_MS = 6e4;
|
|
1127
|
+
function resolvePollInterval(requested) {
|
|
1128
|
+
return Math.max(MIN_POLL_INTERVAL_MS, requested ?? DEFAULT_POLL_INTERVAL_MS);
|
|
1129
|
+
}
|
|
1130
|
+
var VersionPoller = class {
|
|
1131
|
+
constructor(opts) {
|
|
1132
|
+
__publicField(this, "opts", opts);
|
|
1133
|
+
__publicField(this, "intervalMs");
|
|
1134
|
+
__publicField(this, "timer", null);
|
|
1135
|
+
/** `start()` called and not yet `stop()`ped (survives background pauses). */
|
|
1136
|
+
__publicField(this, "wanted", false);
|
|
1137
|
+
__publicField(this, "appStateUnsub", null);
|
|
1138
|
+
this.intervalMs = resolvePollInterval(opts.intervalMs);
|
|
1139
|
+
}
|
|
1140
|
+
/** A tick is scheduled (not paused, not stopped). */
|
|
1141
|
+
get running() {
|
|
1142
|
+
return this.timer !== null;
|
|
1143
|
+
}
|
|
1144
|
+
/** Begin polling (first tick jittered). No-op while already running or in the background. */
|
|
1145
|
+
start() {
|
|
1146
|
+
this.wanted = true;
|
|
1147
|
+
if (this.opts.appState && this.opts.followAppState !== false && !this.appStateUnsub) {
|
|
1148
|
+
this.appStateUnsub = this.opts.appState.subscribe((active) => {
|
|
1149
|
+
if (!this.wanted) return;
|
|
1150
|
+
if (active) {
|
|
1151
|
+
void this.checkNow();
|
|
1152
|
+
this.schedule();
|
|
1153
|
+
} else {
|
|
1154
|
+
this.clear();
|
|
1155
|
+
}
|
|
1156
|
+
});
|
|
1157
|
+
}
|
|
1158
|
+
this.schedule();
|
|
1159
|
+
}
|
|
1160
|
+
/** Stop ticking and drop the app-state subscription. */
|
|
1161
|
+
stop() {
|
|
1162
|
+
this.wanted = false;
|
|
1163
|
+
this.appStateUnsub?.();
|
|
1164
|
+
this.appStateUnsub = null;
|
|
1165
|
+
this.clear();
|
|
1166
|
+
}
|
|
1167
|
+
/** Alias of {@link stop}. */
|
|
1168
|
+
dispose() {
|
|
1169
|
+
this.stop();
|
|
1170
|
+
}
|
|
1171
|
+
/** Run one check now (outside the cadence). Never rejects. */
|
|
1172
|
+
async checkNow() {
|
|
1173
|
+
try {
|
|
1174
|
+
await this.opts.check();
|
|
1175
|
+
} catch {
|
|
1176
|
+
}
|
|
1177
|
+
}
|
|
1178
|
+
isForeground() {
|
|
1179
|
+
return this.opts.appState ? this.opts.appState.isActive() : true;
|
|
1180
|
+
}
|
|
1181
|
+
schedule() {
|
|
1182
|
+
if (this.timer !== null || !this.isForeground()) return;
|
|
1183
|
+
const random = this.opts.random ?? Math.random;
|
|
1184
|
+
const firstDelay = Math.floor(random() * this.intervalMs);
|
|
1185
|
+
this.arm(firstDelay);
|
|
1186
|
+
}
|
|
1187
|
+
arm(delay) {
|
|
1188
|
+
const set = this.opts.setTimeout ?? ((fn, ms) => setTimeout(fn, ms));
|
|
1189
|
+
const handle = set(() => {
|
|
1190
|
+
if (this.timer !== handle) return;
|
|
1191
|
+
this.timer = null;
|
|
1192
|
+
this.arm(this.intervalMs);
|
|
1193
|
+
void this.checkNow();
|
|
1194
|
+
}, delay);
|
|
1195
|
+
this.timer = handle;
|
|
1196
|
+
handle?.unref?.();
|
|
1197
|
+
}
|
|
1198
|
+
clear() {
|
|
1199
|
+
if (this.timer === null) return;
|
|
1200
|
+
const clear = this.opts.clearTimeout ?? ((h) => clearTimeout(h));
|
|
1201
|
+
clear(this.timer);
|
|
1202
|
+
this.timer = null;
|
|
1203
|
+
}
|
|
1204
|
+
};
|
|
1205
|
+
|
|
1206
|
+
// ../core/src/sync/SseSupervisor.ts
|
|
1207
|
+
var SSE_RAPID_CLOSE_MS = 5e3;
|
|
1208
|
+
var SSE_MAX_RAPID_CLOSES = 3;
|
|
1209
|
+
var SSE_RECONNECT_BASE_MS = 1e3;
|
|
1210
|
+
var SSE_RECONNECT_MAX_MS = 8e3;
|
|
1211
|
+
var SSE_RECONNECT_JITTER = 0.3;
|
|
1212
|
+
var SSE_IDLE_TIMEOUT_MS = 6e4;
|
|
1213
|
+
var SseSupervisor = class {
|
|
1214
|
+
constructor(opts) {
|
|
1215
|
+
__publicField(this, "opts", opts);
|
|
1216
|
+
__publicField(this, "conn", null);
|
|
1217
|
+
/** Identity of the live connection; cleared on drop (also covers callbacks fired during connect). */
|
|
1218
|
+
__publicField(this, "token", null);
|
|
1219
|
+
/** Bumped by start/stop so in-flight opens and stale callbacks detect they were superseded. */
|
|
1220
|
+
__publicField(this, "epoch", 0);
|
|
1221
|
+
__publicField(this, "openedAt", 0);
|
|
1222
|
+
__publicField(this, "rapidCloses", 0);
|
|
1223
|
+
__publicField(this, "reconnectTimer", null);
|
|
1224
|
+
__publicField(this, "idleTimer", null);
|
|
1225
|
+
}
|
|
1226
|
+
/** A connection is currently open (or opening at the transport level). */
|
|
1227
|
+
get connected() {
|
|
1228
|
+
return this.token !== null;
|
|
1229
|
+
}
|
|
1230
|
+
/** (Re)open the channel: resets the rapid-close streak, replaces any current connection. */
|
|
1231
|
+
async start() {
|
|
1232
|
+
this.epoch += 1;
|
|
1233
|
+
this.clearReconnect();
|
|
1234
|
+
this.rapidCloses = 0;
|
|
1235
|
+
await this.open(this.epoch);
|
|
1236
|
+
}
|
|
1237
|
+
/** Close the channel and silence every pending callback / reconnect. */
|
|
1238
|
+
stop() {
|
|
1239
|
+
this.epoch += 1;
|
|
1240
|
+
this.clearReconnect();
|
|
1241
|
+
this.rapidCloses = 0;
|
|
1242
|
+
this.dropConnection();
|
|
1243
|
+
}
|
|
1244
|
+
now() {
|
|
1245
|
+
return (this.opts.now ?? Date.now)();
|
|
1246
|
+
}
|
|
1247
|
+
set(fn, ms) {
|
|
1248
|
+
const handle = (this.opts.setTimeout ?? ((f, t) => setTimeout(f, t)))(fn, ms);
|
|
1249
|
+
handle?.unref?.();
|
|
1250
|
+
return handle;
|
|
1251
|
+
}
|
|
1252
|
+
clear(handle) {
|
|
1253
|
+
(this.opts.clearTimeout ?? ((h) => clearTimeout(h)))(handle);
|
|
1254
|
+
}
|
|
1255
|
+
/** (Re)arm the idle watchdog of the current connection; it reopens the channel when it fires. */
|
|
1256
|
+
armIdle(epoch, token) {
|
|
1257
|
+
if (this.idleTimer !== null) this.clear(this.idleTimer);
|
|
1258
|
+
this.idleTimer = this.set(() => {
|
|
1259
|
+
this.idleTimer = null;
|
|
1260
|
+
if (epoch !== this.epoch || this.token !== token) return;
|
|
1261
|
+
this.dropConnection();
|
|
1262
|
+
this.rapidCloses = 0;
|
|
1263
|
+
void this.open(epoch);
|
|
1264
|
+
}, SSE_IDLE_TIMEOUT_MS);
|
|
1265
|
+
}
|
|
1266
|
+
async open(epoch) {
|
|
1267
|
+
let headers = {};
|
|
1268
|
+
try {
|
|
1269
|
+
headers = await this.opts.headers?.() ?? {};
|
|
1270
|
+
} catch {
|
|
1271
|
+
if (epoch === this.epoch) this.opts.onFallback();
|
|
1272
|
+
return;
|
|
1273
|
+
}
|
|
1274
|
+
if (epoch !== this.epoch) return;
|
|
1275
|
+
this.dropConnection();
|
|
1276
|
+
this.openedAt = this.now();
|
|
1277
|
+
const token = {};
|
|
1278
|
+
this.token = token;
|
|
1279
|
+
const isCurrent = () => epoch === this.epoch && this.token === token;
|
|
1280
|
+
this.armIdle(epoch, token);
|
|
1281
|
+
const conn = this.opts.connectSse(this.opts.url(), headers, {
|
|
1282
|
+
onMessage: (event) => {
|
|
1283
|
+
if (!isCurrent()) return;
|
|
1284
|
+
this.armIdle(epoch, token);
|
|
1285
|
+
this.opts.onMessage(event);
|
|
1286
|
+
},
|
|
1287
|
+
onError: () => {
|
|
1288
|
+
if (!isCurrent()) return;
|
|
1289
|
+
this.dropConnection();
|
|
1290
|
+
this.opts.onFallback();
|
|
1291
|
+
},
|
|
1292
|
+
onClose: (info) => {
|
|
1293
|
+
if (!isCurrent()) return;
|
|
1294
|
+
this.dropConnection();
|
|
1295
|
+
if (info?.reason === "recycle") {
|
|
1296
|
+
this.rapidCloses = 0;
|
|
1297
|
+
void this.open(epoch);
|
|
1298
|
+
return;
|
|
1299
|
+
}
|
|
1300
|
+
if (this.now() - this.openedAt >= SSE_RAPID_CLOSE_MS) this.rapidCloses = 0;
|
|
1301
|
+
this.rapidCloses += 1;
|
|
1302
|
+
if (this.rapidCloses >= SSE_MAX_RAPID_CLOSES) {
|
|
1303
|
+
this.opts.onFallback();
|
|
1304
|
+
return;
|
|
1305
|
+
}
|
|
1306
|
+
const base = Math.min(SSE_RECONNECT_MAX_MS, SSE_RECONNECT_BASE_MS * 2 ** (this.rapidCloses - 1));
|
|
1307
|
+
const random = this.opts.random ?? Math.random;
|
|
1308
|
+
const delay = Math.round(base * (1 - SSE_RECONNECT_JITTER + 2 * SSE_RECONNECT_JITTER * random()));
|
|
1309
|
+
this.clearReconnect();
|
|
1310
|
+
this.reconnectTimer = this.set(() => {
|
|
1311
|
+
this.reconnectTimer = null;
|
|
1312
|
+
if (epoch !== this.epoch) return;
|
|
1313
|
+
void this.open(epoch);
|
|
1314
|
+
}, delay);
|
|
1315
|
+
}
|
|
1316
|
+
});
|
|
1317
|
+
if (this.token === token) this.conn = conn;
|
|
1318
|
+
else conn.close();
|
|
1319
|
+
}
|
|
1320
|
+
dropConnection() {
|
|
1321
|
+
const conn = this.conn;
|
|
1322
|
+
if (this.idleTimer !== null) this.clear(this.idleTimer);
|
|
1323
|
+
this.idleTimer = null;
|
|
1324
|
+
this.token = null;
|
|
1325
|
+
this.conn = null;
|
|
1326
|
+
conn?.close();
|
|
1327
|
+
}
|
|
1328
|
+
clearReconnect() {
|
|
1329
|
+
if (this.reconnectTimer === null) return;
|
|
1330
|
+
this.clear(this.reconnectTimer);
|
|
1331
|
+
this.reconnectTimer = null;
|
|
1332
|
+
}
|
|
1333
|
+
};
|
|
1334
|
+
|
|
1335
|
+
// ../core/src/config-sync/ConfigSyncClient.ts
|
|
1336
|
+
function isVersionEvent(event) {
|
|
1337
|
+
return typeof event === "object" && event !== null && typeof event.version === "number";
|
|
1338
|
+
}
|
|
1339
|
+
var ConfigSyncClient = class {
|
|
1340
|
+
constructor(opts) {
|
|
1341
|
+
__publicField(this, "opts", opts);
|
|
1342
|
+
__publicField(this, "data");
|
|
1343
|
+
__publicField(this, "version", 0);
|
|
1344
|
+
__publicField(this, "listeners", /* @__PURE__ */ new Set());
|
|
1345
|
+
__publicField(this, "stopped", false);
|
|
1346
|
+
__publicField(this, "appStateUnsub", null);
|
|
1347
|
+
/** Polling fallback; this client drives pause/resume itself (SSE and polling share AppState). */
|
|
1348
|
+
__publicField(this, "poller");
|
|
1349
|
+
__publicField(this, "sse");
|
|
1350
|
+
this.data = opts.buildTimeDefault;
|
|
1351
|
+
this.version = opts.buildTimeVersion ?? 0;
|
|
1352
|
+
this.poller = new VersionPoller({
|
|
1353
|
+
check: () => this.pollOnce(),
|
|
1354
|
+
intervalMs: opts.pollIntervalMs,
|
|
1355
|
+
appState: opts.appState,
|
|
1356
|
+
followAppState: false,
|
|
1357
|
+
random: opts.random
|
|
1358
|
+
});
|
|
1359
|
+
const connectSse = opts.connectSse;
|
|
1360
|
+
this.sse = connectSse ? new SseSupervisor({
|
|
1361
|
+
connectSse,
|
|
1362
|
+
url: () => `${opts.apiUrl.replace(/\/$/, "")}${END_USER_BASE_PATH}/config/${opts.domain}/watch`,
|
|
1363
|
+
headers: () => {
|
|
1364
|
+
const h = opts.headers;
|
|
1365
|
+
return (typeof h === "function" ? h() : h) ?? {};
|
|
1366
|
+
},
|
|
1367
|
+
onMessage: (event) => {
|
|
1368
|
+
if (isVersionEvent(event) && event.version > this.version) {
|
|
1369
|
+
void this.fetchAndApply({ emit: true });
|
|
1370
|
+
}
|
|
1371
|
+
},
|
|
1372
|
+
// Error, header failure or repeated immediate closes → poll.
|
|
1373
|
+
onFallback: () => this.startPolling(),
|
|
1374
|
+
random: opts.random
|
|
1375
|
+
}) : null;
|
|
1376
|
+
}
|
|
1377
|
+
/** Latest known config (build-time default until `start()` resolves). */
|
|
1378
|
+
current() {
|
|
1379
|
+
return this.data;
|
|
1380
|
+
}
|
|
1381
|
+
subscribe(listener) {
|
|
1382
|
+
this.listeners.add(listener);
|
|
1383
|
+
return () => this.listeners.delete(listener);
|
|
1384
|
+
}
|
|
1385
|
+
async start() {
|
|
1386
|
+
this.stopped = false;
|
|
1387
|
+
await this.hydrateFromCache();
|
|
1388
|
+
if (this.version === 0) {
|
|
1389
|
+
await this.fetchAndApply({ emit: false, force: true });
|
|
1390
|
+
} else {
|
|
1391
|
+
await this.pollOnce();
|
|
1392
|
+
}
|
|
1393
|
+
await this.beginSync();
|
|
1394
|
+
if (this.opts.appState) {
|
|
1395
|
+
this.appStateUnsub = this.opts.appState.subscribe((active) => {
|
|
1396
|
+
if (this.stopped) return;
|
|
1397
|
+
if (active) {
|
|
1398
|
+
void this.beginSync();
|
|
1399
|
+
void this.pollOnce();
|
|
1400
|
+
} else {
|
|
1401
|
+
this.pauseSync();
|
|
1402
|
+
}
|
|
1403
|
+
});
|
|
1404
|
+
}
|
|
1405
|
+
}
|
|
1406
|
+
stop() {
|
|
1407
|
+
this.stopped = true;
|
|
1408
|
+
this.appStateUnsub?.();
|
|
1409
|
+
this.appStateUnsub = null;
|
|
1410
|
+
this.pauseSync();
|
|
1411
|
+
}
|
|
1412
|
+
// --- sync lifecycle (paused/resumed by AppState) ------------------------
|
|
1413
|
+
/** Open the live channel: SSE if configured, otherwise polling. */
|
|
1414
|
+
async beginSync() {
|
|
1415
|
+
if (!this.sse) {
|
|
1416
|
+
this.startPolling();
|
|
1417
|
+
return;
|
|
1418
|
+
}
|
|
1419
|
+
await this.sse.start();
|
|
1420
|
+
}
|
|
1421
|
+
/** Tear the live channel down without ending the client (background). */
|
|
1422
|
+
pauseSync() {
|
|
1423
|
+
this.sse?.stop();
|
|
1424
|
+
this.poller.stop();
|
|
1425
|
+
}
|
|
1426
|
+
// --- internals ----------------------------------------------------------
|
|
1427
|
+
cacheKey() {
|
|
1428
|
+
return `${STORAGE_KEY_CONFIG_PREFIX}${this.opts.domain}`;
|
|
1429
|
+
}
|
|
1430
|
+
async hydrateFromCache() {
|
|
1431
|
+
const raw = await this.opts.storage.getItem(this.cacheKey());
|
|
1432
|
+
if (!raw) return;
|
|
1433
|
+
try {
|
|
1434
|
+
const cached = JSON.parse(raw);
|
|
1435
|
+
if (cached && typeof cached.version === "number" && cached.version > this.version) {
|
|
1436
|
+
this.version = cached.version;
|
|
1437
|
+
this.data = cached.data;
|
|
1438
|
+
}
|
|
1439
|
+
} catch {
|
|
1440
|
+
}
|
|
1441
|
+
}
|
|
1442
|
+
async fetchAndApply({ emit, force }) {
|
|
1443
|
+
let snapshot;
|
|
1444
|
+
try {
|
|
1445
|
+
snapshot = await this.opts.http.request("GET", `/config/${this.opts.domain}`);
|
|
1446
|
+
} catch {
|
|
1447
|
+
return;
|
|
1448
|
+
}
|
|
1449
|
+
if (!force && snapshot.version <= this.version) return;
|
|
1450
|
+
this.version = snapshot.version;
|
|
1451
|
+
this.data = snapshot.data;
|
|
1452
|
+
await this.opts.storage.setItem(this.cacheKey(), JSON.stringify(snapshot));
|
|
1453
|
+
if (emit) this.emit();
|
|
1454
|
+
}
|
|
1455
|
+
emit() {
|
|
1456
|
+
for (const listener of this.listeners) listener(this.data);
|
|
1457
|
+
}
|
|
1458
|
+
/**
|
|
1459
|
+
* One poll cycle: probe the cheap `/version` endpoint and only pull the full
|
|
1460
|
+
* snapshot when the version actually advanced (E56). This keeps a 60s poll
|
|
1461
|
+
* from re-downloading an unchanged KB-sized payload every tick.
|
|
1462
|
+
*/
|
|
1463
|
+
async pollOnce() {
|
|
1464
|
+
let result;
|
|
1465
|
+
try {
|
|
1466
|
+
result = await this.opts.http.request(
|
|
1467
|
+
"GET",
|
|
1468
|
+
`/config/${this.opts.domain}/version`
|
|
1469
|
+
);
|
|
1470
|
+
} catch {
|
|
1471
|
+
return;
|
|
1472
|
+
}
|
|
1473
|
+
if (typeof result?.version === "number" && result.version > this.version) {
|
|
1474
|
+
await this.fetchAndApply({ emit: true });
|
|
1475
|
+
}
|
|
1476
|
+
}
|
|
1477
|
+
startPolling() {
|
|
1478
|
+
if (this.stopped) return;
|
|
1479
|
+
this.poller.start();
|
|
1480
|
+
}
|
|
1481
|
+
};
|
|
1482
|
+
|
|
1483
|
+
// ../core/src/i18n/LanguageManager.ts
|
|
1484
|
+
var DEFAULT_LOCALES = { defaultLocale: "en", locales: ["en"] };
|
|
1485
|
+
var DEFAULT_I18N = { translations: {} };
|
|
1486
|
+
var LanguageManager = class {
|
|
1487
|
+
constructor(deps) {
|
|
1488
|
+
__publicField(this, "deps", deps);
|
|
1489
|
+
/** null until the user picks (or `hydrate` restores) a locale; falls back to default. */
|
|
1490
|
+
__publicField(this, "locale", null);
|
|
1491
|
+
__publicField(this, "locales", DEFAULT_LOCALES);
|
|
1492
|
+
__publicField(this, "i18n", DEFAULT_I18N);
|
|
1493
|
+
__publicField(this, "listeners", /* @__PURE__ */ new Set());
|
|
1494
|
+
/** Monotonic change counter — the `useSyncExternalStore` snapshot for the React hooks. */
|
|
1495
|
+
__publicField(this, "revision", 0);
|
|
1496
|
+
}
|
|
1497
|
+
/** Snapshot for `useSyncExternalStore`: bumps on every locale / data change. */
|
|
1498
|
+
getRevision() {
|
|
1499
|
+
return this.revision;
|
|
1500
|
+
}
|
|
1501
|
+
/** The active locale, or the project default until one is chosen. */
|
|
1502
|
+
getLanguage() {
|
|
1503
|
+
return this.locale ?? this.locales.defaultLocale;
|
|
1504
|
+
}
|
|
1505
|
+
getDefaultLocale() {
|
|
1506
|
+
return this.locales.defaultLocale;
|
|
1507
|
+
}
|
|
1508
|
+
getAvailableLocales() {
|
|
1509
|
+
return this.locales.locales;
|
|
1510
|
+
}
|
|
1511
|
+
/** Switch the active locale: update state, persist, and notify subscribers. */
|
|
1512
|
+
async setLanguage(locale) {
|
|
1513
|
+
this.locale = locale;
|
|
1514
|
+
await this.deps.storage.setItem(STORAGE_KEY_LOCALE, locale);
|
|
1515
|
+
this.emit();
|
|
1516
|
+
}
|
|
1517
|
+
/**
|
|
1518
|
+
* Resolve a UI string. Lookup order: active locale → default locale → the key
|
|
1519
|
+
* itself (so a missing translation degrades to a visible-but-stable token).
|
|
1520
|
+
*/
|
|
1521
|
+
t(key, params) {
|
|
1522
|
+
const tables = this.i18n.translations;
|
|
1523
|
+
const raw = tables[this.getLanguage()]?.[key] ?? tables[this.locales.defaultLocale]?.[key] ?? key;
|
|
1524
|
+
return params ? interpolate(raw, params) : raw;
|
|
1525
|
+
}
|
|
1526
|
+
subscribe(listener) {
|
|
1527
|
+
this.listeners.add(listener);
|
|
1528
|
+
return () => {
|
|
1529
|
+
this.listeners.delete(listener);
|
|
1530
|
+
};
|
|
1531
|
+
}
|
|
1532
|
+
/** Config-sync seam: the `locales` domain snapshot landed. */
|
|
1533
|
+
applyLocales(data) {
|
|
1534
|
+
this.locales = data;
|
|
1535
|
+
this.emit();
|
|
1536
|
+
}
|
|
1537
|
+
/** Config-sync seam: the `i18n` domain snapshot landed. */
|
|
1538
|
+
applyI18n(data) {
|
|
1539
|
+
this.i18n = data;
|
|
1540
|
+
this.emit();
|
|
1541
|
+
}
|
|
1542
|
+
/** Restore the persisted locale (call once at boot, after storage is ready). */
|
|
1543
|
+
async hydrate() {
|
|
1544
|
+
const stored = await this.deps.storage.getItem(STORAGE_KEY_LOCALE);
|
|
1545
|
+
if (stored) this.locale = stored;
|
|
1546
|
+
}
|
|
1547
|
+
emit() {
|
|
1548
|
+
this.revision++;
|
|
1549
|
+
for (const listener of this.listeners) listener();
|
|
1550
|
+
}
|
|
1551
|
+
};
|
|
1552
|
+
function interpolate(template, params) {
|
|
1553
|
+
let out = template;
|
|
1554
|
+
for (const [key, value] of Object.entries(params)) {
|
|
1555
|
+
out = out.replace(
|
|
1556
|
+
new RegExp(`{{\\s*${escapeRegExp(key)}\\s*}}`, "g"),
|
|
1557
|
+
String(value)
|
|
1558
|
+
);
|
|
1559
|
+
}
|
|
1560
|
+
return out;
|
|
1561
|
+
}
|
|
1562
|
+
function escapeRegExp(s) {
|
|
1563
|
+
return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
1564
|
+
}
|
|
1565
|
+
|
|
1566
|
+
// ../core/src/content-sync/versions.ts
|
|
1567
|
+
var enc = encodeURIComponent;
|
|
1568
|
+
async function fetchContentVersions(request, collections) {
|
|
1569
|
+
if (!collections.length) return {};
|
|
1570
|
+
const res = await request(`/content-changes/version?collections=${collections.map(enc).join(",")}`);
|
|
1571
|
+
const out = {};
|
|
1572
|
+
for (const c of collections) {
|
|
1573
|
+
const v = res?.[c];
|
|
1574
|
+
if (typeof v === "string" || typeof v === "number") out[c] = String(v);
|
|
1575
|
+
}
|
|
1576
|
+
return out;
|
|
1577
|
+
}
|
|
1578
|
+
|
|
1579
|
+
// ../core/src/core/client.ts
|
|
1580
|
+
var CONTENT_VERSION_GATE_DEFAULT_MAX_AGE_MS = 24 * 60 * 60 * 1e3;
|
|
1581
|
+
function resolveContentVersionGate(option) {
|
|
1582
|
+
if (!option) return null;
|
|
1583
|
+
const ms = option === true ? void 0 : option.maxAgeMs;
|
|
1584
|
+
const valid = typeof ms === "number" && Number.isFinite(ms) && ms > 0;
|
|
1585
|
+
return { maxAgeMs: valid ? ms : CONTENT_VERSION_GATE_DEFAULT_MAX_AGE_MS };
|
|
1586
|
+
}
|
|
1587
|
+
function validateCoreConfig(config) {
|
|
1588
|
+
const hasProjectId = typeof config.projectId === "string" && config.projectId !== "";
|
|
1589
|
+
if (config.publishableKey === void 0 && !hasProjectId) {
|
|
1590
|
+
throw new Error("QafkaCMS: projectId is required (or a publishableKey qpk_\u2026)");
|
|
1591
|
+
}
|
|
1592
|
+
if (config.publishableKey !== void 0) {
|
|
1593
|
+
if (typeof config.publishableKey !== "string" || !config.publishableKey.startsWith("qpk_")) {
|
|
1594
|
+
throw new Error("publishableKey is required (qpk_\u2026)");
|
|
1595
|
+
}
|
|
1596
|
+
}
|
|
1597
|
+
}
|
|
1598
|
+
function createCoreClient(config, platform, internals = {}) {
|
|
1599
|
+
validateCoreConfig(config);
|
|
1600
|
+
if (!config.apiUrl) throw new Error("QafkaCMS: apiUrl is required");
|
|
1601
|
+
const apiUrl = config.apiUrl;
|
|
1602
|
+
const projectId = config.projectId ? config.projectId : void 0;
|
|
1603
|
+
const now2 = platform.now ?? Date.now;
|
|
1604
|
+
const sessionStorage = platform.sessionStorage;
|
|
1605
|
+
const storage2 = platform.cacheStorage ?? sessionStorage;
|
|
1606
|
+
const proof = platform.proof;
|
|
1607
|
+
const anonymousAuth = config.anonymousAuth === "auto" ? "auto" : "manual";
|
|
1608
|
+
const full = config.tier === "full";
|
|
1609
|
+
let auth;
|
|
1610
|
+
let language;
|
|
1611
|
+
const unlockTokens = new UnlockTokenStore(sessionStorage);
|
|
1612
|
+
const http = new HttpClient(
|
|
1613
|
+
{
|
|
1614
|
+
apiUrl,
|
|
1615
|
+
projectSlug: config.projectSlug,
|
|
1616
|
+
publishableKey: config.publishableKey,
|
|
1617
|
+
projectId,
|
|
1618
|
+
platformOS: platform.os,
|
|
1619
|
+
appVersion: config.appVersion
|
|
1620
|
+
},
|
|
1621
|
+
{
|
|
1622
|
+
fetch: platform.fetch,
|
|
1623
|
+
proof,
|
|
1624
|
+
getAccessToken: () => auth.getValidAccessToken(),
|
|
1625
|
+
getLocale: () => language?.getLanguage() || null,
|
|
1626
|
+
getUnlockTokens: () => unlockTokens.tokens()
|
|
1627
|
+
}
|
|
1628
|
+
);
|
|
1629
|
+
const tokenStore = internals.tokenStore ?? new TokenStore(sessionStorage, now2);
|
|
1630
|
+
auth = new AuthClient(http, tokenStore, now2, {
|
|
1631
|
+
externalTokenProvider: config.externalTokenProvider,
|
|
1632
|
+
externalProvider: config.externalProvider,
|
|
1633
|
+
storage: sessionStorage,
|
|
1634
|
+
anonymousAuth
|
|
1635
|
+
});
|
|
1636
|
+
const createConfigSync = (domain, buildTimeDefault, options) => new ConfigSyncClient({
|
|
1637
|
+
domain,
|
|
1638
|
+
buildTimeDefault,
|
|
1639
|
+
buildTimeVersion: options?.buildTimeVersion,
|
|
1640
|
+
apiUrl,
|
|
1641
|
+
http: { request: (method, path) => http.request(method, path) },
|
|
1642
|
+
storage: storage2,
|
|
1643
|
+
// SSE is opt-in; without it ConfigSyncClient polls.
|
|
1644
|
+
connectSse: options?.live ? platform.connectSse : void 0,
|
|
1645
|
+
headers: () => http.securityHeaders(),
|
|
1646
|
+
pollIntervalMs: options?.pollIntervalMs,
|
|
1647
|
+
appState: platform.appState
|
|
1648
|
+
});
|
|
1649
|
+
let localesSync = null;
|
|
1650
|
+
let i18nSync = null;
|
|
1651
|
+
if (full) {
|
|
1652
|
+
language = new LanguageManager({ storage: storage2 });
|
|
1653
|
+
const poll = config.configPollIntervalMs;
|
|
1654
|
+
const bootstrap = config.bootstrap;
|
|
1655
|
+
localesSync = createConfigSync(
|
|
1656
|
+
"locales",
|
|
1657
|
+
bootstrap?.locales?.data ?? { defaultLocale: "en", locales: ["en"] },
|
|
1658
|
+
{ pollIntervalMs: poll, buildTimeVersion: bootstrap?.locales?.version }
|
|
1659
|
+
);
|
|
1660
|
+
i18nSync = createConfigSync(
|
|
1661
|
+
"i18n",
|
|
1662
|
+
bootstrap?.i18n?.data ?? { translations: { en: {} } },
|
|
1663
|
+
{ pollIntervalMs: poll, buildTimeVersion: bootstrap?.i18n?.version }
|
|
1664
|
+
);
|
|
1665
|
+
}
|
|
1666
|
+
const content = new ContentClient(http, {
|
|
1667
|
+
getLocale: () => language?.getLanguage() || null,
|
|
1668
|
+
unlockTokens
|
|
1669
|
+
});
|
|
1670
|
+
let hub;
|
|
1671
|
+
let warnedNoHub = false;
|
|
1672
|
+
const request = (path) => http.request("GET", path);
|
|
1673
|
+
const contentChanges = {
|
|
1674
|
+
watch: (target, mode, opts) => {
|
|
1675
|
+
if (!internals.contentHub) {
|
|
1676
|
+
if (!warnedNoHub) platform.warn?.("[QafkaCMS] live content is not enabled on this client; `live` is ignored");
|
|
1677
|
+
warnedNoHub = true;
|
|
1678
|
+
return () => {
|
|
1679
|
+
};
|
|
1680
|
+
}
|
|
1681
|
+
return (hub ?? (hub = internals.contentHub({
|
|
1682
|
+
apiUrl,
|
|
1683
|
+
request,
|
|
1684
|
+
headers: () => http.securityHeaders(),
|
|
1685
|
+
connectSse: platform.contentSse ?? platform.connectSse,
|
|
1686
|
+
appState: platform.appState,
|
|
1687
|
+
warn: platform.warn
|
|
1688
|
+
}))).watch(target, mode ?? config.contentLiveDefault ?? "auto", opts);
|
|
1689
|
+
},
|
|
1690
|
+
status: () => hub?.status() ?? "idle",
|
|
1691
|
+
reset: () => hub?.reset(),
|
|
1692
|
+
dispose: () => hub?.dispose(),
|
|
1693
|
+
// QFK2-E59 D7 — a plain GET: needs neither a watch nor the hub.
|
|
1694
|
+
versions: (collections) => fetchContentVersions(request, collections)
|
|
1695
|
+
};
|
|
1696
|
+
const initialize = async () => {
|
|
1697
|
+
await tokenStore.hydrate();
|
|
1698
|
+
await unlockTokens.hydrate();
|
|
1699
|
+
await proof.initialize?.();
|
|
1700
|
+
if (!tokenStore.getRefreshToken()) await auth.getValidAccessToken().catch(() => null);
|
|
1701
|
+
const extraStarts = internals.configStarts ?? (() => []);
|
|
1702
|
+
if (language && localesSync && i18nSync) {
|
|
1703
|
+
const lang = language;
|
|
1704
|
+
const locales = localesSync;
|
|
1705
|
+
const i18n = i18nSync;
|
|
1706
|
+
await lang.hydrate();
|
|
1707
|
+
locales.subscribe((data) => lang.applyLocales(data));
|
|
1708
|
+
i18n.subscribe((data) => lang.applyI18n(data));
|
|
1709
|
+
await Promise.all([locales.start(), i18n.start(), ...extraStarts()]);
|
|
1710
|
+
lang.applyLocales(locales.current());
|
|
1711
|
+
lang.applyI18n(i18n.current());
|
|
1712
|
+
} else {
|
|
1713
|
+
await Promise.all(extraStarts());
|
|
1714
|
+
}
|
|
1715
|
+
if (anonymousAuth === "auto" && !auth.isAuthenticated()) {
|
|
1716
|
+
await auth.signInAnonymously().catch((err) => {
|
|
1717
|
+
platform.warn?.("[QafkaCMS] anonymous sign-in (anonymousAuth: 'auto') failed", err);
|
|
1718
|
+
});
|
|
1719
|
+
}
|
|
1720
|
+
};
|
|
1721
|
+
const getRequestHeaders = async (options = {}) => {
|
|
1722
|
+
await Promise.all([proof.initialize?.(), unlockTokens.hydrate()]);
|
|
1723
|
+
const headers = await http.projectProofHeaders({ withProjectKey: true });
|
|
1724
|
+
if (options.withUnlockTokens !== false) {
|
|
1725
|
+
const unlock = unlockTokens.tokens();
|
|
1726
|
+
if (unlock.length) headers["X-Unlock-Token"] = unlock.join(",");
|
|
1727
|
+
}
|
|
1728
|
+
if (http.appVersion) headers["X-App-Version"] = http.appVersion;
|
|
1729
|
+
return headers;
|
|
1730
|
+
};
|
|
1731
|
+
const bundle = internals.contentBundle?.({
|
|
1732
|
+
...config.contentBundle,
|
|
1733
|
+
apiUrl,
|
|
1734
|
+
http,
|
|
1735
|
+
platform,
|
|
1736
|
+
language
|
|
1737
|
+
});
|
|
1738
|
+
return {
|
|
1739
|
+
auth,
|
|
1740
|
+
content,
|
|
1741
|
+
storage: storage2,
|
|
1742
|
+
cacheStorage: storage2,
|
|
1743
|
+
language,
|
|
1744
|
+
bundle,
|
|
1745
|
+
http,
|
|
1746
|
+
proof,
|
|
1747
|
+
contentChanges,
|
|
1748
|
+
contentVersionGate: resolveContentVersionGate(config.contentVersionGate),
|
|
1749
|
+
appVersion: http.appVersion,
|
|
1750
|
+
initialize,
|
|
1751
|
+
getRequestHeaders,
|
|
1752
|
+
createConfigSync
|
|
1753
|
+
};
|
|
1754
|
+
}
|
|
1755
|
+
|
|
1756
|
+
// ../core/src/cache/duration.ts
|
|
1757
|
+
var UNIT_MS = {
|
|
1758
|
+
ms: 1,
|
|
1759
|
+
s: 1e3,
|
|
1760
|
+
m: 6e4,
|
|
1761
|
+
h: 36e5,
|
|
1762
|
+
d: 864e5
|
|
1763
|
+
};
|
|
1764
|
+
function parseDuration(value) {
|
|
1765
|
+
if (value == null) return null;
|
|
1766
|
+
if (typeof value === "number") {
|
|
1767
|
+
if (!Number.isFinite(value) || value < 0) {
|
|
1768
|
+
throw new Error(`QafkaCMS: invalid duration ${value} (expected a non-negative number of ms)`);
|
|
1769
|
+
}
|
|
1770
|
+
return value;
|
|
1771
|
+
}
|
|
1772
|
+
const match = /^(\d+(?:\.\d+)?)\s*(ms|s|m|h|d)?$/.exec(value.trim());
|
|
1773
|
+
if (!match) {
|
|
1774
|
+
throw new Error(`QafkaCMS: invalid duration "${value}" (use e.g. 500, '30s', '10m', '1h', '2d')`);
|
|
1775
|
+
}
|
|
1776
|
+
const amount = parseFloat(match[1]);
|
|
1777
|
+
const unit = match[2] ?? "ms";
|
|
1778
|
+
return amount * UNIT_MS[unit];
|
|
1779
|
+
}
|
|
1780
|
+
|
|
1781
|
+
// ../core/src/cache/query-key.ts
|
|
1782
|
+
function serializeKey(key) {
|
|
1783
|
+
return typeof key === "string" ? key : stableStringify(key);
|
|
1784
|
+
}
|
|
1785
|
+
function stableStringify(value) {
|
|
1786
|
+
if (value === void 0) return "null";
|
|
1787
|
+
if (value === null || typeof value !== "object") return JSON.stringify(value) ?? "null";
|
|
1788
|
+
if (Array.isArray(value)) return `[${value.map(stableStringify).join(",")}]`;
|
|
1789
|
+
const obj = value;
|
|
1790
|
+
const parts = Object.keys(obj).filter((k) => obj[k] !== void 0).sort().map((k) => `${JSON.stringify(k)}:${stableStringify(obj[k])}`);
|
|
1791
|
+
return `{${parts.join(",")}}`;
|
|
1792
|
+
}
|
|
1793
|
+
|
|
1794
|
+
// ../core/src/cache/conditional.ts
|
|
1795
|
+
var BRAND = /* @__PURE__ */ Symbol.for("@qafka/cms.conditional");
|
|
1796
|
+
var conditional = {
|
|
1797
|
+
/** The server confirmed the cached data is current (HTTP 304). */
|
|
1798
|
+
notModified() {
|
|
1799
|
+
return { [BRAND]: true, notModified: true };
|
|
1800
|
+
},
|
|
1801
|
+
/** A full response and its ETag (`null` when the server sent none). */
|
|
1802
|
+
data(data, etag) {
|
|
1803
|
+
return { [BRAND]: true, notModified: false, data, etag };
|
|
1804
|
+
},
|
|
1805
|
+
/** Brand a transport {@link ConditionalResponse}. */
|
|
1806
|
+
from(res) {
|
|
1807
|
+
return res.notModified ? conditional.notModified() : conditional.data(res.data, res.etag);
|
|
1808
|
+
}
|
|
1809
|
+
};
|
|
1810
|
+
function isConditionalResult(value) {
|
|
1811
|
+
return typeof value === "object" && value !== null && value[BRAND] === true;
|
|
1812
|
+
}
|
|
1813
|
+
|
|
1814
|
+
// ../core/src/cache/version-gate.ts
|
|
1815
|
+
var VERSION_GATE_BATCH_MS = 10;
|
|
1816
|
+
var VERSION_GATE_MAX_SLUGS = 20;
|
|
1817
|
+
function createVersionBatcher(check) {
|
|
1818
|
+
const disabled = /* @__PURE__ */ new Set();
|
|
1819
|
+
let queue = null;
|
|
1820
|
+
const ask = async (slugs) => {
|
|
1821
|
+
try {
|
|
1822
|
+
const res = await check(slugs);
|
|
1823
|
+
return slugs.map((s) => {
|
|
1824
|
+
const v = res?.[s];
|
|
1825
|
+
return typeof v === "string" || typeof v === "number" ? String(v) : null;
|
|
1826
|
+
});
|
|
1827
|
+
} catch (err) {
|
|
1828
|
+
if (err?.status !== 404) return slugs.map(() => null);
|
|
1829
|
+
if (slugs.length > 1) return Promise.all(slugs.map(async (s) => (await ask([s]))[0]));
|
|
1830
|
+
disabled.add(slugs[0]);
|
|
1831
|
+
return [null];
|
|
1832
|
+
}
|
|
1833
|
+
};
|
|
1834
|
+
const flush = (batch) => {
|
|
1835
|
+
queue = null;
|
|
1836
|
+
const slugs = [...batch.keys()];
|
|
1837
|
+
for (let i = 0; i < slugs.length; i += VERSION_GATE_MAX_SLUGS) {
|
|
1838
|
+
const part = slugs.slice(i, i + VERSION_GATE_MAX_SLUGS);
|
|
1839
|
+
void ask(part).then((vs) => part.forEach((s, j) => batch.get(s).forEach((resolve) => resolve(vs[j]))));
|
|
1840
|
+
}
|
|
1841
|
+
};
|
|
1842
|
+
return {
|
|
1843
|
+
get: (slug) => disabled.has(slug) ? Promise.resolve(null) : new Promise((resolve) => {
|
|
1844
|
+
if (!queue) {
|
|
1845
|
+
const batch = queue = /* @__PURE__ */ new Map();
|
|
1846
|
+
setTimeout(() => flush(batch), VERSION_GATE_BATCH_MS);
|
|
1847
|
+
}
|
|
1848
|
+
const waiting = queue.get(slug);
|
|
1849
|
+
if (waiting) waiting.push(resolve);
|
|
1850
|
+
else queue.set(slug, [resolve]);
|
|
1851
|
+
}),
|
|
1852
|
+
isDisabled: (slug) => disabled.has(slug)
|
|
1853
|
+
};
|
|
1854
|
+
}
|
|
1855
|
+
|
|
1856
|
+
// ../core/src/cache/QueryCache.ts
|
|
1857
|
+
var IDLE_SNAPSHOT = Object.freeze({
|
|
1858
|
+
data: void 0,
|
|
1859
|
+
error: void 0,
|
|
1860
|
+
status: "idle",
|
|
1861
|
+
isLoading: false,
|
|
1862
|
+
isFetching: false,
|
|
1863
|
+
isStale: true,
|
|
1864
|
+
updatedAt: null
|
|
1865
|
+
});
|
|
1866
|
+
var PERSIST_WARNING = "[QafkaCMS] A query requested `persist: true` but this QueryCache has no `storage`: it works in memory only and will not survive a restart.";
|
|
1867
|
+
var QueryCache = class {
|
|
1868
|
+
constructor(options = {}) {
|
|
1869
|
+
__publicField(this, "entries", /* @__PURE__ */ new Map());
|
|
1870
|
+
__publicField(this, "persistedKeys", /* @__PURE__ */ new Set());
|
|
1871
|
+
/** Loads the persisted key index once (keys written in earlier sessions). */
|
|
1872
|
+
__publicField(this, "indexLoad", null);
|
|
1873
|
+
/** Serialized index writes, so a slower earlier write cannot overwrite a newer one. */
|
|
1874
|
+
__publicField(this, "indexWrite", Promise.resolve());
|
|
1875
|
+
/** Pending delayed refetches (one per serialized key). */
|
|
1876
|
+
__publicField(this, "delayed", /* @__PURE__ */ new Map());
|
|
1877
|
+
__publicField(this, "storage");
|
|
1878
|
+
__publicField(this, "now");
|
|
1879
|
+
__publicField(this, "defaultTtl");
|
|
1880
|
+
__publicField(this, "onError");
|
|
1881
|
+
__publicField(this, "warnedNoStorage", false);
|
|
1882
|
+
__publicField(this, "warn");
|
|
1883
|
+
__publicField(this, "versions");
|
|
1884
|
+
__publicField(this, "gateMaxAgeMs");
|
|
1885
|
+
__publicField(this, "appVersion");
|
|
1886
|
+
/** Normalized form of {@link appVersion} (`1.4` = `1.4.0`); `'null'` when none. */
|
|
1887
|
+
__publicField(this, "appVersionKey");
|
|
1888
|
+
this.storage = options.storage;
|
|
1889
|
+
this.now = options.now ?? Date.now;
|
|
1890
|
+
this.defaultTtl = parseDuration(options.defaultTtl ?? null);
|
|
1891
|
+
this.onError = options.onError;
|
|
1892
|
+
this.warn = options.warn;
|
|
1893
|
+
const gate = options.versionGate;
|
|
1894
|
+
this.versions = gate ? createVersionBatcher(gate.check) : null;
|
|
1895
|
+
this.gateMaxAgeMs = gate?.maxAgeMs ?? 0;
|
|
1896
|
+
this.appVersion = validAppVersion(options.appVersion);
|
|
1897
|
+
this.appVersionKey = String(parseAppVersion(this.appVersion));
|
|
1898
|
+
}
|
|
1899
|
+
// --- reactivity ---------------------------------------------------------
|
|
1900
|
+
/** Current immutable view for a key. Stable reference between changes. */
|
|
1901
|
+
getSnapshot(key) {
|
|
1902
|
+
const entry = this.entries.get(serializeKey(key));
|
|
1903
|
+
return entry ? entry.snapshot : IDLE_SNAPSHOT;
|
|
1904
|
+
}
|
|
1905
|
+
/** Subscribe to changes for a key. Returns an unsubscribe function. */
|
|
1906
|
+
subscribe(key, listener) {
|
|
1907
|
+
const entry = this.getOrCreate(serializeKey(key));
|
|
1908
|
+
entry.listeners.add(listener);
|
|
1909
|
+
return () => {
|
|
1910
|
+
entry.listeners.delete(listener);
|
|
1911
|
+
};
|
|
1912
|
+
}
|
|
1913
|
+
// --- read / fetch -------------------------------------------------------
|
|
1914
|
+
/**
|
|
1915
|
+
* Ensure data for `key` is loading or loaded. Hydrates from persistence
|
|
1916
|
+
* first, returns immediately if fresh, otherwise fetches (deduped). The
|
|
1917
|
+
* returned promise resolves once the work settles; data is read via state.
|
|
1918
|
+
*/
|
|
1919
|
+
async ensure(key, fetcher, options) {
|
|
1920
|
+
const sk = serializeKey(key);
|
|
1921
|
+
const entry = this.getOrCreate(sk);
|
|
1922
|
+
entry.fetcher = fetcher;
|
|
1923
|
+
this.applyOptions(entry, options);
|
|
1924
|
+
await this.maybeHydrate(entry, sk);
|
|
1925
|
+
if (entry.data !== void 0 && !this.isStale(entry)) return;
|
|
1926
|
+
return this.runFetch(entry, sk, true);
|
|
1927
|
+
}
|
|
1928
|
+
/** Boot/warm-up prefetch — same semantics as {@link ensure}, no subscriber required. */
|
|
1929
|
+
prefetch(key, fetcher, options) {
|
|
1930
|
+
return this.ensure(key, fetcher, options);
|
|
1931
|
+
}
|
|
1932
|
+
/** Force a refetch regardless of freshness (background revalidate over existing data). */
|
|
1933
|
+
refetch(key, fetcher) {
|
|
1934
|
+
const sk = serializeKey(key);
|
|
1935
|
+
const entry = this.entries.get(sk);
|
|
1936
|
+
if (!entry) return Promise.resolve();
|
|
1937
|
+
if (fetcher) entry.fetcher = fetcher;
|
|
1938
|
+
if (!entry.fetcher) return Promise.resolve();
|
|
1939
|
+
entry.epoch += 1;
|
|
1940
|
+
entry.promise = null;
|
|
1941
|
+
return this.runFetch(entry, sk);
|
|
1942
|
+
}
|
|
1943
|
+
/**
|
|
1944
|
+
* Refetch every entry that currently has subscribers — used after an identity
|
|
1945
|
+
* change so mounted screens reload with the new session. Entries with no
|
|
1946
|
+
* listeners are left untouched (they refetch on their next mount).
|
|
1947
|
+
*/
|
|
1948
|
+
refetchActive() {
|
|
1949
|
+
for (const [sk, entry] of this.entries) {
|
|
1950
|
+
if (entry.listeners.size > 0 && entry.fetcher) {
|
|
1951
|
+
entry.epoch += 1;
|
|
1952
|
+
entry.promise = null;
|
|
1953
|
+
void this.runFetch(entry, sk);
|
|
1954
|
+
}
|
|
1955
|
+
}
|
|
1956
|
+
}
|
|
1957
|
+
// --- mutation / invalidation -------------------------------------------
|
|
1958
|
+
/**
|
|
1959
|
+
* Mark a key stale and, if it has active subscribers, revalidate it — now, or
|
|
1960
|
+
* after `opts.delayMs`. An entry without subscribers is only marked stale.
|
|
1961
|
+
*/
|
|
1962
|
+
invalidate(key, opts) {
|
|
1963
|
+
const sk = serializeKey(key);
|
|
1964
|
+
const entry = this.entries.get(sk);
|
|
1965
|
+
if (entry) this.invalidateEntry(entry, sk, opts?.delayMs);
|
|
1966
|
+
}
|
|
1967
|
+
/** Invalidate every key whose serialized form matches `predicate`. */
|
|
1968
|
+
invalidateWhere(predicate) {
|
|
1969
|
+
for (const [sk, entry] of this.entries) {
|
|
1970
|
+
if (predicate(sk)) this.invalidateEntry(entry, sk);
|
|
1971
|
+
}
|
|
1972
|
+
}
|
|
1973
|
+
/**
|
|
1974
|
+
* Invalidate every key that has `prefix` as a leading segment (react-query
|
|
1975
|
+
* style). `invalidateByPrefix(['content', 'posts'])` refreshes every cached
|
|
1976
|
+
* `content.list('posts', …)` regardless of params; a string prefix matches
|
|
1977
|
+
* that exact key.
|
|
1978
|
+
*/
|
|
1979
|
+
invalidateByPrefix(prefix, opts) {
|
|
1980
|
+
const matches = prefixMatcher(prefix);
|
|
1981
|
+
for (const [sk, entry] of this.entries) {
|
|
1982
|
+
if (matches(sk)) this.invalidateEntry(entry, sk, opts?.delayMs);
|
|
1983
|
+
}
|
|
1984
|
+
}
|
|
1985
|
+
/**
|
|
1986
|
+
* Whether any entry matching `prefix` (same matching as
|
|
1987
|
+
* {@link invalidateByPrefix}) currently has subscribers, i.e. is on screen.
|
|
1988
|
+
*/
|
|
1989
|
+
hasActive(prefix) {
|
|
1990
|
+
const matches = prefixMatcher(prefix);
|
|
1991
|
+
for (const [sk, entry] of this.entries) {
|
|
1992
|
+
if (entry.listeners.size > 0 && matches(sk)) return true;
|
|
1993
|
+
}
|
|
1994
|
+
return false;
|
|
1995
|
+
}
|
|
1996
|
+
/**
|
|
1997
|
+
* Write data directly (optimistic update); cancels any in-flight fetch. The
|
|
1998
|
+
* ETag is dropped: the written data is not the server's representation.
|
|
1999
|
+
*/
|
|
2000
|
+
setData(key, data) {
|
|
2001
|
+
const sk = serializeKey(key);
|
|
2002
|
+
const entry = this.getOrCreate(sk);
|
|
2003
|
+
entry.epoch += 1;
|
|
2004
|
+
entry.promise = null;
|
|
2005
|
+
entry.data = data;
|
|
2006
|
+
entry.etag = null;
|
|
2007
|
+
entry.gate = null;
|
|
2008
|
+
entry.error = void 0;
|
|
2009
|
+
entry.status = "success";
|
|
2010
|
+
entry.savedAt = this.now();
|
|
2011
|
+
void this.maybePersist(entry, sk);
|
|
2012
|
+
this.touch(entry);
|
|
2013
|
+
}
|
|
2014
|
+
/**
|
|
2015
|
+
* Reset every entry to idle and drop persisted copies. Call on logout so a
|
|
2016
|
+
* previous user's visible set cannot leak. Does NOT auto-refetch — mounted
|
|
2017
|
+
* screens re-fetch on their next mount.
|
|
2018
|
+
*/
|
|
2019
|
+
async clear() {
|
|
2020
|
+
for (const timer of this.delayed.values()) clearTimeout(timer);
|
|
2021
|
+
this.delayed.clear();
|
|
2022
|
+
for (const [, entry] of this.entries) {
|
|
2023
|
+
entry.epoch += 1;
|
|
2024
|
+
entry.promise = null;
|
|
2025
|
+
entry.data = void 0;
|
|
2026
|
+
entry.etag = null;
|
|
2027
|
+
entry.gate = null;
|
|
2028
|
+
entry.error = void 0;
|
|
2029
|
+
entry.status = "idle";
|
|
2030
|
+
entry.savedAt = null;
|
|
2031
|
+
entry.isFetching = false;
|
|
2032
|
+
entry.hydrated = true;
|
|
2033
|
+
this.touch(entry);
|
|
2034
|
+
}
|
|
2035
|
+
if (!this.storage) return;
|
|
2036
|
+
await this.loadIndex();
|
|
2037
|
+
await this.indexWrite;
|
|
2038
|
+
const keys = [...this.persistedKeys];
|
|
2039
|
+
this.persistedKeys.clear();
|
|
2040
|
+
try {
|
|
2041
|
+
await this.storage.multiRemove([...keys, STORAGE_KEY_QUERY_INDEX]);
|
|
2042
|
+
} catch {
|
|
2043
|
+
}
|
|
2044
|
+
}
|
|
2045
|
+
// --- internals ----------------------------------------------------------
|
|
2046
|
+
getOrCreate(sk) {
|
|
2047
|
+
let entry = this.entries.get(sk);
|
|
2048
|
+
if (!entry) {
|
|
2049
|
+
entry = {
|
|
2050
|
+
status: "idle",
|
|
2051
|
+
data: void 0,
|
|
2052
|
+
error: void 0,
|
|
2053
|
+
savedAt: null,
|
|
2054
|
+
ttl: this.defaultTtl,
|
|
2055
|
+
isFetching: false,
|
|
2056
|
+
persist: false,
|
|
2057
|
+
promise: null,
|
|
2058
|
+
fetcher: null,
|
|
2059
|
+
etag: null,
|
|
2060
|
+
gateSlug: null,
|
|
2061
|
+
gate: null,
|
|
2062
|
+
epoch: 0,
|
|
2063
|
+
hydrated: false,
|
|
2064
|
+
snapshot: IDLE_SNAPSHOT,
|
|
2065
|
+
listeners: /* @__PURE__ */ new Set()
|
|
2066
|
+
};
|
|
2067
|
+
this.entries.set(sk, entry);
|
|
2068
|
+
}
|
|
2069
|
+
return entry;
|
|
2070
|
+
}
|
|
2071
|
+
applyOptions(entry, options) {
|
|
2072
|
+
if (!options) return;
|
|
2073
|
+
if (options.ttl !== void 0) entry.ttl = parseDuration(options.ttl);
|
|
2074
|
+
if (options.persist !== void 0) entry.persist = options.persist;
|
|
2075
|
+
if (options.gate !== void 0) entry.gateSlug = options.gate || null;
|
|
2076
|
+
}
|
|
2077
|
+
isStale(entry) {
|
|
2078
|
+
if (entry.savedAt == null) return true;
|
|
2079
|
+
if (entry.ttl == null) return true;
|
|
2080
|
+
return this.now() - entry.savedAt >= entry.ttl;
|
|
2081
|
+
}
|
|
2082
|
+
/**
|
|
2083
|
+
* Fetch (deduped). `gated` = reached through `ensure`: a version-gated entry
|
|
2084
|
+
* whose version is unchanged may skip the fetcher (QFK2-E59 D8). Forced
|
|
2085
|
+
* paths (`invalidate*`, `refetch*`) always fetch, still recording the version.
|
|
2086
|
+
*/
|
|
2087
|
+
runFetch(entry, sk, gated = false) {
|
|
2088
|
+
if (entry.promise) return entry.promise;
|
|
2089
|
+
const fetcher = entry.fetcher;
|
|
2090
|
+
if (!fetcher) return Promise.resolve();
|
|
2091
|
+
const myEpoch = entry.epoch;
|
|
2092
|
+
entry.isFetching = true;
|
|
2093
|
+
if (entry.data === void 0) entry.status = "loading";
|
|
2094
|
+
this.touch(entry);
|
|
2095
|
+
const promise = (async () => {
|
|
2096
|
+
try {
|
|
2097
|
+
const slug = this.gateSlugOf(entry);
|
|
2098
|
+
const version = slug ? await this.versions.get(slug) : null;
|
|
2099
|
+
if (entry.epoch !== myEpoch) return;
|
|
2100
|
+
if (gated && version !== null && this.gateHolds(entry, version)) {
|
|
2101
|
+
entry.error = void 0;
|
|
2102
|
+
entry.status = "success";
|
|
2103
|
+
entry.savedAt = this.now();
|
|
2104
|
+
await this.maybePersist(entry, sk);
|
|
2105
|
+
return;
|
|
2106
|
+
}
|
|
2107
|
+
const ctx = { etag: entry.data !== void 0 ? entry.etag : null };
|
|
2108
|
+
const result = await fetcher(ctx);
|
|
2109
|
+
if (entry.epoch !== myEpoch) return;
|
|
2110
|
+
this.applyResult(entry, result);
|
|
2111
|
+
entry.gate = version !== null ? { v: version, validatedAt: entry.savedAt } : null;
|
|
2112
|
+
await this.maybePersist(entry, sk);
|
|
2113
|
+
} catch (err) {
|
|
2114
|
+
if (entry.epoch !== myEpoch) return;
|
|
2115
|
+
const error = err instanceof Error ? err : new Error(String(err));
|
|
2116
|
+
entry.error = error;
|
|
2117
|
+
entry.status = entry.data !== void 0 ? "success" : "error";
|
|
2118
|
+
this.onError?.(error, sk);
|
|
2119
|
+
} finally {
|
|
2120
|
+
if (entry.epoch === myEpoch) {
|
|
2121
|
+
entry.isFetching = false;
|
|
2122
|
+
entry.promise = null;
|
|
2123
|
+
this.touch(entry);
|
|
2124
|
+
} else if (entry.promise === null) {
|
|
2125
|
+
entry.isFetching = false;
|
|
2126
|
+
this.touch(entry);
|
|
2127
|
+
}
|
|
2128
|
+
}
|
|
2129
|
+
})();
|
|
2130
|
+
entry.promise = promise;
|
|
2131
|
+
return promise;
|
|
2132
|
+
}
|
|
2133
|
+
/**
|
|
2134
|
+
* Store a fetcher result (QFK2-E59 D5). Branded `notModified` keeps the data
|
|
2135
|
+
* (same object) and ETag and only refreshes the timestamp; branded data
|
|
2136
|
+
* stores data + ETag; a plain value is today's behavior with no ETag.
|
|
2137
|
+
*/
|
|
2138
|
+
applyResult(entry, result) {
|
|
2139
|
+
if (isConditionalResult(result)) {
|
|
2140
|
+
if (result.notModified) {
|
|
2141
|
+
if (entry.data === void 0) throw new Error("QafkaCMS: not-modified result for a query with no cached data");
|
|
2142
|
+
} else {
|
|
2143
|
+
entry.data = result.data;
|
|
2144
|
+
entry.etag = result.etag;
|
|
2145
|
+
}
|
|
2146
|
+
} else {
|
|
2147
|
+
entry.data = result;
|
|
2148
|
+
entry.etag = null;
|
|
2149
|
+
}
|
|
2150
|
+
entry.error = void 0;
|
|
2151
|
+
entry.status = "success";
|
|
2152
|
+
entry.savedAt = this.now();
|
|
2153
|
+
}
|
|
2154
|
+
/** The entry's gate slug when the gate applies to it (configured, set, not refused). */
|
|
2155
|
+
gateSlugOf(entry) {
|
|
2156
|
+
const slug = entry.gateSlug;
|
|
2157
|
+
return slug && this.versions && !this.versions.isDisabled(slug) ? slug : null;
|
|
2158
|
+
}
|
|
2159
|
+
/** Data + stored version equal to `version`, within `maxAgeMs` of the last real validation. */
|
|
2160
|
+
gateHolds(entry, version) {
|
|
2161
|
+
const gate = entry.gate;
|
|
2162
|
+
if (entry.data === void 0 || !gate || gate.v !== version) return false;
|
|
2163
|
+
const age = this.now() - gate.validatedAt;
|
|
2164
|
+
return age >= 0 && age < this.gateMaxAgeMs;
|
|
2165
|
+
}
|
|
2166
|
+
invalidateEntry(entry, sk, delayMs) {
|
|
2167
|
+
entry.gate = null;
|
|
2168
|
+
entry.savedAt = null;
|
|
2169
|
+
entry.epoch += 1;
|
|
2170
|
+
entry.promise = null;
|
|
2171
|
+
const active = entry.listeners.size > 0 && entry.fetcher;
|
|
2172
|
+
if (active && delayMs && delayMs > 0) {
|
|
2173
|
+
this.touch(entry);
|
|
2174
|
+
if (this.delayed.has(sk)) return;
|
|
2175
|
+
const timer = setTimeout(() => {
|
|
2176
|
+
this.delayed.delete(sk);
|
|
2177
|
+
if (entry.listeners.size === 0 || !entry.fetcher || entry.savedAt != null) return;
|
|
2178
|
+
void this.runFetch(entry, sk);
|
|
2179
|
+
}, delayMs);
|
|
2180
|
+
timer.unref?.();
|
|
2181
|
+
this.delayed.set(sk, timer);
|
|
2182
|
+
return;
|
|
2183
|
+
}
|
|
2184
|
+
this.cancelDelayed(sk);
|
|
2185
|
+
if (active) {
|
|
2186
|
+
void this.runFetch(entry, sk);
|
|
2187
|
+
} else {
|
|
2188
|
+
this.touch(entry);
|
|
2189
|
+
}
|
|
2190
|
+
}
|
|
2191
|
+
cancelDelayed(sk) {
|
|
2192
|
+
const timer = this.delayed.get(sk);
|
|
2193
|
+
if (timer === void 0) return;
|
|
2194
|
+
clearTimeout(timer);
|
|
2195
|
+
this.delayed.delete(sk);
|
|
2196
|
+
}
|
|
2197
|
+
async maybeHydrate(entry, sk) {
|
|
2198
|
+
if (entry.hydrated) return;
|
|
2199
|
+
entry.hydrated = true;
|
|
2200
|
+
if (!entry.persist || !this.storage) return;
|
|
2201
|
+
try {
|
|
2202
|
+
const raw = await this.storage.getItem(STORAGE_KEY_QUERY_PREFIX + sk);
|
|
2203
|
+
if (!raw) return;
|
|
2204
|
+
const env = JSON.parse(raw);
|
|
2205
|
+
if (env && typeof env.savedAt === "number" && "data" in env) {
|
|
2206
|
+
const sameApp = this.sameAppVersion(env.appVersion);
|
|
2207
|
+
entry.data = env.data;
|
|
2208
|
+
entry.etag = typeof env.etag === "string" && env.etag ? env.etag : null;
|
|
2209
|
+
entry.gate = sameApp ? readGate(env.gate) : null;
|
|
2210
|
+
entry.savedAt = sameApp ? env.savedAt : null;
|
|
2211
|
+
entry.ttl = env.ttl ?? entry.ttl;
|
|
2212
|
+
entry.status = "success";
|
|
2213
|
+
const isNew = this.track(STORAGE_KEY_QUERY_PREFIX + sk);
|
|
2214
|
+
this.touch(entry);
|
|
2215
|
+
if (isNew) await this.writeIndex();
|
|
2216
|
+
}
|
|
2217
|
+
} catch {
|
|
2218
|
+
}
|
|
2219
|
+
}
|
|
2220
|
+
async maybePersist(entry, sk) {
|
|
2221
|
+
if (!entry.persist) return;
|
|
2222
|
+
if (!this.storage) {
|
|
2223
|
+
this.warnNoStorage();
|
|
2224
|
+
return;
|
|
2225
|
+
}
|
|
2226
|
+
if (entry.data === void 0 || entry.savedAt == null) return;
|
|
2227
|
+
const env = { data: entry.data, savedAt: entry.savedAt, ttl: entry.ttl };
|
|
2228
|
+
if (entry.etag) env.etag = entry.etag;
|
|
2229
|
+
if (entry.gate) env.gate = entry.gate;
|
|
2230
|
+
if (this.appVersion) env.appVersion = this.appVersion;
|
|
2231
|
+
const storageKey = STORAGE_KEY_QUERY_PREFIX + sk;
|
|
2232
|
+
const isNew = this.track(storageKey);
|
|
2233
|
+
try {
|
|
2234
|
+
await this.storage.setItem(storageKey, JSON.stringify(env));
|
|
2235
|
+
} catch {
|
|
2236
|
+
}
|
|
2237
|
+
if (isNew) await this.writeIndex();
|
|
2238
|
+
}
|
|
2239
|
+
/** Read the persisted key index once into `persistedKeys`. */
|
|
2240
|
+
loadIndex() {
|
|
2241
|
+
const storage2 = this.storage;
|
|
2242
|
+
if (!storage2) return Promise.resolve();
|
|
2243
|
+
if (!this.indexLoad) {
|
|
2244
|
+
this.indexLoad = (async () => {
|
|
2245
|
+
try {
|
|
2246
|
+
const raw = await storage2.getItem(STORAGE_KEY_QUERY_INDEX);
|
|
2247
|
+
const keys = raw ? JSON.parse(raw) : [];
|
|
2248
|
+
if (Array.isArray(keys)) {
|
|
2249
|
+
for (const k of keys) {
|
|
2250
|
+
if (typeof k === "string" && k.startsWith(STORAGE_KEY_QUERY_PREFIX)) this.persistedKeys.add(k);
|
|
2251
|
+
}
|
|
2252
|
+
}
|
|
2253
|
+
} catch {
|
|
2254
|
+
}
|
|
2255
|
+
})();
|
|
2256
|
+
}
|
|
2257
|
+
return this.indexLoad;
|
|
2258
|
+
}
|
|
2259
|
+
/** Remember a persisted key in memory; true when it was not known yet. */
|
|
2260
|
+
track(storageKey) {
|
|
2261
|
+
if (this.persistedKeys.has(storageKey)) return false;
|
|
2262
|
+
this.persistedKeys.add(storageKey);
|
|
2263
|
+
return true;
|
|
2264
|
+
}
|
|
2265
|
+
/** Write the stored key index (after merging the earlier-session index); serialized. */
|
|
2266
|
+
async writeIndex() {
|
|
2267
|
+
const storage2 = this.storage;
|
|
2268
|
+
if (!storage2) return;
|
|
2269
|
+
await this.loadIndex();
|
|
2270
|
+
this.indexWrite = this.indexWrite.then(async () => {
|
|
2271
|
+
try {
|
|
2272
|
+
await storage2.setItem(STORAGE_KEY_QUERY_INDEX, JSON.stringify([...this.persistedKeys]));
|
|
2273
|
+
} catch {
|
|
2274
|
+
}
|
|
2275
|
+
});
|
|
2276
|
+
await this.indexWrite;
|
|
2277
|
+
}
|
|
2278
|
+
touch(entry) {
|
|
2279
|
+
entry.snapshot = Object.freeze({
|
|
2280
|
+
data: entry.data,
|
|
2281
|
+
error: entry.error,
|
|
2282
|
+
status: entry.status,
|
|
2283
|
+
isLoading: entry.status === "loading",
|
|
2284
|
+
isFetching: entry.isFetching,
|
|
2285
|
+
isStale: this.isStale(entry),
|
|
2286
|
+
updatedAt: entry.savedAt
|
|
2287
|
+
});
|
|
2288
|
+
for (const listener of entry.listeners) listener();
|
|
2289
|
+
}
|
|
2290
|
+
/** Whether a persisted tag names this cache's app version (both absent counts as equal). */
|
|
2291
|
+
sameAppVersion(tag) {
|
|
2292
|
+
return String(parseAppVersion(tag)) === this.appVersionKey;
|
|
2293
|
+
}
|
|
2294
|
+
warnNoStorage() {
|
|
2295
|
+
if (this.warnedNoStorage) return;
|
|
2296
|
+
this.warnedNoStorage = true;
|
|
2297
|
+
this.warn?.(PERSIST_WARNING);
|
|
2298
|
+
}
|
|
2299
|
+
};
|
|
2300
|
+
function readGate(raw) {
|
|
2301
|
+
const g = raw;
|
|
2302
|
+
if (!g || typeof g.v !== "string" || typeof g.validatedAt !== "number") return null;
|
|
2303
|
+
return { v: g.v, validatedAt: g.validatedAt };
|
|
2304
|
+
}
|
|
2305
|
+
function prefixMatcher(prefix) {
|
|
2306
|
+
const full = serializeKey(prefix);
|
|
2307
|
+
if (typeof prefix === "string") return (k) => k === full;
|
|
2308
|
+
const open = full.slice(0, -1);
|
|
2309
|
+
return (k) => k === full || k.startsWith(`${open},`) || k.startsWith(`${open}]`);
|
|
2310
|
+
}
|
|
2311
|
+
|
|
2312
|
+
// ../core/src/cache/cache-storage.ts
|
|
2313
|
+
function createMemoryCacheStorage() {
|
|
2314
|
+
const map = /* @__PURE__ */ new Map();
|
|
2315
|
+
return {
|
|
2316
|
+
async getItem(key) {
|
|
2317
|
+
return map.has(key) ? map.get(key) : null;
|
|
2318
|
+
},
|
|
2319
|
+
async setItem(key, value) {
|
|
2320
|
+
map.set(key, value);
|
|
2321
|
+
},
|
|
2322
|
+
async removeItem(key) {
|
|
2323
|
+
map.delete(key);
|
|
2324
|
+
},
|
|
2325
|
+
async multiRemove(keys) {
|
|
2326
|
+
for (const k of keys) map.delete(k);
|
|
2327
|
+
}
|
|
2328
|
+
};
|
|
2329
|
+
}
|
|
2330
|
+
|
|
2331
|
+
// ../core/src/cache/secure-migration.ts
|
|
2332
|
+
function isSecureMigratableKey(key) {
|
|
2333
|
+
return key.startsWith(STORAGE_KEY_QUERY_PREFIX) || key === STORAGE_KEY_QUERY_INDEX || key.startsWith(STORAGE_KEY_CONFIG_PREFIX) || key === STORAGE_KEY_LOCALE;
|
|
2334
|
+
}
|
|
2335
|
+
function createSecureMigrationStorage(plain, secure) {
|
|
2336
|
+
const settled = /* @__PURE__ */ new Set();
|
|
2337
|
+
const generation = /* @__PURE__ */ new Map();
|
|
2338
|
+
const bump = (key) => generation.set(key, (generation.get(key) ?? 0) + 1);
|
|
2339
|
+
const dropSecure = async (keys) => {
|
|
2340
|
+
if (!keys.length) return;
|
|
2341
|
+
for (const k of keys) settled.add(k);
|
|
2342
|
+
try {
|
|
2343
|
+
await (keys.length === 1 ? secure.removeItem(keys[0]) : secure.multiRemove(keys));
|
|
2344
|
+
} catch {
|
|
2345
|
+
}
|
|
2346
|
+
};
|
|
2347
|
+
return {
|
|
2348
|
+
async getItem(key) {
|
|
2349
|
+
const gen = generation.get(key);
|
|
2350
|
+
const value = await plain.getItem(key);
|
|
2351
|
+
if (!isSecureMigratableKey(key) || settled.has(key)) return value;
|
|
2352
|
+
if (value !== null) {
|
|
2353
|
+
settled.add(key);
|
|
2354
|
+
return value;
|
|
2355
|
+
}
|
|
2356
|
+
let old;
|
|
2357
|
+
try {
|
|
2358
|
+
old = await secure.getItem(key);
|
|
2359
|
+
} catch {
|
|
2360
|
+
return null;
|
|
2361
|
+
}
|
|
2362
|
+
if (generation.get(key) !== gen) return plain.getItem(key);
|
|
2363
|
+
if (old === null) {
|
|
2364
|
+
settled.add(key);
|
|
2365
|
+
return null;
|
|
2366
|
+
}
|
|
2367
|
+
try {
|
|
2368
|
+
await plain.setItem(key, old);
|
|
2369
|
+
} catch {
|
|
2370
|
+
return old;
|
|
2371
|
+
}
|
|
2372
|
+
await dropSecure([key]);
|
|
2373
|
+
return old;
|
|
2374
|
+
},
|
|
2375
|
+
async setItem(key, value) {
|
|
2376
|
+
bump(key);
|
|
2377
|
+
const result = await plain.setItem(key, value);
|
|
2378
|
+
if (isSecureMigratableKey(key) && !settled.has(key)) await dropSecure([key]);
|
|
2379
|
+
return result;
|
|
2380
|
+
},
|
|
2381
|
+
// The secure copy goes even when the plain remove throws: a sign-out must not
|
|
2382
|
+
// leave per-user cache behind to be moved back on the next start.
|
|
2383
|
+
async removeItem(key) {
|
|
2384
|
+
bump(key);
|
|
2385
|
+
try {
|
|
2386
|
+
await plain.removeItem(key);
|
|
2387
|
+
} finally {
|
|
2388
|
+
if (isSecureMigratableKey(key)) await dropSecure([key]);
|
|
2389
|
+
}
|
|
2390
|
+
},
|
|
2391
|
+
async multiRemove(keys) {
|
|
2392
|
+
for (const k of keys) bump(k);
|
|
2393
|
+
try {
|
|
2394
|
+
await plain.multiRemove(keys);
|
|
2395
|
+
} finally {
|
|
2396
|
+
await dropSecure(keys.filter(isSecureMigratableKey));
|
|
2397
|
+
}
|
|
2398
|
+
}
|
|
2399
|
+
};
|
|
2400
|
+
}
|
|
2401
|
+
|
|
2402
|
+
// ../core/src/content-sync/ContentChangeHub.ts
|
|
2403
|
+
var CONTENT_WATCH_MAX_COLLECTIONS = 20;
|
|
2404
|
+
var CONTENT_WATCH_MAX_ITEMS = 50;
|
|
2405
|
+
var CONTENT_WATCH_DEBOUNCE_MS = 250;
|
|
2406
|
+
var CONTENT_HELLO_SPREAD_MS = 5e3;
|
|
2407
|
+
var enc2 = encodeURIComponent;
|
|
2408
|
+
var isNotFound = (err) => err?.status === 404;
|
|
2409
|
+
function createContentChangeHub(o) {
|
|
2410
|
+
const subs = /* @__PURE__ */ new Set();
|
|
2411
|
+
const known = /* @__PURE__ */ new Map();
|
|
2412
|
+
const disabled = /* @__PURE__ */ new Set();
|
|
2413
|
+
const warned = /* @__PURE__ */ new Set();
|
|
2414
|
+
const random = o.random ?? Math.random;
|
|
2415
|
+
const setT = o.setTimeout ?? ((fn, ms) => setTimeout(fn, ms));
|
|
2416
|
+
const clearT = o.clearTimeout ?? ((h) => clearTimeout(h));
|
|
2417
|
+
let sse;
|
|
2418
|
+
let sseUrl = "";
|
|
2419
|
+
let sseOn = false;
|
|
2420
|
+
let sseFailed = false;
|
|
2421
|
+
let poller;
|
|
2422
|
+
let pollSet = [];
|
|
2423
|
+
let applied = "";
|
|
2424
|
+
let timer;
|
|
2425
|
+
let appUnsub;
|
|
2426
|
+
const active = () => !o.appState || o.appState.isActive();
|
|
2427
|
+
const warnOnce = (key, message) => {
|
|
2428
|
+
if (warned.has(key)) return;
|
|
2429
|
+
warned.add(key);
|
|
2430
|
+
o.warn?.(message);
|
|
2431
|
+
};
|
|
2432
|
+
const cancel = () => {
|
|
2433
|
+
if (timer !== void 0) clearT(timer);
|
|
2434
|
+
timer = void 0;
|
|
2435
|
+
};
|
|
2436
|
+
const schedule = () => {
|
|
2437
|
+
cancel();
|
|
2438
|
+
timer = setT(() => {
|
|
2439
|
+
timer = void 0;
|
|
2440
|
+
apply();
|
|
2441
|
+
}, CONTENT_WATCH_DEBOUNCE_MS);
|
|
2442
|
+
};
|
|
2443
|
+
const pause = () => {
|
|
2444
|
+
sse?.stop();
|
|
2445
|
+
poller?.stop();
|
|
2446
|
+
sseOn = false;
|
|
2447
|
+
applied = "";
|
|
2448
|
+
};
|
|
2449
|
+
const stop = () => {
|
|
2450
|
+
cancel();
|
|
2451
|
+
pause();
|
|
2452
|
+
pollSet = [];
|
|
2453
|
+
appUnsub?.();
|
|
2454
|
+
appUnsub = void 0;
|
|
2455
|
+
};
|
|
2456
|
+
const plan = () => {
|
|
2457
|
+
const cols = /* @__PURE__ */ new Set();
|
|
2458
|
+
const items = /* @__PURE__ */ new Map();
|
|
2459
|
+
let interval = Infinity;
|
|
2460
|
+
let wantSse = false;
|
|
2461
|
+
for (const s of subs) {
|
|
2462
|
+
const { collection: c, id, also } = s.t;
|
|
2463
|
+
if (!disabled.has(c)) id ? items.set(`${enc2(c)}:${enc2(id)}`, c) : cols.add(c);
|
|
2464
|
+
for (const a of also ?? []) if (!disabled.has(a)) cols.add(a);
|
|
2465
|
+
interval = Math.min(interval, resolvePollInterval(s.poll));
|
|
2466
|
+
wantSse || (wantSse = s.mode !== "poll");
|
|
2467
|
+
}
|
|
2468
|
+
const itemList = [...items].filter(([, c]) => !cols.has(c));
|
|
2469
|
+
const colList = [...cols];
|
|
2470
|
+
let url = null;
|
|
2471
|
+
let poll = [...colList, ...itemList.map(([, c]) => c)];
|
|
2472
|
+
if (wantSse && o.connectSse && !sseFailed) {
|
|
2473
|
+
const onCols = colList.slice(0, CONTENT_WATCH_MAX_COLLECTIONS);
|
|
2474
|
+
const onItems = itemList.slice(0, CONTENT_WATCH_MAX_ITEMS);
|
|
2475
|
+
poll = [...colList.slice(CONTENT_WATCH_MAX_COLLECTIONS), ...itemList.slice(CONTENT_WATCH_MAX_ITEMS).map(([, c]) => c)];
|
|
2476
|
+
if (poll.length) warnOnce("", "[QafkaCMS] live: over 20 collections / 50 records; the rest polls");
|
|
2477
|
+
const q = [];
|
|
2478
|
+
if (onCols.length) q.push(`collections=${onCols.map(enc2).join(",")}`);
|
|
2479
|
+
if (onItems.length) q.push(`items=${onItems.map(([k]) => k).join(",")}`);
|
|
2480
|
+
if (q.length) url = `${o.apiUrl.replace(/\/$/, "")}${END_USER_BASE_PATH}/content-changes/watch?${q.join("&")}`;
|
|
2481
|
+
}
|
|
2482
|
+
poll = [...new Set(poll)];
|
|
2483
|
+
return { url, poll, interval: interval === Infinity ? resolvePollInterval() : interval };
|
|
2484
|
+
};
|
|
2485
|
+
const apply = (catchUp = false) => {
|
|
2486
|
+
if (!subs.size) return stop();
|
|
2487
|
+
if (o.appState && !appUnsub) {
|
|
2488
|
+
appUnsub = o.appState.subscribe((on) => {
|
|
2489
|
+
if (!on) return pause();
|
|
2490
|
+
sseFailed = false;
|
|
2491
|
+
apply(true);
|
|
2492
|
+
});
|
|
2493
|
+
}
|
|
2494
|
+
if (!active()) return pause();
|
|
2495
|
+
const p = plan();
|
|
2496
|
+
const key = JSON.stringify(p);
|
|
2497
|
+
if (key === applied) return;
|
|
2498
|
+
applied = key;
|
|
2499
|
+
sseOn = !!p.url;
|
|
2500
|
+
if (p.url) {
|
|
2501
|
+
sseUrl = p.url;
|
|
2502
|
+
sse ?? (sse = new SseSupervisor({
|
|
2503
|
+
connectSse: o.connectSse,
|
|
2504
|
+
url: () => sseUrl,
|
|
2505
|
+
headers: o.headers,
|
|
2506
|
+
onMessage,
|
|
2507
|
+
onFallback: fallback,
|
|
2508
|
+
random: o.random,
|
|
2509
|
+
setTimeout: o.setTimeout,
|
|
2510
|
+
clearTimeout: o.clearTimeout
|
|
2511
|
+
}));
|
|
2512
|
+
void sse.start();
|
|
2513
|
+
} else {
|
|
2514
|
+
sse?.stop();
|
|
2515
|
+
}
|
|
2516
|
+
pollSet = p.poll;
|
|
2517
|
+
if (!p.poll.length) return poller?.stop();
|
|
2518
|
+
if (poller?.intervalMs !== p.interval) {
|
|
2519
|
+
poller?.stop();
|
|
2520
|
+
poller = new VersionPoller({
|
|
2521
|
+
check,
|
|
2522
|
+
intervalMs: p.interval,
|
|
2523
|
+
appState: o.appState,
|
|
2524
|
+
followAppState: false,
|
|
2525
|
+
random: o.random,
|
|
2526
|
+
setTimeout: o.setTimeout,
|
|
2527
|
+
clearTimeout: o.clearTimeout
|
|
2528
|
+
});
|
|
2529
|
+
}
|
|
2530
|
+
if (!poller.running) poller.start();
|
|
2531
|
+
if (catchUp || p.poll.some((c) => !known.has(c))) void check();
|
|
2532
|
+
};
|
|
2533
|
+
function fallback() {
|
|
2534
|
+
sse?.stop();
|
|
2535
|
+
sseFailed = true;
|
|
2536
|
+
applied = "";
|
|
2537
|
+
apply(true);
|
|
2538
|
+
}
|
|
2539
|
+
function onMessage(e) {
|
|
2540
|
+
const ev = e ?? {};
|
|
2541
|
+
const { type, collection: c, spreadMs: spread } = ev;
|
|
2542
|
+
if (type === "hello" && ev.versions && typeof ev.versions === "object") {
|
|
2543
|
+
for (const [col, v] of Object.entries(ev.versions)) saw(col, v, CONTENT_HELLO_SPREAD_MS);
|
|
2544
|
+
} else if (type === "changed" && typeof c === "string") {
|
|
2545
|
+
if (typeof ev.v === "string" || typeof ev.v === "number") known.set(c, String(ev.v));
|
|
2546
|
+
changed(c, typeof ev.id === "string" ? ev.id : void 0, typeof spread === "number" && spread > 0 ? spread : 0);
|
|
2547
|
+
} else if (type === "error") {
|
|
2548
|
+
fallback();
|
|
2549
|
+
}
|
|
2550
|
+
}
|
|
2551
|
+
function saw(c, raw, spread = 0) {
|
|
2552
|
+
if (typeof raw !== "string" && typeof raw !== "number") return;
|
|
2553
|
+
const prev = known.get(c);
|
|
2554
|
+
known.set(c, String(raw));
|
|
2555
|
+
if (prev !== void 0 && prev !== String(raw)) changed(c, void 0, spread);
|
|
2556
|
+
}
|
|
2557
|
+
function changed(c, id, spread) {
|
|
2558
|
+
const delayMs = spread ? Math.floor(random() * spread) : 0;
|
|
2559
|
+
const done = /* @__PURE__ */ new Set();
|
|
2560
|
+
const caches = [];
|
|
2561
|
+
for (const { t, cache } of subs) {
|
|
2562
|
+
if (!cache) continue;
|
|
2563
|
+
if (!(t.collection === c && (!t.id || id === void 0 || id === t.id) || t.also?.includes(c))) continue;
|
|
2564
|
+
let i = caches.indexOf(cache);
|
|
2565
|
+
if (i < 0) i = caches.push(cache) - 1;
|
|
2566
|
+
const prefixes = t.id ? [["content-item", t.collection, t.id]] : [["content", t.collection], ["content-item", t.collection]];
|
|
2567
|
+
for (const prefix of prefixes) {
|
|
2568
|
+
const k = i + JSON.stringify(prefix);
|
|
2569
|
+
if (done.has(k)) continue;
|
|
2570
|
+
done.add(k);
|
|
2571
|
+
cache.invalidateByPrefix(prefix, { delayMs });
|
|
2572
|
+
}
|
|
2573
|
+
}
|
|
2574
|
+
}
|
|
2575
|
+
async function record(cols) {
|
|
2576
|
+
const res = await o.request(`/content-changes/version?collections=${cols.map(enc2).join(",")}`);
|
|
2577
|
+
for (const c of cols) saw(c, res?.[c]);
|
|
2578
|
+
}
|
|
2579
|
+
async function check() {
|
|
2580
|
+
let dropped = false;
|
|
2581
|
+
for (let i = 0; i < pollSet.length; i += CONTENT_WATCH_MAX_COLLECTIONS) {
|
|
2582
|
+
const chunk = pollSet.slice(i, i + CONTENT_WATCH_MAX_COLLECTIONS);
|
|
2583
|
+
try {
|
|
2584
|
+
await record(chunk);
|
|
2585
|
+
} catch (err) {
|
|
2586
|
+
if (!isNotFound(err)) continue;
|
|
2587
|
+
for (const c of chunk) {
|
|
2588
|
+
try {
|
|
2589
|
+
if (chunk.length === 1) throw err;
|
|
2590
|
+
await record([c]);
|
|
2591
|
+
} catch (e) {
|
|
2592
|
+
if (!isNotFound(e)) continue;
|
|
2593
|
+
disabled.add(c);
|
|
2594
|
+
warnOnce(c, `[QafkaCMS] live disabled for ${c}: enable change signal in the collection settings`);
|
|
2595
|
+
dropped = true;
|
|
2596
|
+
}
|
|
2597
|
+
}
|
|
2598
|
+
}
|
|
2599
|
+
}
|
|
2600
|
+
if (dropped) {
|
|
2601
|
+
sseFailed = false;
|
|
2602
|
+
schedule();
|
|
2603
|
+
}
|
|
2604
|
+
}
|
|
2605
|
+
return {
|
|
2606
|
+
watch(target, mode = "auto", opts = {}) {
|
|
2607
|
+
const sub = { t: target, mode, cache: opts.cache, poll: opts.pollIntervalMs };
|
|
2608
|
+
subs.add(sub);
|
|
2609
|
+
schedule();
|
|
2610
|
+
return () => {
|
|
2611
|
+
if (subs.delete(sub)) schedule();
|
|
2612
|
+
};
|
|
2613
|
+
},
|
|
2614
|
+
status: () => sseOn ? "sse" : poller?.running ? "polling" : "idle",
|
|
2615
|
+
reset() {
|
|
2616
|
+
known.clear();
|
|
2617
|
+
disabled.clear();
|
|
2618
|
+
sseFailed = false;
|
|
2619
|
+
if (!subs.size) return;
|
|
2620
|
+
cancel();
|
|
2621
|
+
applied = "";
|
|
2622
|
+
apply();
|
|
2623
|
+
},
|
|
2624
|
+
dispose() {
|
|
2625
|
+
subs.clear();
|
|
2626
|
+
stop();
|
|
2627
|
+
},
|
|
2628
|
+
versions: (collections) => fetchContentVersions(o.request, collections)
|
|
2629
|
+
};
|
|
2630
|
+
}
|
|
2631
|
+
|
|
2632
|
+
// ../core/src/content-bundle/filter.ts
|
|
2633
|
+
var MAX_DEPTH = 32;
|
|
2634
|
+
var EMPTY = [];
|
|
2635
|
+
function isObject(v) {
|
|
2636
|
+
return typeof v === "object" && v !== null && !Array.isArray(v);
|
|
2637
|
+
}
|
|
2638
|
+
function hiddenBundleComponents(components, appVersion) {
|
|
2639
|
+
const client = parseAppVersion(appVersion);
|
|
2640
|
+
const out = /* @__PURE__ */ new Set();
|
|
2641
|
+
for (const [id, c] of Object.entries(components ?? {})) {
|
|
2642
|
+
const min = parseAppVersion(c?.minAppVersion);
|
|
2643
|
+
if (!min) continue;
|
|
2644
|
+
if (client ? compareAppVersion(min, client) > 0 : c.appVersionUnknown === "hide") out.add(id);
|
|
2645
|
+
}
|
|
2646
|
+
return out;
|
|
2647
|
+
}
|
|
2648
|
+
function rowVisible(row, rule, client) {
|
|
2649
|
+
const bounds = [];
|
|
2650
|
+
if (rule.minField) bounds.push([rule.minField, 1]);
|
|
2651
|
+
if (rule.maxField) bounds.push([rule.maxField, -1]);
|
|
2652
|
+
if (!bounds.length || !client && rule.unknown !== "hide") return true;
|
|
2653
|
+
return bounds.every(([field, sign]) => {
|
|
2654
|
+
const v = parseAppVersion(row[field]);
|
|
2655
|
+
return !v || client !== null && sign * compareAppVersion(v, client) <= 0;
|
|
2656
|
+
});
|
|
2657
|
+
}
|
|
2658
|
+
function strip(value, hidden, depth) {
|
|
2659
|
+
if (depth > MAX_DEPTH) return value;
|
|
2660
|
+
if (Array.isArray(value)) {
|
|
2661
|
+
let changed = false;
|
|
2662
|
+
const out2 = [];
|
|
2663
|
+
for (const item of value) {
|
|
2664
|
+
if (isObject(item) && typeof item.__component === "string" && hidden.has(item.__component)) {
|
|
2665
|
+
changed = true;
|
|
2666
|
+
continue;
|
|
2667
|
+
}
|
|
2668
|
+
const next = strip(item, hidden, depth + 1);
|
|
2669
|
+
if (next !== item) changed = true;
|
|
2670
|
+
out2.push(next);
|
|
2671
|
+
}
|
|
2672
|
+
return changed ? out2 : value;
|
|
2673
|
+
}
|
|
2674
|
+
if (!isObject(value)) return value;
|
|
2675
|
+
if (typeof value.__component === "string" && hidden.has(value.__component)) return null;
|
|
2676
|
+
let out;
|
|
2677
|
+
for (const [k, v] of Object.entries(value)) {
|
|
2678
|
+
const next = strip(v, hidden, depth + 1);
|
|
2679
|
+
if (next !== v) (out ?? (out = { ...value }))[k] = next;
|
|
2680
|
+
}
|
|
2681
|
+
return out ?? value;
|
|
2682
|
+
}
|
|
2683
|
+
var hasMeta = (m) => !!m && (!!m.componentFields || !!m.zoneFields);
|
|
2684
|
+
function isLocaleMap(v) {
|
|
2685
|
+
if (!isObject(v)) return false;
|
|
2686
|
+
const entries = Object.values(v);
|
|
2687
|
+
return entries.length > 0 && entries.every((e) => e === null || isObject(e) && typeof e.state === "string" && "value" in e);
|
|
2688
|
+
}
|
|
2689
|
+
function perLocale(v, fn) {
|
|
2690
|
+
if (!isLocaleMap(v)) return fn(v);
|
|
2691
|
+
let out;
|
|
2692
|
+
for (const [loc, e] of Object.entries(v)) {
|
|
2693
|
+
if (!e) continue;
|
|
2694
|
+
const next = fn(e.value);
|
|
2695
|
+
if (next !== e.value) (out ?? (out = { ...v }))[loc] = { ...e, value: next };
|
|
2696
|
+
}
|
|
2697
|
+
return out ?? v;
|
|
2698
|
+
}
|
|
2699
|
+
function stripFields(obj, meta, hidden, components, depth) {
|
|
2700
|
+
let out;
|
|
2701
|
+
const set = (k, fn) => {
|
|
2702
|
+
if (!(k in obj)) return;
|
|
2703
|
+
const next = perLocale(obj[k], fn);
|
|
2704
|
+
if (next !== obj[k]) (out ?? (out = { ...obj }))[k] = next;
|
|
2705
|
+
};
|
|
2706
|
+
for (const [k, f] of Object.entries(meta.componentFields ?? {})) {
|
|
2707
|
+
set(k, (v) => {
|
|
2708
|
+
if (v === null || v === void 0 || !f || typeof f.componentId !== "string") return v;
|
|
2709
|
+
if (hidden.has(f.componentId)) return null;
|
|
2710
|
+
if (!Array.isArray(v)) return instance(v, f.componentId, hidden, components, depth);
|
|
2711
|
+
const items = v.map((it) => instance(it, f.componentId, hidden, components, depth));
|
|
2712
|
+
return items.some((it, i) => it !== v[i]) ? items : v;
|
|
2713
|
+
});
|
|
2714
|
+
}
|
|
2715
|
+
for (const k of meta.zoneFields ?? []) {
|
|
2716
|
+
set(k, (v) => {
|
|
2717
|
+
if (!Array.isArray(v)) return v;
|
|
2718
|
+
let changed = false;
|
|
2719
|
+
const kept = [];
|
|
2720
|
+
for (const item of v) {
|
|
2721
|
+
const cid = isObject(item) ? item.__component : void 0;
|
|
2722
|
+
if (typeof cid === "string" && hidden.has(cid)) {
|
|
2723
|
+
changed = true;
|
|
2724
|
+
continue;
|
|
2725
|
+
}
|
|
2726
|
+
const next = typeof cid === "string" ? instance(item, cid, hidden, components, depth) : item;
|
|
2727
|
+
if (next !== item) changed = true;
|
|
2728
|
+
kept.push(next);
|
|
2729
|
+
}
|
|
2730
|
+
return changed ? kept : v;
|
|
2731
|
+
});
|
|
2732
|
+
}
|
|
2733
|
+
return out ?? obj;
|
|
2734
|
+
}
|
|
2735
|
+
function instance(v, cid, hidden, components, depth) {
|
|
2736
|
+
const meta = components?.[cid];
|
|
2737
|
+
if (!isObject(v) || depth >= MAX_DEPTH || !hasMeta(meta)) return v;
|
|
2738
|
+
return stripFields(v, meta, hidden, components, depth + 1);
|
|
2739
|
+
}
|
|
2740
|
+
function stripHiddenBundleBlocks(row, hidden, meta, components) {
|
|
2741
|
+
if (!hidden.size) return row;
|
|
2742
|
+
if (hasMeta(meta)) return stripFields(row, meta, hidden, components, 0);
|
|
2743
|
+
let out;
|
|
2744
|
+
for (const [k, v] of Object.entries(row)) {
|
|
2745
|
+
const next = strip(v, hidden, 0);
|
|
2746
|
+
if (next !== v) (out ?? (out = { ...row }))[k] = next;
|
|
2747
|
+
}
|
|
2748
|
+
return out ?? row;
|
|
2749
|
+
}
|
|
2750
|
+
function filterBundleRows(file, collection, appVersion) {
|
|
2751
|
+
const col = file.collections[collection];
|
|
2752
|
+
if (!col || !Array.isArray(col.rows)) return EMPTY;
|
|
2753
|
+
const client = parseAppVersion(appVersion);
|
|
2754
|
+
const rule = col.appVersion;
|
|
2755
|
+
const rows = rule ? col.rows.filter((r) => rowVisible(r, rule, client)) : col.rows;
|
|
2756
|
+
const hidden = hiddenBundleComponents(file.components, appVersion);
|
|
2757
|
+
return hidden.size ? rows.map((r) => stripHiddenBundleBlocks(r, hidden, col, file.components)) : rows;
|
|
2758
|
+
}
|
|
2759
|
+
|
|
2760
|
+
// ../core/src/content-bundle/ContentBundleClient.ts
|
|
2761
|
+
var STORAGE_KEY_BUNDLE_INDEX = `${STORAGE_PREFIX}bundle-index`;
|
|
2762
|
+
var STORAGE_KEY_BUNDLE_PREFIX = `${STORAGE_PREFIX}bundle:`;
|
|
2763
|
+
var fileKey = (locale) => `${STORAGE_KEY_BUNDLE_PREFIX}${locale}`;
|
|
2764
|
+
var NO_STORAGE = {
|
|
2765
|
+
getItem: async () => null,
|
|
2766
|
+
setItem: async () => void 0,
|
|
2767
|
+
removeItem: async () => void 0,
|
|
2768
|
+
multiRemove: async () => void 0
|
|
2769
|
+
};
|
|
2770
|
+
var EMPTY2 = [];
|
|
2771
|
+
var ORIGIN_RE = /^([a-z][a-z\d+.-]*:)\/\/([^/?#]*)/i;
|
|
2772
|
+
function isBundleFile(v) {
|
|
2773
|
+
const f = v;
|
|
2774
|
+
return typeof f === "object" && f !== null && f.formatVersion === 1 && typeof f.version === "number" && typeof f.locale === "string" && typeof f.collections === "object" && f.collections !== null;
|
|
2775
|
+
}
|
|
2776
|
+
function originOf(url) {
|
|
2777
|
+
const m = ORIGIN_RE.exec(url);
|
|
2778
|
+
if (!m) return null;
|
|
2779
|
+
const scheme = m[1].toLowerCase();
|
|
2780
|
+
let host = m[2].toLowerCase();
|
|
2781
|
+
if (scheme === "https:" && host.endsWith(":443") || scheme === "http:" && host.endsWith(":80")) {
|
|
2782
|
+
host = host.slice(0, host.lastIndexOf(":"));
|
|
2783
|
+
}
|
|
2784
|
+
return `${scheme}//${host}`;
|
|
2785
|
+
}
|
|
2786
|
+
function resolveBundleUrl(apiUrl, url) {
|
|
2787
|
+
const api = originOf(apiUrl) ?? "";
|
|
2788
|
+
if (url.startsWith("//")) url = `${api.slice(0, api.indexOf("//"))}${url}`;
|
|
2789
|
+
const origin = originOf(url);
|
|
2790
|
+
if (origin) return { href: url, sameOrigin: origin === api };
|
|
2791
|
+
return { href: `${api}${url.startsWith("/") ? "" : "/"}${url}`, sameOrigin: true };
|
|
2792
|
+
}
|
|
2793
|
+
function toError(e) {
|
|
2794
|
+
return e instanceof Error ? e : new Error(String(e));
|
|
2795
|
+
}
|
|
2796
|
+
function createContentBundleClient(o) {
|
|
2797
|
+
const { http, platform, language } = o;
|
|
2798
|
+
const plain = o.storage !== void 0 ? o.storage : platform.cacheStorage;
|
|
2799
|
+
if (plain === void 0) {
|
|
2800
|
+
platform.warn?.(
|
|
2801
|
+
"[QafkaCMS] contentBundle has no plain storage: the bundle is kept in memory for this app session (plus `initial`). Pass `contentBundle: { storage: AsyncStorage }` (or an MMKV adapter) to keep it offline."
|
|
2802
|
+
);
|
|
2803
|
+
}
|
|
2804
|
+
const storage2 = plain ?? NO_STORAGE;
|
|
2805
|
+
const appVersion = http.appVersion;
|
|
2806
|
+
const listeners = /* @__PURE__ */ new Set();
|
|
2807
|
+
let file = null;
|
|
2808
|
+
if (o.initial !== void 0) {
|
|
2809
|
+
if (isBundleFile(o.initial)) file = o.initial;
|
|
2810
|
+
else platform.warn?.("[QafkaCMS] contentBundle.initial is not a bundle file (formatVersion 1); ignored");
|
|
2811
|
+
}
|
|
2812
|
+
let memo = /* @__PURE__ */ new Map();
|
|
2813
|
+
let error = null;
|
|
2814
|
+
let revision = 0;
|
|
2815
|
+
let hydrated = false;
|
|
2816
|
+
let settled = false;
|
|
2817
|
+
let hydration = null;
|
|
2818
|
+
let running = null;
|
|
2819
|
+
let override;
|
|
2820
|
+
const notify = () => {
|
|
2821
|
+
revision++;
|
|
2822
|
+
for (const l of [...listeners]) l();
|
|
2823
|
+
};
|
|
2824
|
+
const setFile = (next) => {
|
|
2825
|
+
file = next;
|
|
2826
|
+
memo = /* @__PURE__ */ new Map();
|
|
2827
|
+
};
|
|
2828
|
+
const wanted = () => override ?? o.locale ?? language?.getLanguage() ?? null;
|
|
2829
|
+
const readIndex = async () => {
|
|
2830
|
+
try {
|
|
2831
|
+
const idx = JSON.parse(await storage2.getItem(STORAGE_KEY_BUNDLE_INDEX) ?? "null");
|
|
2832
|
+
if (idx && typeof idx.files === "object" && idx.files) return idx;
|
|
2833
|
+
} catch {
|
|
2834
|
+
}
|
|
2835
|
+
return { current: null, files: {} };
|
|
2836
|
+
};
|
|
2837
|
+
const loadStored = async (locale) => {
|
|
2838
|
+
try {
|
|
2839
|
+
const raw = await storage2.getItem(fileKey(locale));
|
|
2840
|
+
const parsed = raw ? JSON.parse(raw) : null;
|
|
2841
|
+
return isBundleFile(parsed) ? parsed : null;
|
|
2842
|
+
} catch {
|
|
2843
|
+
return null;
|
|
2844
|
+
}
|
|
2845
|
+
};
|
|
2846
|
+
const ready = () => hydration ?? (hydration = (async () => {
|
|
2847
|
+
try {
|
|
2848
|
+
const index = await readIndex();
|
|
2849
|
+
const want = wanted();
|
|
2850
|
+
const locale = want !== null && index.files[want] !== void 0 ? want : index.current;
|
|
2851
|
+
const stored = locale ? await loadStored(locale) : null;
|
|
2852
|
+
const better = (s, f) => s.locale === f.locale ? s.version >= f.version : f.locale !== want;
|
|
2853
|
+
if (stored && (!file || better(stored, file))) setFile(stored);
|
|
2854
|
+
} finally {
|
|
2855
|
+
hydrated = true;
|
|
2856
|
+
notify();
|
|
2857
|
+
}
|
|
2858
|
+
})());
|
|
2859
|
+
const persist = async (next, text) => {
|
|
2860
|
+
const index = await readIndex();
|
|
2861
|
+
if (await storage2.setItem(fileKey(next.locale), text)) {
|
|
2862
|
+
await storage2.removeItem(fileKey(next.locale));
|
|
2863
|
+
throw new Error("storage quota exceeded");
|
|
2864
|
+
}
|
|
2865
|
+
const files = { [next.locale]: next.version };
|
|
2866
|
+
const stale = [];
|
|
2867
|
+
for (const [loc, v] of Object.entries(index.files)) {
|
|
2868
|
+
if (loc === next.locale) continue;
|
|
2869
|
+
if (v === next.version) files[loc] = v;
|
|
2870
|
+
else stale.push(fileKey(loc));
|
|
2871
|
+
}
|
|
2872
|
+
if (stale.length) await storage2.multiRemove(stale);
|
|
2873
|
+
await storage2.setItem(STORAGE_KEY_BUNDLE_INDEX, JSON.stringify({ current: next.locale, files }));
|
|
2874
|
+
};
|
|
2875
|
+
const download = async (url) => {
|
|
2876
|
+
const { href, sameOrigin } = resolveBundleUrl(o.apiUrl, url);
|
|
2877
|
+
const headers = sameOrigin ? await http.securityHeaders({}, { method: "GET", path: href }) : {};
|
|
2878
|
+
const res = await platform.fetch(href, { method: "GET", headers });
|
|
2879
|
+
if (!res.ok) throw await toProblemError(res);
|
|
2880
|
+
return res.text();
|
|
2881
|
+
};
|
|
2882
|
+
const run = async (locale) => {
|
|
2883
|
+
let m;
|
|
2884
|
+
try {
|
|
2885
|
+
m = await http.request("GET", "/content-bundle", { query: { locale } });
|
|
2886
|
+
} catch (e) {
|
|
2887
|
+
if (!(e instanceof ProblemError && e.status === 404 && e.raw.code === "CONTENT_BUNDLE_NOT_FOUND")) throw e;
|
|
2888
|
+
const had = file !== null;
|
|
2889
|
+
setFile(null);
|
|
2890
|
+
const index = await readIndex();
|
|
2891
|
+
await storage2.multiRemove([...Object.keys(index.files).map(fileKey), STORAGE_KEY_BUNDLE_INDEX]);
|
|
2892
|
+
return { version: null, changed: had };
|
|
2893
|
+
}
|
|
2894
|
+
if (!m || typeof m.version !== "number" || typeof m.url !== "string") {
|
|
2895
|
+
throw new Error("QafkaCMS: invalid content bundle manifest");
|
|
2896
|
+
}
|
|
2897
|
+
if (file && file.version === m.version && file.locale === m.locale) return { version: m.version, changed: false };
|
|
2898
|
+
let next = await loadStored(m.locale);
|
|
2899
|
+
let text = null;
|
|
2900
|
+
if (!next || next.version !== m.version) {
|
|
2901
|
+
text = await download(m.url);
|
|
2902
|
+
let parsed;
|
|
2903
|
+
try {
|
|
2904
|
+
parsed = JSON.parse(text);
|
|
2905
|
+
} catch {
|
|
2906
|
+
throw new Error("QafkaCMS: the content bundle file is not valid JSON");
|
|
2907
|
+
}
|
|
2908
|
+
if (!isBundleFile(parsed)) {
|
|
2909
|
+
throw new Error("QafkaCMS: unsupported content bundle file (formatVersion 1 expected)");
|
|
2910
|
+
}
|
|
2911
|
+
if (parsed.version !== m.version) {
|
|
2912
|
+
throw new Error(`QafkaCMS: content bundle version ${parsed.version} \u2260 announced ${m.version}`);
|
|
2913
|
+
}
|
|
2914
|
+
next = parsed;
|
|
2915
|
+
}
|
|
2916
|
+
setFile(next);
|
|
2917
|
+
try {
|
|
2918
|
+
if (text !== null) await persist(next, text);
|
|
2919
|
+
else {
|
|
2920
|
+
const index = await readIndex();
|
|
2921
|
+
await storage2.setItem(STORAGE_KEY_BUNDLE_INDEX, JSON.stringify({ ...index, current: next.locale }));
|
|
2922
|
+
}
|
|
2923
|
+
} catch (e) {
|
|
2924
|
+
platform.warn?.("[QafkaCMS] content bundle could not be stored (kept in memory for this session)", e);
|
|
2925
|
+
}
|
|
2926
|
+
return { version: m.version, changed: true };
|
|
2927
|
+
};
|
|
2928
|
+
const sync = (options = {}) => {
|
|
2929
|
+
if (options.locale) override = options.locale;
|
|
2930
|
+
const locale = wanted();
|
|
2931
|
+
if (running && running.locale === locale) return running.promise;
|
|
2932
|
+
const before = running?.promise;
|
|
2933
|
+
const promise = (async () => {
|
|
2934
|
+
await before?.catch(() => void 0);
|
|
2935
|
+
await ready().catch(() => void 0);
|
|
2936
|
+
try {
|
|
2937
|
+
const result = await run(locale);
|
|
2938
|
+
error = null;
|
|
2939
|
+
return result;
|
|
2940
|
+
} catch (e) {
|
|
2941
|
+
throw error = toError(e);
|
|
2942
|
+
}
|
|
2943
|
+
})();
|
|
2944
|
+
running = { locale, promise };
|
|
2945
|
+
const done = () => {
|
|
2946
|
+
if (running?.promise === promise) running = null;
|
|
2947
|
+
settled = true;
|
|
2948
|
+
notify();
|
|
2949
|
+
};
|
|
2950
|
+
promise.then(done, done);
|
|
2951
|
+
notify();
|
|
2952
|
+
return promise;
|
|
2953
|
+
};
|
|
2954
|
+
const collection = (name) => {
|
|
2955
|
+
let m = memo.get(name);
|
|
2956
|
+
if (!m) memo.set(name, m = { rows: file ? filterBundleRows(file, name, appVersion) : EMPTY2 });
|
|
2957
|
+
return m;
|
|
2958
|
+
};
|
|
2959
|
+
const getRow = (name, id) => {
|
|
2960
|
+
if (!file) return null;
|
|
2961
|
+
const m = collection(name);
|
|
2962
|
+
m.byId ?? (m.byId = new Map(m.rows.map((r) => [String(r.id), r])));
|
|
2963
|
+
return m.byId.get(String(id)) ?? null;
|
|
2964
|
+
};
|
|
2965
|
+
let views = /* @__PURE__ */ new Map();
|
|
2966
|
+
let viewsRevision = -1;
|
|
2967
|
+
const cachedView = (key, make) => {
|
|
2968
|
+
if (viewsRevision !== revision) {
|
|
2969
|
+
views = /* @__PURE__ */ new Map();
|
|
2970
|
+
viewsRevision = revision;
|
|
2971
|
+
}
|
|
2972
|
+
if (!views.has(key)) views.set(key, make());
|
|
2973
|
+
return views.get(key);
|
|
2974
|
+
};
|
|
2975
|
+
const status = () => ({ version: file?.version ?? null, isLoading: isLoading(), error });
|
|
2976
|
+
const isLoading = () => !file && (!hydrated || !settled || running !== null);
|
|
2977
|
+
const start = () => {
|
|
2978
|
+
const kick = () => void sync().catch(() => void 0);
|
|
2979
|
+
kick();
|
|
2980
|
+
const offApp = platform.appState?.subscribe((active) => active && kick());
|
|
2981
|
+
let last = language?.getLanguage() ?? null;
|
|
2982
|
+
const offLocale = language?.subscribe(() => {
|
|
2983
|
+
const next = language.getLanguage();
|
|
2984
|
+
if (next === last) return;
|
|
2985
|
+
last = next;
|
|
2986
|
+
override = void 0;
|
|
2987
|
+
if (!o.locale) kick();
|
|
2988
|
+
});
|
|
2989
|
+
return () => {
|
|
2990
|
+
offApp?.();
|
|
2991
|
+
offLocale?.();
|
|
2992
|
+
};
|
|
2993
|
+
};
|
|
2994
|
+
return {
|
|
2995
|
+
get version() {
|
|
2996
|
+
return file?.version ?? null;
|
|
2997
|
+
},
|
|
2998
|
+
get locale() {
|
|
2999
|
+
return file?.locale ?? null;
|
|
3000
|
+
},
|
|
3001
|
+
get error() {
|
|
3002
|
+
return error;
|
|
3003
|
+
},
|
|
3004
|
+
get isLoading() {
|
|
3005
|
+
return isLoading();
|
|
3006
|
+
},
|
|
3007
|
+
get revision() {
|
|
3008
|
+
return revision;
|
|
3009
|
+
},
|
|
3010
|
+
sync,
|
|
3011
|
+
ready,
|
|
3012
|
+
rows: (name) => collection(name).rows,
|
|
3013
|
+
get: getRow,
|
|
3014
|
+
view: (name) => cachedView(`r
|
|
3015
|
+
${name}`, () => ({ rows: collection(name).rows, ...status() })),
|
|
3016
|
+
itemView: (name, id) => cachedView(`i
|
|
3017
|
+
${name}
|
|
3018
|
+
${id ?? ""}`, () => ({ data: id ? getRow(name, id) : null, ...status() })),
|
|
3019
|
+
subscribe: (listener) => {
|
|
3020
|
+
void ready();
|
|
3021
|
+
listeners.add(listener);
|
|
3022
|
+
return () => void listeners.delete(listener);
|
|
3023
|
+
},
|
|
3024
|
+
start
|
|
3025
|
+
};
|
|
3026
|
+
}
|
|
3027
|
+
|
|
3028
|
+
// ../core/src/color/resolveColor.ts
|
|
3029
|
+
var HEX = /^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$/;
|
|
3030
|
+
function isPlainColor(v) {
|
|
3031
|
+
if (typeof v === "string") return HEX.test(v);
|
|
3032
|
+
return typeof v === "object" && v !== null && !Array.isArray(v) && Array.isArray(v.stops);
|
|
3033
|
+
}
|
|
3034
|
+
function resolveColor(value, scheme) {
|
|
3035
|
+
if (isPlainColor(value)) return value;
|
|
3036
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) return null;
|
|
3037
|
+
const { light, dark } = value;
|
|
3038
|
+
if (!isPlainColor(light)) return null;
|
|
3039
|
+
if (scheme === "dark" && isPlainColor(dark)) return dark;
|
|
3040
|
+
return light;
|
|
3041
|
+
}
|
|
3042
|
+
|
|
3043
|
+
// ../core/src/services/storageCore.ts
|
|
3044
|
+
var FALLBACK_WARNING = "[QafkaCMS] Native QafkaCmsStorage module not registered \u2014 falling back to in-memory storage. Persistence will be lost when the app closes. This usually means autolinking failed or the app was not rebuilt after upgrading the SDK.";
|
|
3045
|
+
function createStorage(native2, warn) {
|
|
3046
|
+
if (native2) {
|
|
3047
|
+
return {
|
|
3048
|
+
getItem: (key) => native2.getItem(key),
|
|
3049
|
+
setItem: (key, value) => native2.setItem(key, value),
|
|
3050
|
+
removeItem: (key) => native2.removeItem(key),
|
|
3051
|
+
multiRemove: (keys) => native2.multiRemove(keys)
|
|
3052
|
+
};
|
|
3053
|
+
}
|
|
3054
|
+
const memory = /* @__PURE__ */ new Map();
|
|
3055
|
+
let warned = false;
|
|
3056
|
+
const warnOnce = () => {
|
|
3057
|
+
if (!warned) {
|
|
3058
|
+
warn?.(FALLBACK_WARNING);
|
|
3059
|
+
warned = true;
|
|
3060
|
+
}
|
|
3061
|
+
};
|
|
3062
|
+
return {
|
|
3063
|
+
async getItem(key) {
|
|
3064
|
+
warnOnce();
|
|
3065
|
+
return memory.has(key) ? memory.get(key) : null;
|
|
3066
|
+
},
|
|
3067
|
+
async setItem(key, value) {
|
|
3068
|
+
warnOnce();
|
|
3069
|
+
memory.set(key, value);
|
|
3070
|
+
},
|
|
3071
|
+
async removeItem(key) {
|
|
3072
|
+
warnOnce();
|
|
3073
|
+
memory.delete(key);
|
|
3074
|
+
},
|
|
3075
|
+
async multiRemove(keys) {
|
|
3076
|
+
warnOnce();
|
|
3077
|
+
for (const k of keys) memory.delete(k);
|
|
3078
|
+
}
|
|
3079
|
+
};
|
|
3080
|
+
}
|
|
3081
|
+
|
|
3082
|
+
// ../core/src/types/filter.ts
|
|
3083
|
+
var CURRENT_USER = "$CURRENT_USER";
|
|
3084
|
+
var NOW = "$NOW";
|
|
3085
|
+
var NOW_OFFSET = /^[+-]\d{1,6}[mhdw]$/;
|
|
3086
|
+
function now(offset) {
|
|
3087
|
+
if (offset === void 0) return NOW;
|
|
3088
|
+
if (!NOW_OFFSET.test(offset)) {
|
|
3089
|
+
throw new Error(
|
|
3090
|
+
`QafkaCMS: invalid now() offset ${JSON.stringify(offset)}; expected a signed count and unit such as '+7d', '-1w', '+2h', '-30m' (units m, h, d, w)`
|
|
3091
|
+
);
|
|
3092
|
+
}
|
|
3093
|
+
return `$NOW(${offset})`;
|
|
3094
|
+
}
|
|
3095
|
+
|
|
3096
|
+
// src/native/QafkaCmsAttestation.ts
|
|
3097
|
+
var import_react_native = require("react-native");
|
|
3098
|
+
var mod = import_react_native.NativeModules.QafkaCmsAttestation ?? null;
|
|
3099
|
+
function getDeviceInfo() {
|
|
3100
|
+
return {
|
|
3101
|
+
bundleId: mod?.bundleId ?? "",
|
|
3102
|
+
appVersion: mod?.appVersion ?? "",
|
|
3103
|
+
deviceModel: mod?.deviceModel ?? ""
|
|
3104
|
+
};
|
|
3105
|
+
}
|
|
3106
|
+
function isAttestationAvailable() {
|
|
3107
|
+
return mod !== null;
|
|
3108
|
+
}
|
|
3109
|
+
var nativeAttestation = {
|
|
3110
|
+
isAvailable: () => mod !== null,
|
|
3111
|
+
async isSupported() {
|
|
3112
|
+
if (!mod) return false;
|
|
3113
|
+
try {
|
|
3114
|
+
return await mod.isSupported();
|
|
3115
|
+
} catch {
|
|
3116
|
+
return false;
|
|
3117
|
+
}
|
|
3118
|
+
},
|
|
3119
|
+
generateKey() {
|
|
3120
|
+
if (!mod?.generateKey) throw new Error("iOS only");
|
|
3121
|
+
return mod.generateKey();
|
|
3122
|
+
},
|
|
3123
|
+
attestKey(keyId, challengeBase64) {
|
|
3124
|
+
if (!mod?.attestKey) throw new Error("iOS only");
|
|
3125
|
+
return mod.attestKey(keyId, challengeBase64);
|
|
3126
|
+
},
|
|
3127
|
+
generateAssertion(keyId, clientDataBase64) {
|
|
3128
|
+
if (!mod?.generateAssertion) throw new Error("iOS only");
|
|
3129
|
+
return mod.generateAssertion(keyId, clientDataBase64);
|
|
3130
|
+
},
|
|
3131
|
+
generateKeyPair(alias, challengeBase64) {
|
|
3132
|
+
if (!mod?.generateKeyPair) throw new Error("Android only");
|
|
3133
|
+
return mod.generateKeyPair(alias, challengeBase64);
|
|
3134
|
+
},
|
|
3135
|
+
getAttestationCertChain(alias) {
|
|
3136
|
+
if (!mod?.getAttestationCertChain) throw new Error("Android only");
|
|
3137
|
+
return mod.getAttestationCertChain(alias);
|
|
3138
|
+
}
|
|
3139
|
+
};
|
|
3140
|
+
|
|
3141
|
+
// src/native/QafkaCmsStorage.ts
|
|
3142
|
+
var import_react_native2 = require("react-native");
|
|
3143
|
+
var native = import_react_native2.NativeModules.QafkaCmsStorage ?? null;
|
|
3144
|
+
function getNativeStorage() {
|
|
3145
|
+
return native;
|
|
3146
|
+
}
|
|
3147
|
+
|
|
3148
|
+
// src/services/storage.ts
|
|
3149
|
+
var storage = createStorage(getNativeStorage(), (message) => {
|
|
3150
|
+
if (typeof __DEV__ !== "undefined" && __DEV__) console.warn(message);
|
|
3151
|
+
});
|
|
3152
|
+
|
|
3153
|
+
// src/services/AttestationManager.ts
|
|
3154
|
+
var import_react_native3 = require("react-native");
|
|
3155
|
+
var PROJECT_ERROR_CODES = /PROJECT_KEY_REQUIRED|INVALID_PROJECT_KEY|APP_NOT_REGISTERED|PROJECT_MISMATCH|PROJECT_REQUIRED|ATTESTATION_REQUIRED|ATTESTATION_SESSION_EXPIRED/;
|
|
3156
|
+
var DEV_BYPASS = "dev-bypass";
|
|
3157
|
+
var EXPIRY_MARGIN_MS = 6e4;
|
|
3158
|
+
var AttestationManager = class {
|
|
3159
|
+
constructor(config, deps) {
|
|
3160
|
+
__publicField(this, "config");
|
|
3161
|
+
__publicField(this, "d");
|
|
3162
|
+
__publicField(this, "sessionToken", null);
|
|
3163
|
+
__publicField(this, "keyId", null);
|
|
3164
|
+
/** The attestation/assertion in flight; concurrent callers share it. */
|
|
3165
|
+
__publicField(this, "inflight", null);
|
|
3166
|
+
this.config = config;
|
|
3167
|
+
this.d = {
|
|
3168
|
+
native: deps?.native ?? nativeAttestation,
|
|
3169
|
+
storage: deps?.storage ?? storage,
|
|
3170
|
+
fetch: deps?.fetch ?? ((url, init) => fetch(url, init)),
|
|
3171
|
+
platformOS: deps?.platformOS ?? import_react_native3.Platform.OS,
|
|
3172
|
+
now: deps?.now ?? Date.now
|
|
3173
|
+
};
|
|
3174
|
+
}
|
|
3175
|
+
async initialize() {
|
|
3176
|
+
return this.exclusive(() => this.doInitialize());
|
|
3177
|
+
}
|
|
3178
|
+
/**
|
|
3179
|
+
* Run one attestation operation at a time. A second caller joins the one in
|
|
3180
|
+
* flight instead of starting its own: attesting a key twice makes Apple
|
|
3181
|
+
* refuse it and the stale-key path would mint an extra key.
|
|
3182
|
+
*/
|
|
3183
|
+
exclusive(op) {
|
|
3184
|
+
if (this.inflight) return this.inflight;
|
|
3185
|
+
const run = op().finally(() => {
|
|
3186
|
+
if (this.inflight === run) this.inflight = null;
|
|
3187
|
+
});
|
|
3188
|
+
this.inflight = run;
|
|
3189
|
+
return run;
|
|
3190
|
+
}
|
|
3191
|
+
async doInitialize() {
|
|
3192
|
+
const moduleLinked = this.d.native.isAvailable?.() ?? isAttestationAvailable();
|
|
3193
|
+
const supported = await this.d.native.isSupported();
|
|
3194
|
+
if (!supported) {
|
|
3195
|
+
const reason = !moduleLinked ? "the QafkaCmsAttestation native module is not registered (rebuild your app after installing the SDK)" : "this device does not support attestation (Android 8.0+ / iOS 14+ required)";
|
|
3196
|
+
if (typeof __DEV__ !== "undefined" && __DEV__) {
|
|
3197
|
+
console.warn(
|
|
3198
|
+
`[QafkaCMS] Attestation unavailable \u2014 entering dev-bypass because ${reason}. Requests will omit the session token.`
|
|
3199
|
+
);
|
|
3200
|
+
this.sessionToken = { token: DEV_BYPASS, expiresAt: this.d.now() + 30 * 60 * 1e3 };
|
|
3201
|
+
return;
|
|
3202
|
+
}
|
|
3203
|
+
throw new Error(`Device attestation is not supported: ${reason}.`);
|
|
3204
|
+
}
|
|
3205
|
+
if (this.d.platformOS === "ios") {
|
|
3206
|
+
await this.initializeIos();
|
|
3207
|
+
} else if (this.d.platformOS === "android") {
|
|
3208
|
+
await this.performAndroidAttestation();
|
|
3209
|
+
}
|
|
3210
|
+
}
|
|
3211
|
+
/**
|
|
3212
|
+
* iOS start: an attested key is reused through an assertion (Apple allows a
|
|
3213
|
+
* single attestation per key); without one a new key is attested.
|
|
3214
|
+
*/
|
|
3215
|
+
async initializeIos() {
|
|
3216
|
+
this.keyId = await this.d.storage.getItem(STORAGE_KEY_ATTESTATION_KEY_ID);
|
|
3217
|
+
if (!this.keyId) {
|
|
3218
|
+
await this.attestNewIosKey();
|
|
3219
|
+
return;
|
|
3220
|
+
}
|
|
3221
|
+
await this.assertOrReattestIos();
|
|
3222
|
+
}
|
|
3223
|
+
/**
|
|
3224
|
+
* Assertion with the stored key. Network, server (5xx) and project errors say
|
|
3225
|
+
* nothing about the key: keep it and propagate. Anything else (key unknown to
|
|
3226
|
+
* the server, key invalid on this device after a restore) starts a new key.
|
|
3227
|
+
*/
|
|
3228
|
+
async assertOrReattestIos() {
|
|
3229
|
+
try {
|
|
3230
|
+
await this.performIosAssertion();
|
|
3231
|
+
} catch (err) {
|
|
3232
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
3233
|
+
if (PROJECT_ERROR_CODES.test(msg) || /network|fetch|offline|timed out|\b5\d\d\b/i.test(msg)) throw err;
|
|
3234
|
+
await this.d.storage.removeItem(STORAGE_KEY_ATTESTATION_KEY_ID);
|
|
3235
|
+
await this.attestNewIosKey();
|
|
3236
|
+
}
|
|
3237
|
+
}
|
|
3238
|
+
/**
|
|
3239
|
+
* Generate and attest a new key; it is stored only once the server accepted
|
|
3240
|
+
* it, so a failed attempt never leaves an unattested key behind.
|
|
3241
|
+
*/
|
|
3242
|
+
async attestNewIosKey() {
|
|
3243
|
+
this.keyId = await this.d.native.generateKey();
|
|
3244
|
+
try {
|
|
3245
|
+
await this.performIosAttestation();
|
|
3246
|
+
} catch (err) {
|
|
3247
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
3248
|
+
const looksLikeStaleNativeKey = !PROJECT_ERROR_CODES.test(msg) && !/HTTP|\b401\b|\b403\b|\b404\b|\b5\d\d\b|app not registered|app_not_registered|fetch|network/i.test(msg) && (/invalid|not found|unknown|key|attestation/i.test(msg) || /com\.apple\.devicecheck\.error/i.test(msg) || /android\.security\.keystore/i.test(msg));
|
|
3249
|
+
if (!looksLikeStaleNativeKey) throw err;
|
|
3250
|
+
await this.d.storage.removeItem(STORAGE_KEY_ATTESTATION_KEY_ID);
|
|
3251
|
+
this.keyId = await this.d.native.generateKey();
|
|
3252
|
+
await this.performIosAttestation();
|
|
3253
|
+
}
|
|
3254
|
+
await this.d.storage.setItem(STORAGE_KEY_ATTESTATION_KEY_ID, this.keyId);
|
|
3255
|
+
}
|
|
3256
|
+
async performIosAttestation() {
|
|
3257
|
+
const challenge = await this.requestChallenge("ios");
|
|
3258
|
+
const attestationData = await this.d.native.attestKey(this.keyId, challenge);
|
|
3259
|
+
const res = await this.submitAttestation({ platform: "ios", attestationData, keyId: this.keyId, challenge });
|
|
3260
|
+
this.setSession(res);
|
|
3261
|
+
}
|
|
3262
|
+
async performIosAssertion() {
|
|
3263
|
+
const challenge = await this.requestChallenge("ios");
|
|
3264
|
+
const assertionData = await this.d.native.generateAssertion(this.keyId, challenge);
|
|
3265
|
+
const res = await this.submitAttestation({
|
|
3266
|
+
platform: "ios",
|
|
3267
|
+
attestationData: assertionData,
|
|
3268
|
+
keyId: this.keyId,
|
|
3269
|
+
challenge,
|
|
3270
|
+
isAssertion: true
|
|
3271
|
+
});
|
|
3272
|
+
this.setSession(res);
|
|
3273
|
+
}
|
|
3274
|
+
async performAndroidAttestation() {
|
|
3275
|
+
const challenge = await this.requestChallenge("android");
|
|
3276
|
+
await this.d.native.generateKeyPair(ANDROID_ATTEST_ALIAS, challenge);
|
|
3277
|
+
const certChain = await this.d.native.getAttestationCertChain(ANDROID_ATTEST_ALIAS);
|
|
3278
|
+
const res = await this.submitAttestation({ platform: "android", certChain, challenge });
|
|
3279
|
+
this.setSession(res);
|
|
3280
|
+
}
|
|
3281
|
+
async getSessionToken() {
|
|
3282
|
+
if (this.inflight) await this.inflight.catch(() => void 0);
|
|
3283
|
+
if (this.sessionToken?.token === DEV_BYPASS) return null;
|
|
3284
|
+
if (this.sessionToken && this.d.now() < this.sessionToken.expiresAt - EXPIRY_MARGIN_MS) {
|
|
3285
|
+
return this.sessionToken.token;
|
|
3286
|
+
}
|
|
3287
|
+
try {
|
|
3288
|
+
await this.exclusive(() => this.refreshSession());
|
|
3289
|
+
return this.sessionToken?.token ?? null;
|
|
3290
|
+
} catch {
|
|
3291
|
+
return null;
|
|
3292
|
+
}
|
|
3293
|
+
}
|
|
3294
|
+
/** Called by the transport when the backend signals a refresh (429 / budget). */
|
|
3295
|
+
async refresh() {
|
|
3296
|
+
if (this.isDevBypass()) return null;
|
|
3297
|
+
try {
|
|
3298
|
+
await this.exclusive(() => this.refreshSession());
|
|
3299
|
+
return this.sessionToken?.token ?? null;
|
|
3300
|
+
} catch {
|
|
3301
|
+
return null;
|
|
3302
|
+
}
|
|
3303
|
+
}
|
|
3304
|
+
/**
|
|
3305
|
+
* Replace the session with a new one started after this call and return its
|
|
3306
|
+
* token. Unlike {@link refresh} it rejects on failure, so callers never keep a
|
|
3307
|
+
* stale token by accident. `null` only in dev-bypass (there is no session).
|
|
3308
|
+
*/
|
|
3309
|
+
async forceRefresh() {
|
|
3310
|
+
if (this.inflight) await this.inflight.catch(() => void 0);
|
|
3311
|
+
if (this.isDevBypass()) return null;
|
|
3312
|
+
await this.exclusive(() => this.refreshSession());
|
|
3313
|
+
return this.sessionToken.token;
|
|
3314
|
+
}
|
|
3315
|
+
async refreshSession() {
|
|
3316
|
+
if (this.d.platformOS === "android") {
|
|
3317
|
+
await this.performAndroidAttestation();
|
|
3318
|
+
return;
|
|
3319
|
+
}
|
|
3320
|
+
if (!this.keyId) {
|
|
3321
|
+
await this.initializeIos();
|
|
3322
|
+
return;
|
|
3323
|
+
}
|
|
3324
|
+
await this.assertOrReattestIos();
|
|
3325
|
+
}
|
|
3326
|
+
isDevBypass() {
|
|
3327
|
+
return this.sessionToken?.token === DEV_BYPASS;
|
|
3328
|
+
}
|
|
3329
|
+
async reset() {
|
|
3330
|
+
this.sessionToken = null;
|
|
3331
|
+
this.keyId = null;
|
|
3332
|
+
await this.d.storage.removeItem(STORAGE_KEY_ATTESTATION_KEY_ID);
|
|
3333
|
+
}
|
|
3334
|
+
// --- transport ----------------------------------------------------------
|
|
3335
|
+
setSession(res) {
|
|
3336
|
+
this.sessionToken = { token: res.sessionToken, expiresAt: this.d.now() + res.expiresIn * 1e3 };
|
|
3337
|
+
}
|
|
3338
|
+
getHeaders() {
|
|
3339
|
+
const headers = { "Content-Type": "application/json" };
|
|
3340
|
+
if (this.config.projectId) headers["X-Project-Id"] = this.config.projectId;
|
|
3341
|
+
if (this.config.publishableKey) headers["X-Project-Key"] = this.config.publishableKey;
|
|
3342
|
+
if (this.config.projectSlug) headers["X-Project-Slug"] = this.config.projectSlug;
|
|
3343
|
+
if (this.config.apiKey) headers["x-api-key"] = this.config.apiKey;
|
|
3344
|
+
return headers;
|
|
3345
|
+
}
|
|
3346
|
+
async requestChallenge(platform) {
|
|
3347
|
+
const url = `${this.base()}/challenge`;
|
|
3348
|
+
const response = await this.d.fetch(url, {
|
|
3349
|
+
method: "POST",
|
|
3350
|
+
headers: this.getHeaders(),
|
|
3351
|
+
body: JSON.stringify({ platform })
|
|
3352
|
+
});
|
|
3353
|
+
if (!response.ok) throw new Error(`Challenge request failed: HTTP ${response.status}`);
|
|
3354
|
+
const data = await response.json();
|
|
3355
|
+
return data.challenge;
|
|
3356
|
+
}
|
|
3357
|
+
async submitAttestation(body) {
|
|
3358
|
+
const url = this.base();
|
|
3359
|
+
const response = await this.d.fetch(url, {
|
|
3360
|
+
method: "POST",
|
|
3361
|
+
headers: this.getHeaders(),
|
|
3362
|
+
body: JSON.stringify(body)
|
|
3363
|
+
});
|
|
3364
|
+
if (!response.ok) {
|
|
3365
|
+
const errorData = await response.json().catch(() => ({}));
|
|
3366
|
+
const errorCode = errorData.code ?? errorData.error;
|
|
3367
|
+
const code = errorCode ? ` ${errorCode}` : "";
|
|
3368
|
+
throw new Error(
|
|
3369
|
+
`Attestation failed: ${response.status}${code} \u2014 ${errorData.message || errorData.detail || "Unknown error"}`
|
|
3370
|
+
);
|
|
3371
|
+
}
|
|
3372
|
+
return await response.json();
|
|
3373
|
+
}
|
|
3374
|
+
base() {
|
|
3375
|
+
return `${this.config.apiUrl.replace(/\/$/, "")}${END_USER_BASE_PATH}/attest`;
|
|
3376
|
+
}
|
|
3377
|
+
};
|
|
3378
|
+
|
|
3379
|
+
// src/config-sync/sse.ts
|
|
3380
|
+
var SSE_RECYCLE_AFTER_CHARS = 1e6;
|
|
3381
|
+
var SSE_MAX_PENDING_CHARS = 65536;
|
|
3382
|
+
function normalizeNewlines(text) {
|
|
3383
|
+
const held = text.endsWith("\r") ? "\r" : "";
|
|
3384
|
+
const body = held ? text.slice(0, -1) : text;
|
|
3385
|
+
return { text: body.replace(/\r\n?/g, "\n"), held };
|
|
3386
|
+
}
|
|
3387
|
+
function blockData(block) {
|
|
3388
|
+
const lines = [];
|
|
3389
|
+
for (const line of block.split("\n")) {
|
|
3390
|
+
if (line === "data") {
|
|
3391
|
+
lines.push("");
|
|
3392
|
+
} else if (line.startsWith("data:")) {
|
|
3393
|
+
const value = line.slice("data:".length);
|
|
3394
|
+
lines.push(value.startsWith(" ") ? value.slice(1) : value);
|
|
3395
|
+
}
|
|
3396
|
+
}
|
|
3397
|
+
return lines.length ? lines.join("\n") : null;
|
|
3398
|
+
}
|
|
3399
|
+
function createXhrSseConnector(options = {}) {
|
|
3400
|
+
const recycleAfter = options.recycleAfterChars ?? SSE_RECYCLE_AFTER_CHARS;
|
|
3401
|
+
return (url, headers, handlers) => {
|
|
3402
|
+
const Xhr = options.XMLHttpRequest ?? XMLHttpRequest;
|
|
3403
|
+
const xhr = new Xhr();
|
|
3404
|
+
let consumed = 0;
|
|
3405
|
+
let pending = "";
|
|
3406
|
+
let heldCr = "";
|
|
3407
|
+
let done = false;
|
|
3408
|
+
let typeChecked = false;
|
|
3409
|
+
const end = () => {
|
|
3410
|
+
done = true;
|
|
3411
|
+
try {
|
|
3412
|
+
xhr.abort();
|
|
3413
|
+
} catch {
|
|
3414
|
+
}
|
|
3415
|
+
};
|
|
3416
|
+
const fail = (err) => {
|
|
3417
|
+
if (done) return;
|
|
3418
|
+
end();
|
|
3419
|
+
handlers.onError(err);
|
|
3420
|
+
};
|
|
3421
|
+
const dispatch = (block) => {
|
|
3422
|
+
const data = blockData(block);
|
|
3423
|
+
if (!data) return;
|
|
3424
|
+
let event;
|
|
3425
|
+
try {
|
|
3426
|
+
event = JSON.parse(data);
|
|
3427
|
+
} catch {
|
|
3428
|
+
return;
|
|
3429
|
+
}
|
|
3430
|
+
try {
|
|
3431
|
+
handlers.onMessage(event);
|
|
3432
|
+
} catch {
|
|
3433
|
+
}
|
|
3434
|
+
};
|
|
3435
|
+
const checkType = () => {
|
|
3436
|
+
if (typeChecked || xhr.readyState < 2 || typeof xhr.getResponseHeader !== "function") return true;
|
|
3437
|
+
typeChecked = true;
|
|
3438
|
+
const type = xhr.getResponseHeader("content-type");
|
|
3439
|
+
if (type === null || type.toLowerCase().includes("text/event-stream")) return true;
|
|
3440
|
+
fail(new Error(`SSE unexpected content-type: ${type}`));
|
|
3441
|
+
return false;
|
|
3442
|
+
};
|
|
3443
|
+
const parse = () => {
|
|
3444
|
+
if (done || !checkType()) return;
|
|
3445
|
+
const text = xhr.responseText;
|
|
3446
|
+
if (text.length <= consumed) return;
|
|
3447
|
+
const { text: fresh, held } = normalizeNewlines(heldCr + text.slice(consumed));
|
|
3448
|
+
consumed = text.length;
|
|
3449
|
+
heldCr = held;
|
|
3450
|
+
pending += fresh;
|
|
3451
|
+
const boundary = pending.lastIndexOf("\n\n");
|
|
3452
|
+
if (boundary >= 0) {
|
|
3453
|
+
const complete = pending.slice(0, boundary);
|
|
3454
|
+
pending = pending.slice(boundary + 2);
|
|
3455
|
+
for (const block of complete.split("\n\n")) {
|
|
3456
|
+
if (done) return;
|
|
3457
|
+
dispatch(block);
|
|
3458
|
+
}
|
|
3459
|
+
}
|
|
3460
|
+
if (!done && pending.length > SSE_MAX_PENDING_CHARS) {
|
|
3461
|
+
fail(new Error("SSE event exceeds 64 KB"));
|
|
3462
|
+
return;
|
|
3463
|
+
}
|
|
3464
|
+
if (boundary < 0) return;
|
|
3465
|
+
if (!done && consumed - pending.length - heldCr.length >= recycleAfter) {
|
|
3466
|
+
end();
|
|
3467
|
+
if (handlers.onClose) handlers.onClose({ reason: "recycle" });
|
|
3468
|
+
else handlers.onError(new Error("SSE recycled"));
|
|
3469
|
+
}
|
|
3470
|
+
};
|
|
3471
|
+
xhr.open("GET", url);
|
|
3472
|
+
xhr.setRequestHeader("Accept", "text/event-stream");
|
|
3473
|
+
for (const [k, v] of Object.entries(headers)) xhr.setRequestHeader(k, v);
|
|
3474
|
+
xhr.onreadystatechange = () => {
|
|
3475
|
+
if (done) return;
|
|
3476
|
+
if (xhr.readyState >= 2 && xhr.status >= 400) {
|
|
3477
|
+
fail(new Error(`SSE HTTP ${xhr.status}`));
|
|
3478
|
+
return;
|
|
3479
|
+
}
|
|
3480
|
+
if (xhr.readyState === 4 && xhr.status === 0) {
|
|
3481
|
+
fail(new Error(`SSE closed (status ${xhr.status})`));
|
|
3482
|
+
return;
|
|
3483
|
+
}
|
|
3484
|
+
if (!checkType()) return;
|
|
3485
|
+
if (xhr.readyState >= 3) parse();
|
|
3486
|
+
};
|
|
3487
|
+
xhr.onprogress = () => parse();
|
|
3488
|
+
xhr.onerror = () => fail(new Error("SSE network error"));
|
|
3489
|
+
xhr.onload = () => {
|
|
3490
|
+
if (done) return;
|
|
3491
|
+
parse();
|
|
3492
|
+
if (done) return;
|
|
3493
|
+
done = true;
|
|
3494
|
+
if (handlers.onClose) handlers.onClose();
|
|
3495
|
+
else handlers.onOpen?.();
|
|
3496
|
+
};
|
|
3497
|
+
xhr.send();
|
|
3498
|
+
return {
|
|
3499
|
+
close() {
|
|
3500
|
+
if (done) return;
|
|
3501
|
+
end();
|
|
3502
|
+
}
|
|
3503
|
+
};
|
|
3504
|
+
};
|
|
3505
|
+
}
|
|
3506
|
+
var connectSseViaXhr = createXhrSseConnector();
|
|
3507
|
+
|
|
3508
|
+
// src/config/runtime-config-loader.ts
|
|
3509
|
+
function normalizeRuntimeConfig(raw) {
|
|
3510
|
+
if (!raw || typeof raw !== "object") return null;
|
|
3511
|
+
const obj = raw;
|
|
3512
|
+
const projectsRaw = obj.projects;
|
|
3513
|
+
const projects = {};
|
|
3514
|
+
if (projectsRaw && typeof projectsRaw === "object") {
|
|
3515
|
+
for (const [id, value] of Object.entries(projectsRaw)) {
|
|
3516
|
+
if (value && typeof value === "object") {
|
|
3517
|
+
const entry = value;
|
|
3518
|
+
const developmentKey = typeof entry.developmentKey === "string" ? entry.developmentKey : void 0;
|
|
3519
|
+
projects[id] = developmentKey !== void 0 ? { developmentKey } : {};
|
|
3520
|
+
}
|
|
3521
|
+
}
|
|
3522
|
+
}
|
|
3523
|
+
const out = { projects };
|
|
3524
|
+
if (typeof obj.defaultProjectId === "string") out.defaultProjectId = obj.defaultProjectId;
|
|
3525
|
+
if (typeof obj.apiUrl === "string") out.apiUrl = obj.apiUrl;
|
|
3526
|
+
return out;
|
|
3527
|
+
}
|
|
3528
|
+
function loadRuntimeConfig() {
|
|
3529
|
+
try {
|
|
3530
|
+
const raw = require("../qafkacms.config");
|
|
3531
|
+
return normalizeRuntimeConfig(raw);
|
|
3532
|
+
} catch {
|
|
3533
|
+
return null;
|
|
3534
|
+
}
|
|
3535
|
+
}
|
|
3536
|
+
|
|
3537
|
+
// src/config/resolve-runtime-config-source.ts
|
|
3538
|
+
function resolveRuntimeConfigSource(devConfig, loaded) {
|
|
3539
|
+
const provided = devConfig != null ? normalizeRuntimeConfig(devConfig) : null;
|
|
3540
|
+
return provided ?? loaded;
|
|
3541
|
+
}
|
|
3542
|
+
|
|
3543
|
+
// src/config/resolve-project-config.ts
|
|
3544
|
+
function resolveProjectConfig(props, runtimeConfig) {
|
|
3545
|
+
const apiUrl = props.apiUrl ?? runtimeConfig?.apiUrl ?? void 0;
|
|
3546
|
+
if (props.projectId) {
|
|
3547
|
+
const entry = runtimeConfig?.projects[props.projectId];
|
|
3548
|
+
if (!entry) {
|
|
3549
|
+
throw new RangeError(
|
|
3550
|
+
`QafkaCMS: projectId "${props.projectId}" is not in the dev config. Run \`qafka cms project\` and pass devConfig (require of .qafkacms/qafkacms-runtime).`
|
|
3551
|
+
);
|
|
3552
|
+
}
|
|
3553
|
+
return { apiKey: entry.developmentKey ?? null, apiUrl };
|
|
3554
|
+
}
|
|
3555
|
+
const defaultId = runtimeConfig?.defaultProjectId;
|
|
3556
|
+
if (defaultId) {
|
|
3557
|
+
const entry = runtimeConfig?.projects[defaultId];
|
|
3558
|
+
return { apiKey: entry?.developmentKey ?? null, apiUrl };
|
|
3559
|
+
}
|
|
3560
|
+
return { apiKey: null, apiUrl };
|
|
3561
|
+
}
|
|
3562
|
+
|
|
3563
|
+
// src/native/QafkaCmsPush.ts
|
|
3564
|
+
var import_react_native4 = require("react-native");
|
|
3565
|
+
var mod2 = import_react_native4.NativeModules.QafkaCmsPush ?? null;
|
|
3566
|
+
var UNKNOWN_INFO = { osVersion: "", model: "", brand: "" };
|
|
3567
|
+
var nativePush = {
|
|
3568
|
+
isAvailable: () => mod2 !== null,
|
|
3569
|
+
async getPermissionStatus() {
|
|
3570
|
+
if (!mod2) return "undetermined";
|
|
3571
|
+
try {
|
|
3572
|
+
return await mod2.getPermissionStatus();
|
|
3573
|
+
} catch {
|
|
3574
|
+
return "undetermined";
|
|
3575
|
+
}
|
|
3576
|
+
},
|
|
3577
|
+
async requestPermission() {
|
|
3578
|
+
if (!mod2) return "denied";
|
|
3579
|
+
return mod2.requestPermission();
|
|
3580
|
+
},
|
|
3581
|
+
async getToken(androidConfig) {
|
|
3582
|
+
if (!mod2) return null;
|
|
3583
|
+
return mod2.getToken(androidConfig ?? null);
|
|
3584
|
+
},
|
|
3585
|
+
async getDeviceInfo() {
|
|
3586
|
+
if (!mod2) return UNKNOWN_INFO;
|
|
3587
|
+
try {
|
|
3588
|
+
return await mod2.getDeviceInfo();
|
|
3589
|
+
} catch {
|
|
3590
|
+
return UNKNOWN_INFO;
|
|
3591
|
+
}
|
|
3592
|
+
}
|
|
3593
|
+
};
|
|
3594
|
+
|
|
3595
|
+
// src/push/DeviceRegistrationManager.ts
|
|
3596
|
+
var import_react_native5 = require("react-native");
|
|
3597
|
+
function randomUuid() {
|
|
3598
|
+
return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => {
|
|
3599
|
+
const r = Math.floor(Math.random() * 16);
|
|
3600
|
+
const v = c === "x" ? r : r & 3 | 8;
|
|
3601
|
+
return v.toString(16);
|
|
3602
|
+
});
|
|
3603
|
+
}
|
|
3604
|
+
var DeviceRegistrationManager = class {
|
|
3605
|
+
constructor(config, deps) {
|
|
3606
|
+
__publicField(this, "config");
|
|
3607
|
+
__publicField(this, "d");
|
|
3608
|
+
__publicField(this, "state", {
|
|
3609
|
+
permission: "undetermined",
|
|
3610
|
+
deviceId: null,
|
|
3611
|
+
token: null
|
|
3612
|
+
});
|
|
3613
|
+
__publicField(this, "listeners", /* @__PURE__ */ new Set());
|
|
3614
|
+
__publicField(this, "unsubscribeAuth", null);
|
|
3615
|
+
__publicField(this, "initialized", false);
|
|
3616
|
+
this.config = config;
|
|
3617
|
+
this.d = {
|
|
3618
|
+
native: deps.native ?? nativePush,
|
|
3619
|
+
storage: deps.storage ?? storage,
|
|
3620
|
+
registerDevice: deps.registerDevice,
|
|
3621
|
+
subscribeAuth: deps.subscribeAuth,
|
|
3622
|
+
getAndroidPushConfig: deps.getAndroidPushConfig,
|
|
3623
|
+
platformOS: deps.platformOS ?? import_react_native5.Platform.OS,
|
|
3624
|
+
generateDeviceId: deps.generateDeviceId ?? randomUuid
|
|
3625
|
+
};
|
|
3626
|
+
}
|
|
3627
|
+
/** Phase 1 — silent metadata registration; idempotent across calls. */
|
|
3628
|
+
async init() {
|
|
3629
|
+
if (this.initialized) return;
|
|
3630
|
+
this.initialized = true;
|
|
3631
|
+
const deviceId = await this.ensureDeviceId();
|
|
3632
|
+
const permission = await this.d.native.getPermissionStatus();
|
|
3633
|
+
this.setState({ deviceId, permission });
|
|
3634
|
+
const token = permission === "granted" ? await this.fetchToken() : null;
|
|
3635
|
+
await this.register(token);
|
|
3636
|
+
if (this.d.subscribeAuth && !this.unsubscribeAuth) {
|
|
3637
|
+
this.unsubscribeAuth = this.d.subscribeAuth(() => {
|
|
3638
|
+
void this.register(this.state.token).catch((err) => this.warn(err));
|
|
3639
|
+
});
|
|
3640
|
+
}
|
|
3641
|
+
}
|
|
3642
|
+
/** Phase 2 — prompt for permission, then collect + register the token. */
|
|
3643
|
+
async requestPermission() {
|
|
3644
|
+
const permission = await this.d.native.requestPermission();
|
|
3645
|
+
this.setState({ permission });
|
|
3646
|
+
if (permission === "granted") {
|
|
3647
|
+
const token = await this.fetchToken();
|
|
3648
|
+
await this.register(token);
|
|
3649
|
+
}
|
|
3650
|
+
return permission;
|
|
3651
|
+
}
|
|
3652
|
+
getDeviceState() {
|
|
3653
|
+
return this.state;
|
|
3654
|
+
}
|
|
3655
|
+
/** Observe device-state changes (for the `usePush` hook). Returns unsubscribe. */
|
|
3656
|
+
subscribe(listener) {
|
|
3657
|
+
this.listeners.add(listener);
|
|
3658
|
+
return () => this.listeners.delete(listener);
|
|
3659
|
+
}
|
|
3660
|
+
/** Detach the auth subscription. Call when tearing down the client. */
|
|
3661
|
+
dispose() {
|
|
3662
|
+
this.unsubscribeAuth?.();
|
|
3663
|
+
this.unsubscribeAuth = null;
|
|
3664
|
+
this.listeners.clear();
|
|
3665
|
+
}
|
|
3666
|
+
// --- internals ----------------------------------------------------------
|
|
3667
|
+
platform() {
|
|
3668
|
+
return this.d.platformOS === "ios" ? "ios" : "android";
|
|
3669
|
+
}
|
|
3670
|
+
provider() {
|
|
3671
|
+
return this.d.platformOS === "ios" ? "apns" : "fcm";
|
|
3672
|
+
}
|
|
3673
|
+
async ensureDeviceId() {
|
|
3674
|
+
const existing = await this.d.storage.getItem(STORAGE_KEY_DEVICE_ID);
|
|
3675
|
+
if (existing) return existing;
|
|
3676
|
+
const id = this.d.generateDeviceId();
|
|
3677
|
+
await this.d.storage.setItem(STORAGE_KEY_DEVICE_ID, id);
|
|
3678
|
+
return id;
|
|
3679
|
+
}
|
|
3680
|
+
async fetchToken() {
|
|
3681
|
+
const androidConfig = this.d.platformOS === "android" ? this.d.getAndroidPushConfig?.() ?? void 0 : void 0;
|
|
3682
|
+
const token = await this.d.native.getToken(androidConfig);
|
|
3683
|
+
if (token) this.setState({ token });
|
|
3684
|
+
return token;
|
|
3685
|
+
}
|
|
3686
|
+
async register(token) {
|
|
3687
|
+
const deviceId = this.state.deviceId ?? await this.ensureDeviceId();
|
|
3688
|
+
const info = await this.d.native.getDeviceInfo();
|
|
3689
|
+
const body = {
|
|
3690
|
+
deviceId,
|
|
3691
|
+
platform: this.platform(),
|
|
3692
|
+
provider: this.provider()
|
|
3693
|
+
};
|
|
3694
|
+
if (token != null) body.token = token;
|
|
3695
|
+
if (info.osVersion) body.osVersion = info.osVersion;
|
|
3696
|
+
if (info.model) body.model = info.model;
|
|
3697
|
+
if (info.brand) body.brand = info.brand;
|
|
3698
|
+
await this.d.registerDevice(body);
|
|
3699
|
+
this.setState({ deviceId, ...token != null ? { token } : {} });
|
|
3700
|
+
}
|
|
3701
|
+
setState(patch) {
|
|
3702
|
+
this.state = { ...this.state, ...patch };
|
|
3703
|
+
for (const listener of this.listeners) listener();
|
|
3704
|
+
}
|
|
3705
|
+
warn(err) {
|
|
3706
|
+
if (this.config.debug && typeof console !== "undefined") {
|
|
3707
|
+
console.warn("[QafkaCMS] device re-registration failed", err);
|
|
3708
|
+
}
|
|
3709
|
+
}
|
|
3710
|
+
};
|
|
3711
|
+
|
|
3712
|
+
// src/QafkaCmsSdk.ts
|
|
3713
|
+
var import_react_native6 = require("react-native");
|
|
3714
|
+
function devWarn(message, ...details) {
|
|
3715
|
+
if (typeof __DEV__ !== "undefined" && __DEV__) console.warn(message, ...details);
|
|
3716
|
+
}
|
|
3717
|
+
function rnAppStateProvider() {
|
|
3718
|
+
return {
|
|
3719
|
+
isActive: () => import_react_native6.AppState.currentState === "active",
|
|
3720
|
+
subscribe: (listener) => {
|
|
3721
|
+
const sub = import_react_native6.AppState.addEventListener(
|
|
3722
|
+
"change",
|
|
3723
|
+
(state) => listener(state === "active")
|
|
3724
|
+
);
|
|
3725
|
+
return () => sub.remove();
|
|
3726
|
+
}
|
|
3727
|
+
};
|
|
3728
|
+
}
|
|
3729
|
+
var QafkaCmsClient = class {
|
|
3730
|
+
constructor(config, deps = {}) {
|
|
3731
|
+
__publicField(this, "attestation");
|
|
3732
|
+
__publicField(this, "auth");
|
|
3733
|
+
__publicField(this, "content");
|
|
3734
|
+
/**
|
|
3735
|
+
* Device registration (E57): native push-token collection + the backend
|
|
3736
|
+
* `Device` row. Phase 1 (metadata) runs automatically on {@link initialize};
|
|
3737
|
+
* the host calls `deviceRegistration.requestPermission()` (or the `usePush`
|
|
3738
|
+
* hook) to prompt for notifications and collect the token. Dependency-free on
|
|
3739
|
+
* the host: iOS uses raw APNs, Android a SDK-bundled secondary FirebaseApp.
|
|
3740
|
+
*/
|
|
3741
|
+
__publicField(this, "deviceRegistration");
|
|
3742
|
+
/**
|
|
3743
|
+
* Active-language runtime (E55): holds the selected locale, the supported
|
|
3744
|
+
* locale set (`locales` domain) and UI strings (`i18n` domain), and resolves
|
|
3745
|
+
* `t(key)`. Fed by SDK-managed config-sync on {@link initialize}. The React
|
|
3746
|
+
* `useLocale`/`useTranslation` hooks subscribe to it.
|
|
3747
|
+
*/
|
|
3748
|
+
__publicField(this, "language");
|
|
3749
|
+
/**
|
|
3750
|
+
* Live content change signals (QFK2-E76): the hub behind `live` on
|
|
3751
|
+
* `useContent` / `useContentItem` — one multiplexed SSE stream (XHR) or
|
|
3752
|
+
* version polling per client. Nothing runs until something is watched.
|
|
3753
|
+
* `status()` → `'sse' | 'polling' | 'idle'` (debug).
|
|
3754
|
+
*/
|
|
3755
|
+
__publicField(this, "contentChanges");
|
|
3756
|
+
/**
|
|
3757
|
+
* Resolved `contentVersionGate` config (QFK2-E59): `{ maxAgeMs }`, or `null`
|
|
3758
|
+
* when off (the default). The provider gates expand-less content reads on it.
|
|
3759
|
+
*/
|
|
3760
|
+
__publicField(this, "contentVersionGate");
|
|
3761
|
+
/**
|
|
3762
|
+
* App version sent as `X-App-Version` (QFK2-E59): `config.appVersion`, else
|
|
3763
|
+
* the native app version; `null` when none / not a valid app version.
|
|
3764
|
+
*/
|
|
3765
|
+
__publicField(this, "appVersion");
|
|
3766
|
+
/**
|
|
3767
|
+
* Content bundle (QFK2-E59 T466): the offline snapshot of the collections
|
|
3768
|
+
* the project put in its bundle — `sync()`, `rows(collection)`,
|
|
3769
|
+
* `get(collection, id)`, `subscribe`. Present only with `contentBundle`.
|
|
3770
|
+
* Persisted only in `contentBundle.storage`, else {@link cacheStorage} when
|
|
3771
|
+
* `createClient({ cacheStorage })` is set (a plain AsyncStorage / MMKV store),
|
|
3772
|
+
* never in the secure {@link storage}; without either it lives in memory for
|
|
3773
|
+
* the app session. The Provider syncs it at boot, on foreground and on
|
|
3774
|
+
* locale change.
|
|
3775
|
+
*/
|
|
3776
|
+
__publicField(this, "bundle");
|
|
3777
|
+
/** Platform-neutral core (transport, auth, content, language, config-sync) — QFK2-E73. */
|
|
3778
|
+
__publicField(this, "core");
|
|
3779
|
+
__publicField(this, "proof");
|
|
3780
|
+
/**
|
|
3781
|
+
* Per-project public push client config (E57). Android only — the FCM sender
|
|
3782
|
+
* id / app id the SDK needs to mint a token from a secondary FirebaseApp. iOS
|
|
3783
|
+
* (raw APNs) needs nothing, so this is only started + read on Android.
|
|
3784
|
+
*/
|
|
3785
|
+
__publicField(this, "pushConfigSync");
|
|
3786
|
+
/**
|
|
3787
|
+
* The SDK's own native secure storage (iOS Keychain / Android
|
|
3788
|
+
* EncryptedSharedPreferences). Holds the session: refresh token, unlock
|
|
3789
|
+
* tokens, attestation key id, device id. Without `createClient({ cacheStorage })`
|
|
3790
|
+
* it also holds the cached data ({@link cacheStorage} is then this store):
|
|
3791
|
+
* keep persisted payloads small (reference data like categories) then.
|
|
3792
|
+
*/
|
|
3793
|
+
__publicField(this, "storage");
|
|
3794
|
+
/**
|
|
3795
|
+
* Where cached data lives (QFK2-T471): `persist: true` queries (the Provider
|
|
3796
|
+
* reads this), config-sync snapshots, the saved locale and, without its own
|
|
3797
|
+
* `contentBundle.storage`, the content bundle. With
|
|
3798
|
+
* `createClient({ cacheStorage })` it is that plain store, reading through to
|
|
3799
|
+
* the secure store once per key so copies an earlier SDK kept there move over;
|
|
3800
|
+
* otherwise it is {@link storage}.
|
|
3801
|
+
*/
|
|
3802
|
+
__publicField(this, "cacheStorage");
|
|
3803
|
+
__publicField(this, "warnedNoProof", false);
|
|
3804
|
+
const platformOS = deps.platformOS ?? import_react_native6.Platform.OS;
|
|
3805
|
+
const now2 = deps.now ?? Date.now;
|
|
3806
|
+
const doFetch = deps.fetch ?? ((url, init) => fetch(url, init));
|
|
3807
|
+
this.storage = deps.storage ?? storage;
|
|
3808
|
+
const plainCache = config.cacheStorage && config.cacheStorage !== this.storage ? config.cacheStorage : void 0;
|
|
3809
|
+
this.cacheStorage = plainCache ? createSecureMigrationStorage(plainCache, this.storage) : this.storage;
|
|
3810
|
+
let apiUrl = config.apiUrl;
|
|
3811
|
+
let apiKey = config.apiKey ?? null;
|
|
3812
|
+
if (typeof __DEV__ !== "undefined" && __DEV__) {
|
|
3813
|
+
const runtimeConfig = resolveRuntimeConfigSource(
|
|
3814
|
+
config.devConfig,
|
|
3815
|
+
loadRuntimeConfig()
|
|
3816
|
+
);
|
|
3817
|
+
const id = config.projectId;
|
|
3818
|
+
if (id && (config.apiKey || !runtimeConfig?.projects[id])) {
|
|
3819
|
+
if (!config.apiKey) {
|
|
3820
|
+
console.warn(
|
|
3821
|
+
`[QafkaCMS] projectId "${id}" is not in the dev config \u2014 simulator/emulator requests will be rejected without the project's TEST key. Pass it as apiKey from an env var under __DEV__ (apiKey: __DEV__ ? process.env.EXPO_PUBLIC_QAFKA_TEST_KEY : undefined), or pass devConfig.`
|
|
3822
|
+
);
|
|
3823
|
+
}
|
|
3824
|
+
apiUrl = apiUrl ?? runtimeConfig?.apiUrl;
|
|
3825
|
+
} else {
|
|
3826
|
+
const resolved = resolveProjectConfig(
|
|
3827
|
+
{ apiUrl: config.apiUrl, projectId: id },
|
|
3828
|
+
runtimeConfig
|
|
3829
|
+
);
|
|
3830
|
+
apiUrl = apiUrl ?? resolved.apiUrl;
|
|
3831
|
+
apiKey = apiKey ?? resolved.apiKey;
|
|
3832
|
+
}
|
|
3833
|
+
}
|
|
3834
|
+
validateCoreConfig(config);
|
|
3835
|
+
const projectId = typeof config.projectId === "string" && config.projectId !== "" ? config.projectId : void 0;
|
|
3836
|
+
if (!apiUrl) {
|
|
3837
|
+
throw new Error(
|
|
3838
|
+
"QafkaCMS: apiUrl is required. Pass it to createClient(), or run `qafka cms project` and wire devConfig: __DEV__ ? require('./.qafkacms/qafkacms-runtime') : undefined."
|
|
3839
|
+
);
|
|
3840
|
+
}
|
|
3841
|
+
const devApiKey = apiKey;
|
|
3842
|
+
const attestation = new AttestationManager(
|
|
3843
|
+
{
|
|
3844
|
+
apiUrl,
|
|
3845
|
+
projectSlug: config.projectSlug,
|
|
3846
|
+
publishableKey: config.publishableKey,
|
|
3847
|
+
projectId,
|
|
3848
|
+
apiKey
|
|
3849
|
+
},
|
|
3850
|
+
{
|
|
3851
|
+
native: deps.attestationNative ?? nativeAttestation,
|
|
3852
|
+
storage: this.storage,
|
|
3853
|
+
fetch: doFetch,
|
|
3854
|
+
platformOS,
|
|
3855
|
+
now: now2
|
|
3856
|
+
}
|
|
3857
|
+
);
|
|
3858
|
+
this.attestation = attestation;
|
|
3859
|
+
this.proof = new AttestationProof(
|
|
3860
|
+
{
|
|
3861
|
+
projectId,
|
|
3862
|
+
publishableKey: config.publishableKey,
|
|
3863
|
+
projectSlug: config.projectSlug
|
|
3864
|
+
},
|
|
3865
|
+
{
|
|
3866
|
+
getSessionToken: () => attestation.getSessionToken(),
|
|
3867
|
+
refresh: () => attestation.refresh(),
|
|
3868
|
+
getDevApiKey: () => attestation.isDevBypass() ? devApiKey : null,
|
|
3869
|
+
initialize: () => attestation.initialize()
|
|
3870
|
+
}
|
|
3871
|
+
);
|
|
3872
|
+
this.core = createCoreClient(
|
|
3873
|
+
{
|
|
3874
|
+
apiUrl,
|
|
3875
|
+
projectId,
|
|
3876
|
+
publishableKey: config.publishableKey,
|
|
3877
|
+
projectSlug: config.projectSlug,
|
|
3878
|
+
externalTokenProvider: config.externalTokenProvider,
|
|
3879
|
+
externalProvider: config.externalProvider,
|
|
3880
|
+
anonymousAuth: config.anonymousAuth,
|
|
3881
|
+
tier: "full",
|
|
3882
|
+
// Build-time embedded snapshots (E58): paint real config on a cold
|
|
3883
|
+
// start and seed the version so a matching server is not re-fetched.
|
|
3884
|
+
bootstrap: config.bootstrap,
|
|
3885
|
+
// One poll cadence knob drives the SDK-managed domains; ConfigSyncClient
|
|
3886
|
+
// clamps it to the safe floor.
|
|
3887
|
+
configPollIntervalMs: config.configPollIntervalMs,
|
|
3888
|
+
contentLiveDefault: config.contentLiveDefault,
|
|
3889
|
+
contentVersionGate: config.contentVersionGate,
|
|
3890
|
+
// QFK2-E59 V9 — the native version unless the app overrides it (`null` = none).
|
|
3891
|
+
appVersion: config.appVersion !== void 0 ? config.appVersion : getDeviceInfo().appVersion,
|
|
3892
|
+
contentBundle: config.contentBundle
|
|
3893
|
+
},
|
|
3894
|
+
{
|
|
3895
|
+
os: platformOS,
|
|
3896
|
+
fetch: doFetch,
|
|
3897
|
+
sessionStorage: this.storage,
|
|
3898
|
+
// Absent → the core keeps its cache in `sessionStorage` (unchanged behaviour).
|
|
3899
|
+
cacheStorage: plainCache ? this.cacheStorage : void 0,
|
|
3900
|
+
appState: deps.appState ?? rnAppStateProvider(),
|
|
3901
|
+
connectSse: deps.connectSse ?? connectSseViaXhr,
|
|
3902
|
+
proof: this.proof,
|
|
3903
|
+
now: now2,
|
|
3904
|
+
warn: devWarn
|
|
3905
|
+
},
|
|
3906
|
+
{
|
|
3907
|
+
// Only Android needs the FCM client config; iOS uses raw APNs.
|
|
3908
|
+
configStarts: () => platformOS === "android" ? [this.pushConfigSync.start()] : [],
|
|
3909
|
+
// QFK2-E76 — `live` content hooks (SSE over XHR, polling fallback).
|
|
3910
|
+
contentHub: createContentChangeHub,
|
|
3911
|
+
// QFK2-E59 T466 — injecting the module enables `client.bundle`.
|
|
3912
|
+
contentBundle: config.contentBundle ? createContentBundleClient : void 0
|
|
3913
|
+
}
|
|
3914
|
+
);
|
|
3915
|
+
this.auth = this.core.auth;
|
|
3916
|
+
this.content = this.core.content;
|
|
3917
|
+
this.language = this.core.language;
|
|
3918
|
+
this.contentChanges = this.core.contentChanges;
|
|
3919
|
+
this.contentVersionGate = this.core.contentVersionGate;
|
|
3920
|
+
this.appVersion = this.core.appVersion;
|
|
3921
|
+
if (this.core.bundle) {
|
|
3922
|
+
this.bundle = this.core.bundle;
|
|
3923
|
+
const own = typeof config.contentBundle === "object" ? config.contentBundle.storage : void 0;
|
|
3924
|
+
const bundleStore = own !== void 0 ? own : plainCache;
|
|
3925
|
+
if (bundleStore !== this.storage) this.dropSecureBundleCopies();
|
|
3926
|
+
}
|
|
3927
|
+
const http = this.core.http;
|
|
3928
|
+
this.deviceRegistration = new DeviceRegistrationManager(
|
|
3929
|
+
{},
|
|
3930
|
+
{
|
|
3931
|
+
native: deps.pushNative ?? nativePush,
|
|
3932
|
+
storage: this.storage,
|
|
3933
|
+
registerDevice: (body) => http.request("POST", "/devices", { body }),
|
|
3934
|
+
subscribeAuth: (listener) => this.auth.subscribe(listener),
|
|
3935
|
+
getAndroidPushConfig: () => this.pushConfigSync.current().android ?? null,
|
|
3936
|
+
platformOS
|
|
3937
|
+
}
|
|
3938
|
+
);
|
|
3939
|
+
this.pushConfigSync = this.createConfigSync("push", {}, { pollIntervalMs: config.configPollIntervalMs });
|
|
3940
|
+
}
|
|
3941
|
+
/**
|
|
3942
|
+
* Bundle files never belong in the secure store (up to 20 MB each). Pre-release
|
|
3943
|
+
* builds wrote them there: remove such leftovers (one read when none exist).
|
|
3944
|
+
*/
|
|
3945
|
+
dropSecureBundleCopies() {
|
|
3946
|
+
const secure = this.storage;
|
|
3947
|
+
void (async () => {
|
|
3948
|
+
const raw = await secure.getItem(STORAGE_KEY_BUNDLE_INDEX);
|
|
3949
|
+
if (raw === null) return;
|
|
3950
|
+
let locales = [];
|
|
3951
|
+
try {
|
|
3952
|
+
locales = Object.keys(JSON.parse(raw)?.files ?? {});
|
|
3953
|
+
} catch {
|
|
3954
|
+
}
|
|
3955
|
+
await secure.multiRemove([
|
|
3956
|
+
...locales.map((l) => `${STORAGE_KEY_BUNDLE_PREFIX}${l}`),
|
|
3957
|
+
STORAGE_KEY_BUNDLE_INDEX
|
|
3958
|
+
]);
|
|
3959
|
+
})().catch(() => void 0);
|
|
3960
|
+
}
|
|
3961
|
+
/**
|
|
3962
|
+
* Hydrate the persisted session, run device attestation, then start the
|
|
3963
|
+
* language runtime (restore the saved locale + start the locales/i18n
|
|
3964
|
+
* config-sync). Call once at boot.
|
|
3965
|
+
*/
|
|
3966
|
+
async initialize() {
|
|
3967
|
+
await this.core.initialize();
|
|
3968
|
+
void this.deviceRegistration.init().catch((err) => {
|
|
3969
|
+
devWarn("[QafkaCMS] device registration (phase 1) failed", err);
|
|
3970
|
+
});
|
|
3971
|
+
}
|
|
3972
|
+
/**
|
|
3973
|
+
* Project + proof headers for calling the QafkaCMS API with your own HTTP
|
|
3974
|
+
* client: `X-Project-Id` and/or `X-Project-Key`, `X-Project-Slug` (if set), and
|
|
3975
|
+
* `X-Session-Token` (release) or `x-api-key` (dev-bypass), plus
|
|
3976
|
+
* `X-Unlock-Token` when `content.lookup` has unlocked records (QFK2-E78; pass
|
|
3977
|
+
* `{ withUnlockTokens: false }` to leave it out), and `X-App-Version` when
|
|
3978
|
+
* {@link appVersion} is set (QFK2-E59). Initialises device
|
|
3979
|
+
* attestation and loads the persisted unlock tokens first if that has not
|
|
3980
|
+
* happened yet. Contains no `Authorization` or `Content-Type` — add the
|
|
3981
|
+
* end-user token and body headers yourself.
|
|
3982
|
+
*/
|
|
3983
|
+
async getRequestHeaders(options = {}) {
|
|
3984
|
+
const headers = await this.core.getRequestHeaders(options);
|
|
3985
|
+
if (this.attestation.isDevBypass() && !headers["x-api-key"] && !this.warnedNoProof && typeof __DEV__ !== "undefined" && __DEV__) {
|
|
3986
|
+
this.warnedNoProof = true;
|
|
3987
|
+
console.warn(
|
|
3988
|
+
"[QafkaCMS] getRequestHeaders(): dev-bypass without a dev API key \u2014 the request carries no proof."
|
|
3989
|
+
);
|
|
3990
|
+
}
|
|
3991
|
+
return headers;
|
|
3992
|
+
}
|
|
3993
|
+
/**
|
|
3994
|
+
* Force a fresh attestation session, then return {@link getRequestHeaders}.
|
|
3995
|
+
* On the first-ever call the initial attestation already is fresh, so it
|
|
3996
|
+
* attests once; later calls replace the existing session.
|
|
3997
|
+
*/
|
|
3998
|
+
async refreshRequestHeaders(options = {}) {
|
|
3999
|
+
const attestedBefore = this.proof.hasStarted();
|
|
4000
|
+
await this.proof.initialize();
|
|
4001
|
+
if (attestedBefore) await this.attestation.forceRefresh();
|
|
4002
|
+
return this.getRequestHeaders(options);
|
|
4003
|
+
}
|
|
4004
|
+
/**
|
|
4005
|
+
* Build a config-sync client for one customization domain (translations,
|
|
4006
|
+
* theme, navigation, …). Each shares the SDK's transport and storage.
|
|
4007
|
+
*
|
|
4008
|
+
* Transport defaults to **polling** — config rarely changes and a persistent
|
|
4009
|
+
* SSE per domain does not scale (one held connection per app per domain). Pass
|
|
4010
|
+
* `live: true` only for a domain that genuinely needs sub-second push (e.g. a
|
|
4011
|
+
* kill-switch flag); everything else polls (see E56).
|
|
4012
|
+
*/
|
|
4013
|
+
createConfigSync(domain, buildTimeDefault, options) {
|
|
4014
|
+
return this.core.createConfigSync(domain, buildTimeDefault, options);
|
|
4015
|
+
}
|
|
4016
|
+
};
|
|
4017
|
+
function createClient(config, deps) {
|
|
4018
|
+
return new QafkaCmsClient(config, deps);
|
|
4019
|
+
}
|
|
4020
|
+
|
|
4021
|
+
// ../react/src/QafkaCmsProvider.ts
|
|
4022
|
+
var import_react2 = require("react");
|
|
4023
|
+
|
|
4024
|
+
// ../react/src/context.ts
|
|
4025
|
+
var import_react = require("react");
|
|
4026
|
+
var QafkaCmsContext = (0, import_react.createContext)(null);
|
|
4027
|
+
function useQafkaCmsContext() {
|
|
4028
|
+
const value = (0, import_react.useContext)(QafkaCmsContext);
|
|
4029
|
+
if (!value) {
|
|
4030
|
+
throw new Error("QafkaCMS: hooks must be used within a <QafkaCmsProvider>.");
|
|
4031
|
+
}
|
|
4032
|
+
return value;
|
|
4033
|
+
}
|
|
4034
|
+
function useQafkaCmsClient() {
|
|
4035
|
+
return useQafkaCmsContext().client;
|
|
4036
|
+
}
|
|
4037
|
+
function useQafkaCms() {
|
|
4038
|
+
const { status, error, retry, clearCache } = useQafkaCmsContext();
|
|
4039
|
+
return { status, error, retry, clearCache };
|
|
4040
|
+
}
|
|
4041
|
+
function useQafkaCmsCache() {
|
|
4042
|
+
return useQafkaCmsContext().cache;
|
|
4043
|
+
}
|
|
4044
|
+
|
|
4045
|
+
// ../react/src/bootstrap.ts
|
|
4046
|
+
async function runBootstrap(client, cache, prefetch) {
|
|
4047
|
+
await client.initialize();
|
|
4048
|
+
const start = (r) => cache.prefetch(r.key, () => r.fetch(client), { ttl: r.ttl, persist: r.persist });
|
|
4049
|
+
const gating = [];
|
|
4050
|
+
for (const resource of prefetch) {
|
|
4051
|
+
if (resource.gate) gating.push(resource);
|
|
4052
|
+
else void start(resource);
|
|
4053
|
+
}
|
|
4054
|
+
await Promise.all(gating.map(start));
|
|
4055
|
+
}
|
|
4056
|
+
|
|
4057
|
+
// ../react/src/auth-cache-reset.ts
|
|
4058
|
+
function attachAuthCacheReset(client, cache) {
|
|
4059
|
+
const identityOf = () => {
|
|
4060
|
+
const state = client.auth.getAuthState();
|
|
4061
|
+
if (!state.isAuthenticated) return null;
|
|
4062
|
+
return `${state.userId ?? "__authenticated__"}:${state.isAnonymous === true}`;
|
|
4063
|
+
};
|
|
4064
|
+
let last = identityOf();
|
|
4065
|
+
return client.auth.subscribe(() => {
|
|
4066
|
+
const next = identityOf();
|
|
4067
|
+
if (next === last) return;
|
|
4068
|
+
last = next;
|
|
4069
|
+
client.contentChanges?.reset();
|
|
4070
|
+
if (next === null) {
|
|
4071
|
+
void cache.clear();
|
|
4072
|
+
} else {
|
|
4073
|
+
void cache.clear().then(() => cache.refetchActive());
|
|
4074
|
+
}
|
|
4075
|
+
});
|
|
4076
|
+
}
|
|
4077
|
+
|
|
4078
|
+
// ../react/src/unlock-cache-reset.ts
|
|
4079
|
+
function attachUnlockCacheReset(client, cache) {
|
|
4080
|
+
return client.content.onUnlockChange(() => {
|
|
4081
|
+
cache.invalidateWhere(() => true);
|
|
4082
|
+
});
|
|
4083
|
+
}
|
|
4084
|
+
|
|
4085
|
+
// ../react/src/locale-cache-reset.ts
|
|
4086
|
+
function attachLocaleCacheReset(client, cache) {
|
|
4087
|
+
const language = client.language;
|
|
4088
|
+
if (!language) return () => {
|
|
4089
|
+
};
|
|
4090
|
+
let last = language.getLanguage();
|
|
4091
|
+
return language.subscribe(() => {
|
|
4092
|
+
const next = language.getLanguage();
|
|
4093
|
+
if (next === last) return;
|
|
4094
|
+
last = next;
|
|
4095
|
+
cache.invalidateByPrefix(["content"]);
|
|
4096
|
+
cache.invalidateByPrefix(["content-item"]);
|
|
4097
|
+
});
|
|
4098
|
+
}
|
|
4099
|
+
|
|
4100
|
+
// ../react/src/QafkaCmsProvider.ts
|
|
4101
|
+
function QafkaCmsProvider(props) {
|
|
4102
|
+
const { client, prefetch, defaultTtl, onCacheError, fallback, errorFallback, children } = props;
|
|
4103
|
+
const cache = (0, import_react2.useMemo)(
|
|
4104
|
+
() => {
|
|
4105
|
+
const gate = client.contentVersionGate;
|
|
4106
|
+
const changes = client.contentChanges;
|
|
4107
|
+
const options = { storage: client.cacheStorage ?? client.storage, defaultTtl, onError: onCacheError };
|
|
4108
|
+
if (client.appVersion) options.appVersion = client.appVersion;
|
|
4109
|
+
if (gate && changes && typeof changes.versions === "function") {
|
|
4110
|
+
options.versionGate = { check: (cols) => changes.versions(cols), maxAgeMs: gate.maxAgeMs };
|
|
4111
|
+
}
|
|
4112
|
+
return new QueryCache(options);
|
|
4113
|
+
},
|
|
4114
|
+
// A new cache is intentionally tied to the client identity; a swapped client
|
|
4115
|
+
// means a different session and a fresh cache.
|
|
4116
|
+
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
4117
|
+
[client]
|
|
4118
|
+
);
|
|
4119
|
+
const [status, setStatus] = (0, import_react2.useState)("initializing");
|
|
4120
|
+
const [error, setError] = (0, import_react2.useState)(null);
|
|
4121
|
+
const [bootId, setBootId] = (0, import_react2.useState)(0);
|
|
4122
|
+
const prefetchRef = (0, import_react2.useRef)(prefetch);
|
|
4123
|
+
prefetchRef.current = prefetch;
|
|
4124
|
+
(0, import_react2.useEffect)(() => {
|
|
4125
|
+
let cancelled = false;
|
|
4126
|
+
let detachAuthReset = null;
|
|
4127
|
+
let detachLocaleReset = null;
|
|
4128
|
+
let detachUnlockReset = null;
|
|
4129
|
+
let stopBundle;
|
|
4130
|
+
setStatus("initializing");
|
|
4131
|
+
setError(null);
|
|
4132
|
+
runBootstrap(client, cache, prefetchRef.current ?? []).then(() => {
|
|
4133
|
+
if (cancelled) return;
|
|
4134
|
+
detachAuthReset = attachAuthCacheReset(client, cache);
|
|
4135
|
+
detachLocaleReset = attachLocaleCacheReset(client, cache);
|
|
4136
|
+
detachUnlockReset = attachUnlockCacheReset(client, cache);
|
|
4137
|
+
client.contentChanges?.reset();
|
|
4138
|
+
stopBundle = client.bundle?.start();
|
|
4139
|
+
setStatus("ready");
|
|
4140
|
+
}).catch((err) => {
|
|
4141
|
+
if (cancelled) return;
|
|
4142
|
+
setError(err instanceof Error ? err : new Error(String(err)));
|
|
4143
|
+
setStatus("error");
|
|
4144
|
+
});
|
|
4145
|
+
return () => {
|
|
4146
|
+
cancelled = true;
|
|
4147
|
+
detachAuthReset?.();
|
|
4148
|
+
detachLocaleReset?.();
|
|
4149
|
+
detachUnlockReset?.();
|
|
4150
|
+
stopBundle?.();
|
|
4151
|
+
};
|
|
4152
|
+
}, [client, cache, bootId]);
|
|
4153
|
+
const retry = (0, import_react2.useCallback)(() => setBootId((n) => n + 1), []);
|
|
4154
|
+
const clearCache = (0, import_react2.useCallback)(() => {
|
|
4155
|
+
void cache.clear();
|
|
4156
|
+
}, [cache]);
|
|
4157
|
+
const value = (0, import_react2.useMemo)(
|
|
4158
|
+
() => ({ client, cache, status, error, retry, clearCache }),
|
|
4159
|
+
[client, cache, status, error, retry, clearCache]
|
|
4160
|
+
);
|
|
4161
|
+
let content = children;
|
|
4162
|
+
if (status === "error" && errorFallback !== void 0) {
|
|
4163
|
+
content = typeof errorFallback === "function" ? errorFallback(error ?? new Error("QafkaCMS initialization failed"), retry) : errorFallback;
|
|
4164
|
+
} else if (status === "initializing" && fallback !== void 0) {
|
|
4165
|
+
content = fallback;
|
|
4166
|
+
}
|
|
4167
|
+
return (0, import_react2.createElement)(QafkaCmsContext.Provider, { value }, content);
|
|
4168
|
+
}
|
|
4169
|
+
|
|
4170
|
+
// ../react/src/require-language.ts
|
|
4171
|
+
function requireLanguage(client, hook) {
|
|
4172
|
+
if (!client.language) {
|
|
4173
|
+
throw new Error(
|
|
4174
|
+
`QafkaCMS: ${hook}() needs the full tier \u2014 this client has no language runtime (client.language).`
|
|
4175
|
+
);
|
|
4176
|
+
}
|
|
4177
|
+
return client.language;
|
|
4178
|
+
}
|
|
4179
|
+
|
|
4180
|
+
// ../react/src/useQuery.ts
|
|
4181
|
+
var import_react3 = require("react");
|
|
4182
|
+
function useQuery(key, fetcher, options) {
|
|
4183
|
+
const { cache, client } = useQafkaCmsContext();
|
|
4184
|
+
const sk = serializeKey(key);
|
|
4185
|
+
const enabled = options?.enabled ?? true;
|
|
4186
|
+
const ttl = options?.ttl;
|
|
4187
|
+
const persist = options?.persist;
|
|
4188
|
+
const gate = options?.gate;
|
|
4189
|
+
const fetcherRef = (0, import_react3.useRef)(fetcher);
|
|
4190
|
+
fetcherRef.current = fetcher;
|
|
4191
|
+
const subscribe = (0, import_react3.useCallback)((cb) => cache.subscribe(sk, cb), [cache, sk]);
|
|
4192
|
+
const getSnapshot = (0, import_react3.useCallback)(() => cache.getSnapshot(sk), [cache, sk]);
|
|
4193
|
+
const state = (0, import_react3.useSyncExternalStore)(subscribe, getSnapshot, getSnapshot);
|
|
4194
|
+
(0, import_react3.useEffect)(() => {
|
|
4195
|
+
if (!enabled) return;
|
|
4196
|
+
void cache.ensure(sk, (ctx) => fetcherRef.current(client, ctx), { ttl, persist, gate });
|
|
4197
|
+
}, [cache, client, sk, enabled, ttl, persist, gate]);
|
|
4198
|
+
const refetch = (0, import_react3.useCallback)(
|
|
4199
|
+
() => cache.refetch(sk, (ctx) => fetcherRef.current(client, ctx)),
|
|
4200
|
+
[cache, client, sk]
|
|
4201
|
+
);
|
|
4202
|
+
return { ...state, refetch };
|
|
4203
|
+
}
|
|
4204
|
+
|
|
4205
|
+
// ../react/src/useMutation.ts
|
|
4206
|
+
var import_react4 = require("react");
|
|
4207
|
+
function useMutation(mutationFn, options) {
|
|
4208
|
+
const { client, cache } = useQafkaCmsContext();
|
|
4209
|
+
const [isPending, setIsPending] = (0, import_react4.useState)(false);
|
|
4210
|
+
const [error, setError] = (0, import_react4.useState)(void 0);
|
|
4211
|
+
const [data, setData] = (0, import_react4.useState)(void 0);
|
|
4212
|
+
const fnRef = (0, import_react4.useRef)(mutationFn);
|
|
4213
|
+
fnRef.current = mutationFn;
|
|
4214
|
+
const optionsRef = (0, import_react4.useRef)(options);
|
|
4215
|
+
optionsRef.current = options;
|
|
4216
|
+
const mountedRef = (0, import_react4.useRef)(true);
|
|
4217
|
+
(0, import_react4.useEffect)(() => {
|
|
4218
|
+
mountedRef.current = true;
|
|
4219
|
+
return () => {
|
|
4220
|
+
mountedRef.current = false;
|
|
4221
|
+
};
|
|
4222
|
+
}, []);
|
|
4223
|
+
const mutate = (0, import_react4.useCallback)(
|
|
4224
|
+
async (vars) => {
|
|
4225
|
+
if (mountedRef.current) {
|
|
4226
|
+
setIsPending(true);
|
|
4227
|
+
setError(void 0);
|
|
4228
|
+
}
|
|
4229
|
+
try {
|
|
4230
|
+
const result = await fnRef.current(client, vars);
|
|
4231
|
+
const opts = optionsRef.current;
|
|
4232
|
+
const keys = typeof opts?.invalidate === "function" ? opts.invalidate(result, vars) : opts?.invalidate;
|
|
4233
|
+
if (keys) for (const key of keys) cache.invalidateByPrefix(key);
|
|
4234
|
+
if (mountedRef.current) {
|
|
4235
|
+
setData(result);
|
|
4236
|
+
setIsPending(false);
|
|
4237
|
+
}
|
|
4238
|
+
opts?.onSuccess?.(result, vars);
|
|
4239
|
+
return result;
|
|
4240
|
+
} catch (err) {
|
|
4241
|
+
const e = err instanceof Error ? err : new Error(String(err));
|
|
4242
|
+
if (mountedRef.current) {
|
|
4243
|
+
setError(e);
|
|
4244
|
+
setIsPending(false);
|
|
4245
|
+
}
|
|
4246
|
+
optionsRef.current?.onError?.(e, vars);
|
|
4247
|
+
throw e;
|
|
4248
|
+
}
|
|
4249
|
+
},
|
|
4250
|
+
[client, cache]
|
|
4251
|
+
);
|
|
4252
|
+
const reset = (0, import_react4.useCallback)(() => {
|
|
4253
|
+
if (!mountedRef.current) return;
|
|
4254
|
+
setIsPending(false);
|
|
4255
|
+
setError(void 0);
|
|
4256
|
+
setData(void 0);
|
|
4257
|
+
}, []);
|
|
4258
|
+
return { mutate, isPending, error, data, reset };
|
|
4259
|
+
}
|
|
4260
|
+
|
|
4261
|
+
// ../react/src/useContent.ts
|
|
4262
|
+
var import_react5 = require("react");
|
|
4263
|
+
function useGate(collection, params) {
|
|
4264
|
+
const { client } = useQafkaCmsContext();
|
|
4265
|
+
if (!client.contentVersionGate) return void 0;
|
|
4266
|
+
const expand = params?.expand;
|
|
4267
|
+
return expand === void 0 || expand.length === 0 ? collection : void 0;
|
|
4268
|
+
}
|
|
4269
|
+
function useLive(collection, id, live, on) {
|
|
4270
|
+
const { client, cache } = useQafkaCmsContext();
|
|
4271
|
+
const cfg = live === true ? {} : live || null;
|
|
4272
|
+
const key = cfg && on ? JSON.stringify([collection, id ?? null, cfg.mode, cfg.also, cfg.pollIntervalMs]) : null;
|
|
4273
|
+
(0, import_react5.useEffect)(() => {
|
|
4274
|
+
const hub = client.contentChanges;
|
|
4275
|
+
if (!key || !hub) return;
|
|
4276
|
+
const [c, i, mode, also, pollIntervalMs] = JSON.parse(key);
|
|
4277
|
+
return hub.watch({ collection: c, id: i ?? void 0, also: also ?? void 0 }, mode ?? void 0, {
|
|
4278
|
+
cache,
|
|
4279
|
+
pollIntervalMs: pollIntervalMs ?? void 0
|
|
4280
|
+
});
|
|
4281
|
+
}, [client, cache, key]);
|
|
4282
|
+
}
|
|
4283
|
+
function useContent(collection, params, options) {
|
|
4284
|
+
const { live, ...queryOptions } = options ?? {};
|
|
4285
|
+
useLive(collection, void 0, live, queryOptions.enabled ?? true);
|
|
4286
|
+
const gate = useGate(collection, params);
|
|
4287
|
+
return useQuery(
|
|
4288
|
+
["content", collection, params ?? {}],
|
|
4289
|
+
(client, ctx) => {
|
|
4290
|
+
const content = client.content;
|
|
4291
|
+
if (typeof content.listConditional !== "function") return content.list(collection, params);
|
|
4292
|
+
return content.listConditional(collection, params, { ifNoneMatch: ctx.etag }).then(conditional.from);
|
|
4293
|
+
},
|
|
4294
|
+
{ ...queryOptions, gate }
|
|
4295
|
+
);
|
|
4296
|
+
}
|
|
4297
|
+
function useContentItem(collection, id, params, options) {
|
|
4298
|
+
const { live, ...queryOptions } = options ?? {};
|
|
4299
|
+
const enabled = (queryOptions.enabled ?? true) && Boolean(id);
|
|
4300
|
+
useLive(collection, id, live, enabled);
|
|
4301
|
+
const gate = useGate(collection, params);
|
|
4302
|
+
return useQuery(
|
|
4303
|
+
["content-item", collection, id ?? null, params ?? {}],
|
|
4304
|
+
(client, ctx) => {
|
|
4305
|
+
const content = client.content;
|
|
4306
|
+
if (typeof content.getConditional !== "function") return content.get(collection, id, params);
|
|
4307
|
+
return content.getConditional(collection, id, params, { ifNoneMatch: ctx.etag }).then(conditional.from);
|
|
4308
|
+
},
|
|
4309
|
+
{ ...queryOptions, enabled, gate }
|
|
4310
|
+
);
|
|
4311
|
+
}
|
|
4312
|
+
|
|
4313
|
+
// ../react/src/useBundle.ts
|
|
4314
|
+
var import_react6 = require("react");
|
|
4315
|
+
var none = () => () => {
|
|
4316
|
+
};
|
|
4317
|
+
var off = {
|
|
4318
|
+
rows: [],
|
|
4319
|
+
data: null,
|
|
4320
|
+
version: null,
|
|
4321
|
+
isLoading: false,
|
|
4322
|
+
error: new Error("QafkaCMS: contentBundle is not enabled on this client")
|
|
4323
|
+
};
|
|
4324
|
+
function useView(make) {
|
|
4325
|
+
const b = useQafkaCmsContext().client.bundle;
|
|
4326
|
+
const get = () => b ? make(b) : off;
|
|
4327
|
+
return (0, import_react6.useSyncExternalStore)(b ? b.subscribe : none, get, get);
|
|
4328
|
+
}
|
|
4329
|
+
function useBundle(collection) {
|
|
4330
|
+
return useView((b) => b.view(collection));
|
|
4331
|
+
}
|
|
4332
|
+
function useBundleItem(collection, id) {
|
|
4333
|
+
return useView((b) => b.itemView(collection, id));
|
|
4334
|
+
}
|
|
4335
|
+
|
|
4336
|
+
// ../react/src/useLookup.ts
|
|
4337
|
+
function useLookup() {
|
|
4338
|
+
return useMutation(
|
|
4339
|
+
(client, { collection, code, ...params }) => client.content.lookup(collection, code, params)
|
|
4340
|
+
);
|
|
4341
|
+
}
|
|
4342
|
+
|
|
4343
|
+
// ../react/src/useAuth.ts
|
|
4344
|
+
var import_react7 = require("react");
|
|
4345
|
+
function useAuth() {
|
|
4346
|
+
const { client } = useQafkaCmsContext();
|
|
4347
|
+
const subscribe = (0, import_react7.useCallback)((cb) => client.auth.subscribe(cb), [client]);
|
|
4348
|
+
const getSnapshot = (0, import_react7.useCallback)(() => client.auth.getAuthState(), [client]);
|
|
4349
|
+
return (0, import_react7.useSyncExternalStore)(subscribe, getSnapshot, getSnapshot);
|
|
4350
|
+
}
|
|
4351
|
+
|
|
4352
|
+
// ../react/src/useLocale.ts
|
|
4353
|
+
var import_react8 = require("react");
|
|
4354
|
+
function useLocale() {
|
|
4355
|
+
const language = requireLanguage(useQafkaCmsClient(), "useLocale");
|
|
4356
|
+
const subscribe = (0, import_react8.useCallback)((cb) => language.subscribe(cb), [language]);
|
|
4357
|
+
(0, import_react8.useSyncExternalStore)(
|
|
4358
|
+
subscribe,
|
|
4359
|
+
() => language.getRevision(),
|
|
4360
|
+
() => language.getRevision()
|
|
4361
|
+
);
|
|
4362
|
+
const setLocale = (0, import_react8.useCallback)((locale) => language.setLanguage(locale), [language]);
|
|
4363
|
+
return {
|
|
4364
|
+
locale: language.getLanguage(),
|
|
4365
|
+
setLocale,
|
|
4366
|
+
availableLocales: language.getAvailableLocales(),
|
|
4367
|
+
defaultLocale: language.getDefaultLocale()
|
|
4368
|
+
};
|
|
4369
|
+
}
|
|
4370
|
+
|
|
4371
|
+
// ../react/src/useTranslation.ts
|
|
4372
|
+
var import_react9 = require("react");
|
|
4373
|
+
function useTranslation() {
|
|
4374
|
+
const language = requireLanguage(useQafkaCmsClient(), "useTranslation");
|
|
4375
|
+
const subscribe = (0, import_react9.useCallback)((cb) => language.subscribe(cb), [language]);
|
|
4376
|
+
const revision = (0, import_react9.useSyncExternalStore)(
|
|
4377
|
+
subscribe,
|
|
4378
|
+
() => language.getRevision(),
|
|
4379
|
+
() => language.getRevision()
|
|
4380
|
+
);
|
|
4381
|
+
const t = (0, import_react9.useCallback)(
|
|
4382
|
+
(key, params) => language.t(key, params),
|
|
4383
|
+
// `revision` keeps `t`'s identity fresh after each change so memoized
|
|
4384
|
+
// children re-render with the new strings.
|
|
4385
|
+
[language, revision]
|
|
4386
|
+
);
|
|
4387
|
+
const setLocale = (0, import_react9.useCallback)((locale) => language.setLanguage(locale), [language]);
|
|
4388
|
+
return { t, locale: language.getLanguage(), setLocale };
|
|
4389
|
+
}
|
|
4390
|
+
|
|
4391
|
+
// src/rn-react.ts
|
|
4392
|
+
var QafkaCmsProvider2 = QafkaCmsProvider;
|
|
4393
|
+
var useQafkaCmsClient2 = useQafkaCmsClient;
|
|
4394
|
+
var useQafkaCms2 = useQafkaCms;
|
|
4395
|
+
var useQuery2 = useQuery;
|
|
4396
|
+
var useMutation2 = useMutation;
|
|
4397
|
+
|
|
4398
|
+
// src/react/usePush.ts
|
|
4399
|
+
var import_react10 = require("react");
|
|
4400
|
+
function usePush() {
|
|
4401
|
+
const { client } = useQafkaCmsContext();
|
|
4402
|
+
const subscribe = (0, import_react10.useCallback)(
|
|
4403
|
+
(cb) => client.deviceRegistration.subscribe(cb),
|
|
4404
|
+
[client]
|
|
4405
|
+
);
|
|
4406
|
+
const getSnapshot = (0, import_react10.useCallback)(
|
|
4407
|
+
() => client.deviceRegistration.getDeviceState(),
|
|
4408
|
+
[client]
|
|
4409
|
+
);
|
|
4410
|
+
const state = (0, import_react10.useSyncExternalStore)(subscribe, getSnapshot, getSnapshot);
|
|
4411
|
+
const requestPermission = (0, import_react10.useCallback)(
|
|
4412
|
+
() => client.deviceRegistration.requestPermission(),
|
|
4413
|
+
[client]
|
|
4414
|
+
);
|
|
4415
|
+
return { ...state, requestPermission };
|
|
4416
|
+
}
|
|
4417
|
+
|
|
4418
|
+
// src/react/useResolvedColor.ts
|
|
4419
|
+
var import_react_native7 = require("react-native");
|
|
4420
|
+
function useResolvedColor(value) {
|
|
4421
|
+
const scheme = (0, import_react_native7.useColorScheme)();
|
|
4422
|
+
return resolveColor(value, scheme === "dark" ? "dark" : "light");
|
|
4423
|
+
}
|
|
4424
|
+
|
|
4425
|
+
// src/index.ts
|
|
4426
|
+
function getVersion() {
|
|
4427
|
+
return SDK_VERSION;
|
|
4428
|
+
}
|
|
4429
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
4430
|
+
0 && (module.exports = {
|
|
4431
|
+
AttestationManager,
|
|
4432
|
+
AuthClient,
|
|
4433
|
+
CURRENT_USER,
|
|
4434
|
+
ConfigSyncClient,
|
|
4435
|
+
ContentClient,
|
|
4436
|
+
DeviceRegistrationManager,
|
|
4437
|
+
LanguageManager,
|
|
4438
|
+
NOW,
|
|
4439
|
+
ProblemError,
|
|
4440
|
+
QafkaCmsClient,
|
|
4441
|
+
QafkaCmsProvider,
|
|
4442
|
+
QueryCache,
|
|
4443
|
+
SDK_VERSION,
|
|
4444
|
+
UnlockTokenStore,
|
|
4445
|
+
createClient,
|
|
4446
|
+
createMemoryCacheStorage,
|
|
4447
|
+
getVersion,
|
|
4448
|
+
now,
|
|
4449
|
+
parseDuration,
|
|
4450
|
+
resolveColor,
|
|
4451
|
+
serializeKey,
|
|
4452
|
+
useAuth,
|
|
4453
|
+
useBundle,
|
|
4454
|
+
useBundleItem,
|
|
4455
|
+
useContent,
|
|
4456
|
+
useContentItem,
|
|
4457
|
+
useLocale,
|
|
4458
|
+
useLookup,
|
|
4459
|
+
useMutation,
|
|
4460
|
+
usePush,
|
|
4461
|
+
useQafkaCms,
|
|
4462
|
+
useQafkaCmsCache,
|
|
4463
|
+
useQafkaCmsClient,
|
|
4464
|
+
useQuery,
|
|
4465
|
+
useResolvedColor,
|
|
4466
|
+
useTranslation
|
|
4467
|
+
});
|
|
4468
|
+
//# sourceMappingURL=index.js.map
|