@gemmein/sdk 0.0.1 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,611 @@
1
+ export class GemmeinError extends Error {
2
+ constructor(input) {
3
+ super(input.message);
4
+ this.name = "GemmeinError";
5
+ this.status = input.status;
6
+ this.code = input.code;
7
+ this.resetAt = input.resetAt;
8
+ }
9
+ }
10
+ export class MemoryTokenStore {
11
+ get() {
12
+ return this.token;
13
+ }
14
+ set(token) {
15
+ this.token = token;
16
+ }
17
+ clear() {
18
+ this.token = undefined;
19
+ }
20
+ }
21
+ // Persists the session across page reloads — the default in browsers.
22
+ // Sessions are long-lived server-side; a memory-only default would log
23
+ // users out on every refresh. Keyed per app key so two Gemmein apps on
24
+ // one origin never share a token. All storage access is guarded: private
25
+ // modes and blocked storage degrade to "signed out", never to a crash.
26
+ export class BrowserTokenStore {
27
+ constructor(appKey) {
28
+ this.key = `gemmein_session_${appKey.slice(0, 20)}`;
29
+ }
30
+ get() {
31
+ try {
32
+ return window.localStorage.getItem(this.key) ?? undefined;
33
+ }
34
+ catch {
35
+ return undefined;
36
+ }
37
+ }
38
+ set(token) {
39
+ try {
40
+ window.localStorage.setItem(this.key, token);
41
+ }
42
+ catch { /* storage blocked — session lives for this page only */ }
43
+ }
44
+ clear() {
45
+ try {
46
+ window.localStorage.removeItem(this.key);
47
+ }
48
+ catch { /* nothing to clear */ }
49
+ }
50
+ }
51
+ function defaultTokenStore(appKey) {
52
+ try {
53
+ if (typeof window !== "undefined" && window.localStorage)
54
+ return new BrowserTokenStore(appKey);
55
+ }
56
+ catch { /* SSR / Node / storage blocked */ }
57
+ return new MemoryTokenStore();
58
+ }
59
+ /**
60
+ * The client — two layers:
61
+ *
62
+ * - `g.collection("notes")` — YOUR app's collections. Records, files,
63
+ * safety rules. This is where your app's own data model lives.
64
+ * - Business primitives Gemmein runs for you: `g.auth` (sign-in),
65
+ * `g.subscriptions` (who's on which plan), `g.payments` (one-off
66
+ * purchases), `g.account` (the user's own account). These are
67
+ * SELF-SERVICE surfaces for the signed-in user — reads and Stripe
68
+ * hand-offs, never admin powers. Managing other people's users,
69
+ * subscriptions, or records happens in the owner's dashboard
70
+ * (app.gemmein.com), on purpose.
71
+ */
72
+ export class Gemmein {
73
+ constructor(options) {
74
+ // A missing key must land on the signpost below, not a TypeError —
75
+ // gemmein(undefined) is exactly the "env var didn't load" case.
76
+ if (options?.appKey?.startsWith("sk_")) {
77
+ throw new GemmeinError({
78
+ status: 0,
79
+ code: "invalid_app_key",
80
+ message: "Secret keys (sk_) must not be used in the client SDK — use gemmeinServer() instead"
81
+ });
82
+ }
83
+ // The signpost: an AI building without a key gets routed, not stuck.
84
+ if (!options?.appKey || !options.appKey.startsWith("pk_")) {
85
+ throw new GemmeinError({
86
+ status: 0,
87
+ code: "missing_app_key",
88
+ message: 'Gemmein needs your app key (it starts with "pk_"). Get one in 30 seconds: ' +
89
+ "sign in at https://app.gemmein.com with an email code (free, no card) and " +
90
+ 'copy the key from the Setup page. Then: gemmein("pk_...")'
91
+ });
92
+ }
93
+ const config = {
94
+ apiUrl: options.apiUrl ?? "https://api.gemmein.com",
95
+ appKey: options.appKey,
96
+ tokenStore: options.tokenStore ?? defaultTokenStore(options.appKey)
97
+ };
98
+ this.auth = new AuthClient(config);
99
+ this.storage = new StorageClient(config);
100
+ this.subscriptions = new SubscriptionsClient(config);
101
+ this.payments = new PaymentsClient(config);
102
+ this.account = new AccountClient(config);
103
+ }
104
+ /**
105
+ * Your app's data — `g.collection<{ title: string }>("notes")`. The
106
+ * canonical spelling; `g.storage.collection(name)` is the same client.
107
+ */
108
+ collection(name) {
109
+ return this.storage.collection(name);
110
+ }
111
+ }
112
+ // Factory forms — what the copied prompts teach. `gemmein("pk_...")` reads
113
+ // better in an AI prompt than a class instantiation, and both accept an
114
+ // options object when more than a key is needed.
115
+ // ROUND-8 FIND: `gemmein(key, { apiUrl })` is the call shape people (and
116
+ // AIs) write naturally — silently dropping the second argument misrouted a
117
+ // local app to production. Both forms are now first-class.
118
+ export function gemmein(appKeyOrOptions, options) {
119
+ return new Gemmein(typeof appKeyOrOptions === "string"
120
+ ? { appKey: appKeyOrOptions, ...(options ?? {}) }
121
+ : appKeyOrOptions);
122
+ }
123
+ export function gemmeinServer(secretKeyOrOptions, options) {
124
+ return new GemmeinServer(typeof secretKeyOrOptions === "string"
125
+ ? { secretKey: secretKeyOrOptions, ...(options ?? {}) }
126
+ : secretKeyOrOptions);
127
+ }
128
+ export class AuthClient {
129
+ constructor(config) {
130
+ this.config = config;
131
+ }
132
+ async sendEmailCode(email) {
133
+ await this.request("/auth/email/start", {
134
+ method: "POST",
135
+ body: JSON.stringify({ email }),
136
+ headers: { "content-type": "application/json" }
137
+ });
138
+ }
139
+ async verifyEmailCode(input) {
140
+ const result = await this.request("/auth/email/verify", {
141
+ method: "POST",
142
+ body: JSON.stringify(input),
143
+ headers: { "content-type": "application/json" }
144
+ });
145
+ if (isSessionResponse(result)) {
146
+ await this.config.tokenStore.set(result.token);
147
+ return result;
148
+ }
149
+ throw new Error("Gemmein auth response did not include a session token");
150
+ }
151
+ async logout() {
152
+ try {
153
+ await this.request("/auth/logout", { method: "POST" });
154
+ }
155
+ finally {
156
+ // Even if the network call fails, the user asked to be signed out.
157
+ await this.config.tokenStore.clear();
158
+ }
159
+ }
160
+ async currentUser() {
161
+ // Contract: "who am I?" never throws for session state — the server
162
+ // answers 200 {authenticated:false} for a token it won't honour right
163
+ // now, same as no token. We deliberately do NOT clear the stored token
164
+ // here: authenticated:false also covers a SUSPENDED user, whose session
165
+ // is intact and restored on unsuspend — clearing it would make a
166
+ // reversible suspension permanently sign them out. A genuinely expired
167
+ // token is harmless to keep (the next data-plane call 401s and the app
168
+ // re-auths); logout() and g.account.delete() are the deliberate clears.
169
+ //
170
+ // Moderation note: authenticated:false is deliberately SILENT about the
171
+ // why — signed out, suspended, and erased all read the same here, so a
172
+ // moderated user's state is never leaked to the client. Build the
173
+ // signed-out screen for all three.
174
+ return this.request("/auth/current-user");
175
+ }
176
+ request(path, init = {}) {
177
+ return runtimeRequest(this.config, path, init);
178
+ }
179
+ }
180
+ /**
181
+ * SUBS: the subscription primitive, self-service side. Gemmein keeps
182
+ * exactly one subscription per customer — created by the payment itself,
183
+ * updated by Stripe's signed webhooks, overridable by the owner in their
184
+ * dashboard. The client surface is deliberately read-plus-checkout only:
185
+ * there is no client write path to plan or status, by design.
186
+ */
187
+ export class SubscriptionsClient {
188
+ constructor(config) {
189
+ this.config = config;
190
+ }
191
+ /**
192
+ * The signed-in user's subscription — gate features with
193
+ * `(await g.subscriptions.mine())?.plan === "pro"`. Null when payments
194
+ * are off or this user has never paid; throws GemmeinError (401) when
195
+ * nobody is signed in — a data route, not the never-throw current-user
196
+ * contract.
197
+ */
198
+ async mine() {
199
+ const result = (await runtimeRequest(this.config, "/auth/subscription"));
200
+ return result.subscription;
201
+ }
202
+ /**
203
+ * Start a Stripe checkout for a plan — Gemmein mints the URL with the
204
+ * signed-in buyer and the plan already wired in (never build checkout
205
+ * URLs yourself; raw emails get silently dropped by Stripe's URL rules).
206
+ * In a browser this redirects immediately; it also resolves with the URL
207
+ * (for non-browser callers or custom handling). Requires a signed-in user
208
+ * and a plan whose Payment Link the app owner has pasted in their
209
+ * dashboard; omit `plan` to buy the app's paid plan.
210
+ */
211
+ async checkout(plan) {
212
+ const query = plan ? `?plan=${encodeURIComponent(plan)}` : "";
213
+ const result = (await runtimeRequest(this.config, `/auth/checkout${query}`));
214
+ if (typeof window !== "undefined" && window.location) {
215
+ window.location.assign(result.url);
216
+ }
217
+ return result;
218
+ }
219
+ }
220
+ /** The one-off purchase primitive — things, not plans (plans are `g.subscriptions`). */
221
+ export class PaymentsClient {
222
+ constructor(config) {
223
+ this.config = config;
224
+ }
225
+ /**
226
+ * Buy a one-off product — `g.payments.buy("poster")`. Redirects in
227
+ * browsers, and resolves with the URL. The optional `item` note names
228
+ * WHAT is being bought when one product covers many things (e.g. a
229
+ * license tier across a catalog):
230
+ * `g.payments.buy("premium license", { item: "beat_37" })`.
231
+ * A completed payment writes a receipt record addressed to the buyer in
232
+ * the owner's receipts collection; gate downloads/fulfilment on that
233
+ * receipt, never on the redirect coming back.
234
+ */
235
+ async buy(product, options) {
236
+ const params = new URLSearchParams({ product });
237
+ if (options?.item)
238
+ params.set("item", options.item);
239
+ const result = (await runtimeRequest(this.config, `/auth/pay?${params.toString()}`));
240
+ if (typeof window !== "undefined" && window.location) {
241
+ window.location.assign(result.url);
242
+ }
243
+ return result;
244
+ }
245
+ }
246
+ /** The signed-in user's own account — self-service, one deliberate power. */
247
+ export class AccountClient {
248
+ constructor(config) {
249
+ this.config = config;
250
+ }
251
+ /**
252
+ * Self-service erasure — the "delete my account" screen. Every app it
253
+ * APPLIES to needs one (GDPR right to erasure; Apple 5.1.1(v) requires it
254
+ * for any app with account creation). Server-side this is the full
255
+ * cascade: sessions revoked, the user's records and files deleted, their
256
+ * subscription row removed. Irreversible — put a real confirm in front
257
+ * of it.
258
+ */
259
+ async delete() {
260
+ const result = await runtimeRequest(this.config, "/auth/delete-account", { method: "POST" });
261
+ await this.config.tokenStore.clear();
262
+ return result;
263
+ }
264
+ }
265
+ function isSessionResponse(value) {
266
+ return (typeof value === "object" &&
267
+ value !== null &&
268
+ "token" in value &&
269
+ typeof value.token === "string");
270
+ }
271
+ export class StorageClient {
272
+ constructor(config) {
273
+ this.config = config;
274
+ }
275
+ /** Optionally type your fields: `g.storage.collection<{ title: string }>("notes")`. */
276
+ collection(name) {
277
+ assertCollectionName(name);
278
+ return new CollectionClient(this.config, name);
279
+ }
280
+ }
281
+ /**
282
+ * Talks to one collection. Collections themselves are created by the app
283
+ * owner in their dashboard (app.gemmein.com → data) — a 404
284
+ * `unknown_collection` means it doesn't exist yet: ask the owner to create
285
+ * it there, don't retry.
286
+ */
287
+ export class CollectionClient {
288
+ constructor(config, name) {
289
+ this.config = config;
290
+ this.name = name;
291
+ }
292
+ /**
293
+ * Create a record from your fields. The signed-in user becomes its owner.
294
+ *
295
+ * For anything two users can race for (a booking slot, a unique slug, a
296
+ * limited drop), pass a deterministic `key` derived from the thing that
297
+ * must be unique: `create(data, { key: "slot:2026-07-15T15:00" })`.
298
+ * The second writer gets a 409 GemmeinError `conflict` — that error IS
299
+ * the booking system working: catch it and tell the user it's taken.
300
+ * Your own retry with the same key returns the record you already made
301
+ * (`existing: true`) instead of a duplicate. Deleting a keyed record
302
+ * frees its key.
303
+ *
304
+ * On `addressed` and `direct` collections every create names its
305
+ * recipient: `create(data, { for: userId })` — the server stamps it,
306
+ * and only that user (plus the sender/owner) will ever read the record.
307
+ * Sending to a non-user is a 400 `invalid_audience`; a 403 `reply_only`
308
+ * means this collection only allows replies to people who wrote to you
309
+ * first — tell the user, don't retry.
310
+ *
311
+ * On the PUBLIC rules (public_read, community) pass `{ published: false }`
312
+ * to save a DRAFT the public can't see (the author still sees their own;
313
+ * the owner sees all). Publish later with
314
+ * `update(id, {}, { published: true })`. This is server-enforced — never
315
+ * fake drafts with a data field + client-side filtering: on a public
316
+ * collection the data still reaches everyone.
317
+ */
318
+ async create(data, options = {}) {
319
+ const query = new URLSearchParams();
320
+ if (options.key !== undefined)
321
+ query.set("key", options.key);
322
+ if (options.for !== undefined)
323
+ query.set("for", options.for);
324
+ if (options.published !== undefined)
325
+ query.set("published", String(options.published));
326
+ const qs = query.toString();
327
+ return this.request(qs ? `?${qs}` : "", {
328
+ method: "POST",
329
+ body: JSON.stringify(data)
330
+ });
331
+ }
332
+ /**
333
+ * List records this user is allowed to see under the collection's safety
334
+ * rule (the app owner sees everyone's). Returns `{ records, hasMore }` —
335
+ * an object, not a bare array.
336
+ */
337
+ async list(options = {}) {
338
+ const query = new URLSearchParams();
339
+ if (options.limit !== undefined)
340
+ query.set("limit", String(options.limit));
341
+ if (options.sort)
342
+ query.set("sort", options.sort);
343
+ if (options.where)
344
+ query.set("where", JSON.stringify(options.where));
345
+ if (options.cursor)
346
+ query.set("cursor", options.cursor);
347
+ if (options.search)
348
+ query.set("search", options.search);
349
+ if (options.expand && options.expand.length > 0)
350
+ query.set("expand", options.expand.join(","));
351
+ // NOT query.size — absent on Node <19.8 / older browsers, where
352
+ // `undefined > 0` would silently drop every filter.
353
+ const qs = query.toString();
354
+ return this.request(qs ? `?${qs}` : "");
355
+ }
356
+ async get(id, options = {}) {
357
+ const qs = options.expand && options.expand.length > 0 ? `?expand=${encodeURIComponent(options.expand.join(","))}` : "";
358
+ return this.request(`/${encodeURIComponent(id)}${qs}`);
359
+ }
360
+ /**
361
+ * Merge-updates `data` fields; returns the full updated record.
362
+ *
363
+ * Counters that users race for (stock, seats) must never be computed
364
+ * client-side — put an atomic op in value position and the server does
365
+ * the math on current state: `update(id, { stock: { decrement: 1,
366
+ * floor: 0 } })`. Breaching the floor/ceiling → 409 `conflict` ("out of
367
+ * stock" — the limit working, not a bug). An object is treated as an op
368
+ * ONLY when its keys are exactly increment|decrement (+ optional
369
+ * floor|ceiling), all numbers.
370
+ *
371
+ * When different people can edit the same record (CMS pages, shared
372
+ * docs), pass `{ ifVersion: record.version }` — a stale save gets a 409
373
+ * `conflict` instead of clobbering; re-read, reapply, retry.
374
+ */
375
+ async update(id, data, options = {}) {
376
+ const query = new URLSearchParams();
377
+ if (options.ifVersion !== undefined)
378
+ query.set("ifVersion", String(options.ifVersion));
379
+ if (options.published !== undefined)
380
+ query.set("published", String(options.published));
381
+ const qs = query.toString();
382
+ return this.request(`/${encodeURIComponent(id)}${qs ? `?${qs}` : ""}`, {
383
+ method: "PATCH",
384
+ body: JSON.stringify(data)
385
+ });
386
+ }
387
+ async delete(id) {
388
+ await this.request(`/${encodeURIComponent(id)}`, { method: "DELETE" });
389
+ }
390
+ async upload(file, options) {
391
+ const name = options?.name ?? (file instanceof File ? file.name : "upload");
392
+ // Step 1: Get presigned upload URL
393
+ const presign = await this.request("/upload", {
394
+ method: "POST",
395
+ body: JSON.stringify({ name, size: file.size, contentType: file.type }),
396
+ });
397
+ // Step 2: Upload directly to S3 via presigned POST
398
+ const form = new FormData();
399
+ for (const [key, value] of Object.entries(presign.fields)) {
400
+ form.append(key, value);
401
+ }
402
+ form.append("file", file); // Must be last — S3 presigned POST requirement
403
+ const s3Response = await fetch(presign.uploadUrl, { method: "POST", body: form });
404
+ if (!s3Response.ok) {
405
+ throw new GemmeinError({
406
+ status: s3Response.status,
407
+ code: "upload_failed",
408
+ message: `Upload failed: ${s3Response.status}`,
409
+ });
410
+ }
411
+ // Step 3: Confirm upload
412
+ const confirmed = await this.request(`/upload/${encodeURIComponent(presign.fileId)}/confirm`, {
413
+ method: "POST",
414
+ });
415
+ return confirmed;
416
+ }
417
+ async request(suffix, init = {}) {
418
+ const response = await fetch(new URL(`/storage/${encodeURIComponent(this.name)}${suffix}`, this.config.apiUrl), {
419
+ ...init,
420
+ headers: await runtimeHeaders(this.config, {
421
+ "content-type": "application/json",
422
+ ...init.headers
423
+ })
424
+ });
425
+ return handleResponse(response, this.config);
426
+ }
427
+ }
428
+ export class GemmeinServer {
429
+ constructor(options) {
430
+ // Same signpost law as the client: a missing key (env var didn't load)
431
+ // must be a typed error, never a TypeError.
432
+ if (!options?.secretKey || !options.secretKey.startsWith("sk_")) {
433
+ throw new GemmeinError({
434
+ status: 0,
435
+ code: "invalid_secret_key",
436
+ message: options?.secretKey?.startsWith("pk_")
437
+ ? "Public keys (pk_) must not be used with GemmeinServer — use the Gemmein client SDK instead"
438
+ : 'GemmeinServer needs a secret key (it starts with "sk_") — create one in the dashboard at https://app.gemmein.com and pass it from a server env var'
439
+ });
440
+ }
441
+ this.apiUrl = options.apiUrl ?? "https://api.gemmein.com";
442
+ this.secretKey = options.secretKey;
443
+ }
444
+ collection(name) {
445
+ assertCollectionName(name);
446
+ return new ServerCollectionClient(this.apiUrl, this.secretKey, name);
447
+ }
448
+ /**
449
+ * Mint a member session for a test email WITHOUT an OTP round-trip — so a CI
450
+ * self-test ("reaffirm") can sign in as N test users and prove your app's
451
+ * isolation boundaries hold (user B genuinely can't read user A's private
452
+ * records). DEV ENVIRONMENTS ONLY: throws `test_session_forbidden_live` on an
453
+ * `sk_live` key, and the server refuses it too. Never ship this in app code.
454
+ * Pass the returned `token` to `gemmein(pk, { tokenStore })` to act as that user.
455
+ */
456
+ async testSession(email) {
457
+ if (this.secretKey.startsWith("sk_live")) {
458
+ throw new GemmeinError({
459
+ status: 0,
460
+ code: "test_session_forbidden_live",
461
+ message: "test sessions are only available in a development environment — never with a live (sk_live) key",
462
+ });
463
+ }
464
+ const response = await fetch(new URL("/server/test-session", this.apiUrl), {
465
+ method: "POST",
466
+ headers: { "x-app-key": this.secretKey, "content-type": "application/json" },
467
+ body: JSON.stringify({ email }),
468
+ });
469
+ if (!response.ok) {
470
+ const body = await response.json().catch(() => ({ code: "request_failed", message: `Request failed: ${response.status}` }));
471
+ throw new GemmeinError({
472
+ status: response.status,
473
+ code: body.code ?? "request_failed",
474
+ message: body.message ?? `Request failed: ${response.status}`,
475
+ });
476
+ }
477
+ return response.json();
478
+ }
479
+ }
480
+ class ServerCollectionClient {
481
+ constructor(apiUrl, secretKey, name) {
482
+ this.apiUrl = apiUrl;
483
+ this.secretKey = secretKey;
484
+ this.name = name;
485
+ }
486
+ async get(id) {
487
+ return this.request(`/${encodeURIComponent(id)}`);
488
+ }
489
+ async list(options = {}) {
490
+ const query = new URLSearchParams();
491
+ if (options.limit !== undefined)
492
+ query.set("limit", String(options.limit));
493
+ if (options.sort)
494
+ query.set("sort", options.sort);
495
+ if (options.where)
496
+ query.set("where", JSON.stringify(options.where));
497
+ if (options.cursor)
498
+ query.set("cursor", options.cursor);
499
+ if (options.search)
500
+ query.set("search", options.search);
501
+ if (options.expand && options.expand.length > 0)
502
+ query.set("expand", options.expand.join(","));
503
+ // NOT query.size — absent on Node <19.8 / older browsers, where
504
+ // `undefined > 0` would silently drop every filter.
505
+ const qs = query.toString();
506
+ return this.request(qs ? `?${qs}` : "");
507
+ }
508
+ async update(id, data) {
509
+ return this.request(`/${encodeURIComponent(id)}`, {
510
+ method: "PATCH",
511
+ body: JSON.stringify(data),
512
+ });
513
+ }
514
+ async request(suffix, init = {}) {
515
+ const headers = {
516
+ "x-app-key": this.secretKey,
517
+ };
518
+ if (init.body) {
519
+ headers["content-type"] = "application/json";
520
+ }
521
+ const response = await fetch(new URL(`/storage/${encodeURIComponent(this.name)}${suffix}`, this.apiUrl), { ...init, headers });
522
+ if (response.status === 204)
523
+ return undefined;
524
+ if (!response.ok) {
525
+ const body = await response.json().catch(() => ({ code: "request_failed", message: `Request failed: ${response.status}` }));
526
+ throw new GemmeinError({
527
+ status: response.status,
528
+ code: body.code ?? "request_failed",
529
+ message: body.message ?? `Request failed: ${response.status}`,
530
+ });
531
+ }
532
+ return response.json();
533
+ }
534
+ }
535
+ async function handleResponse(response, config) {
536
+ if (response.status === 204)
537
+ return undefined;
538
+ if (!response.ok) {
539
+ const errorBody = await readErrorBody(response);
540
+ if (errorBody.code === "auth_expired") {
541
+ await config.tokenStore.clear();
542
+ }
543
+ // Signpost: a wrong/revoked key routes the builder (or their AI) to
544
+ // where a working key comes from, instead of dead-ending.
545
+ if (errorBody.code === "invalid_app_key" || errorBody.code === "missing_app_key") {
546
+ errorBody.message += " — get your app key from the Setup page at https://app.gemmein.com (sign in with an email code, free, no card)";
547
+ }
548
+ throw new GemmeinError({
549
+ status: response.status,
550
+ code: errorBody.code,
551
+ message: errorBody.message,
552
+ resetAt: errorBody.resetAt
553
+ });
554
+ }
555
+ return response.json();
556
+ }
557
+ async function readErrorBody(response) {
558
+ try {
559
+ const value = await response.json();
560
+ if (typeof value === "object" && value !== null) {
561
+ const code = typeof value.code === "string"
562
+ ? value.code
563
+ : typeof value.error === "string"
564
+ ? value.error
565
+ : "request_failed";
566
+ return {
567
+ code,
568
+ message: typeof value.message === "string"
569
+ ? value.message
570
+ : `Gemmein request failed: ${response.status}`,
571
+ resetAt: typeof value.resetAt === "string"
572
+ ? value.resetAt
573
+ : undefined
574
+ };
575
+ }
576
+ }
577
+ catch {
578
+ // Fall through to a stable typed error.
579
+ }
580
+ return {
581
+ code: "request_failed",
582
+ message: `Gemmein request failed: ${response.status}`
583
+ };
584
+ }
585
+ // One request path for every runtime client (auth, subscriptions,
586
+ // payments, account) — same headers, same error handling, same signposts.
587
+ async function runtimeRequest(config, path, init = {}) {
588
+ const response = await fetch(new URL(path, config.apiUrl), {
589
+ ...init,
590
+ headers: await runtimeHeaders(config, init.headers)
591
+ });
592
+ return handleResponse(response, config);
593
+ }
594
+ async function runtimeHeaders(config, headers) {
595
+ const token = await config.tokenStore.get();
596
+ return {
597
+ ...headers,
598
+ "x-app-key": config.appKey,
599
+ ...(token ? { authorization: `Bearer ${token}` } : {})
600
+ };
601
+ }
602
+ const COLLECTION_NAME_RE = /^[a-z][a-z0-9_]{1,62}$/;
603
+ function assertCollectionName(name) {
604
+ if (!COLLECTION_NAME_RE.test(name)) {
605
+ throw new GemmeinError({
606
+ status: 0,
607
+ code: "invalid_collection_name",
608
+ message: `Collection name must be lowercase letters, numbers, and underscores (e.g. "tasks", "user_notes"). Got: "${name}"`
609
+ });
610
+ }
611
+ }