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