@n-dream/builders-sdk 1.0.0-next.0 → 1.4.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/README.md CHANGED
@@ -3,16 +3,113 @@
3
3
  The SDK for apps on Builders (design 4.5). Apps import it from npm.
4
4
 
5
5
  ```ts
6
- import { appInfo } from "@n-dream/builders-sdk";
6
+ import * as builders from "@n-dream/builders-sdk";
7
7
 
8
- const info = await appInfo(); // { appId, slug, environment, version }
8
+ const info = await builders.appInfo(); // { appId, slug, environment, version }
9
+
10
+ const user = await builders.auth.user(); // { id, name, developer } or null
11
+ builders.auth.onChange((u) => render(u)); // now and at each change
12
+ await builders.auth.signIn(); // leaves the page; comes back signed in
13
+ await builders.auth.signOut();
14
+ builders.auth.accountPage(); // the Builders page: download or delete my data
9
15
  ```
10
16
 
11
17
  - `appInfo()` reads `/_api/app.json` on the app's own host. `environment`
12
18
  is `live`, `preview` or `version`. `version` is null on the preview.
13
- - There is no local mode (D37). Without the platform, `appInfo()` throws a
14
- `BuildersError`. Use it only for things that the page can do without.
15
- - Later platform services add one named export each (design section 12).
19
+ Without the platform, `appInfo()` throws a `BuildersError`.
20
+ - `auth` (docs/login-and-data.md 4.1, 8.1): sign-in with Google, on the
21
+ app's own host. `user.id` is this app's id of the user (another app has
22
+ another id). The app gets the name, never the email. `signIn()` goes to
23
+ the Builders sign-in page and back to the page (or to `returnTo`, a path
24
+ of the app). Previews and versions sign in only developers.
25
+ - Who can sign in is set by the app's owner in the portal (anyone, listed
26
+ domains, or listed emails).
27
+ - `BuildersError` has `code` (for example `sign-in-required`, `offline`,
28
+ `app-stopped`) and `status` (the HTTP status, 0 when no answer came).
29
+
30
+ ## Data
31
+
32
+ Each collection is declared in `builders.data.json` in the app folder
33
+ (docs/login-and-data.md 6.1): `"mine"` (each user's own, sign-in needed)
34
+ or `"public"` (everyone reads; each signed-in user adds and changes only
35
+ their own items; developers can remove any).
36
+
37
+ ```ts
38
+ const notes = builders.db.collection<{ text: string; folder: string }>("notes");
39
+ const n = await notes.add({ text: "Hi", folder: "work" });
40
+ await notes.update(n.id, { text: "Hello" });
41
+ const page = await notes.list({ where: { folder: "work" }, limit: 20 });
42
+ const stop = notes.watch({ where: { folder: "work" } }, (items) => render(items));
43
+ ```
44
+
45
+ - `get`, `set`, `update`, `remove` take an id. A short id (no dot) is
46
+ always the caller's own item. A `public` item has the id
47
+ `<user id>.<id>`.
48
+ - `list` and `count` filter only by equality on the declared `filter`
49
+ fields and sort by `createdAt`, `updatedAt` or the declared `sort`
50
+ field. `watch` gives the whole current list at once and after each
51
+ change.
52
+ - Errors are `BuildersError` with a plain message that says what to do
53
+ (8.3). There are no transactions, joins or counters; calls such as
54
+ `db.transaction` throw a message with the way to do it.
55
+ - `db.usage()`: the bytes of the signed-in user's items and files, and
56
+ their limits.
57
+ - The user guard: each request names the user that the page believes is
58
+ signed in. When the session has another user (a sign-in in another
59
+ tab), Builders refuses it with `user-changed`: nothing is read or
60
+ saved, `auth.onChange` gets the new user, and watches start again.
61
+
62
+ ## Files
63
+
64
+ A file set is declared in `builders.data.json` as `"files": { "photos":
65
+ "mine" }` (docs/login-and-data.md 7). Only the user who uploads a file
66
+ can open it, and only when signed in.
67
+
68
+ ```ts
69
+ const photos = builders.db.files("photos");
70
+ const f = await photos.upload(input.files[0]); // a File or a Blob
71
+ img.src = f.url; // "/_api/files/photos/<id>": only this user can open it
72
+ const { files, next } = await photos.list({ limit: 20 }); // newest first
73
+ await photos.remove(f.id);
74
+ ```
75
+
76
+ - Types: JPEG, PNG, WebP, GIF, AVIF, HEIC; MP3, M4A, OGG, WAV, WebM
77
+ audio; MP4, WebM video; PDF. The platform reads the first bytes of the
78
+ file: the content must be the type of the file. No SVG, HTML or
79
+ scripts.
80
+ - At most 10 MB a file, 1,000 files and 200 MB per user. Make photos
81
+ smaller in the browser before the upload (at most 2,048 pixels, JPEG
82
+ or WebP).
83
+
84
+ ## Local mode
85
+
86
+ On `localhost`, `127.0.0.1` and `[::1]` (`vite dev`, `test:headless`) the
87
+ SDK keeps everything in memory (docs/login-and-data.md 8.4), with the
88
+ same rules and limits as the platform (the same engine runs there):
89
+ `auth.signIn()` signs in "Test user 1" at once. The tabs of one browser
90
+ share the data. A file's `url` is a `blob:` URL there (there is no
91
+ `/_api/files` on localhost); `<img src>` and `<audio src>` work the same. The Vite plugin puts `builders.data.json` into the build:
92
+
93
+ ```ts
94
+ // vite.config.ts
95
+ import { builders } from "@n-dream/builders-sdk/vite";
96
+ export default defineConfig({ plugins: [builders(), react()] });
97
+ ```
98
+
99
+ Headless tests use:
100
+
101
+ ```ts
102
+ import { signInAs, signOut, reset, seed, setLoginMode } from "@n-dream/builders-sdk/testing";
103
+
104
+ signInAs("Ann"); // the same name gives the same user id
105
+ signInAs("Dev", { developer: true });
106
+ await seed("posts", [{ data: { text: "Hi" } }], { as: "Bob" });
107
+ setLoginMode("emails", ["ann@example.com"]); // then signInAs takes the email
108
+ signOut();
109
+ reset(); // no users, no data
110
+ ```
111
+
112
+ The SDK never uses the local mode on other hosts.
16
113
 
17
- Release: the owner publishes with the `next` dist-tag until the
18
- switch-over (Q29). `npm pack` builds `dist/` first.
114
+ Release: the owner publishes with the `next` dist-tag (Q29). `npm pack`
115
+ builds `dist/` first.
package/dist/auth.d.ts ADDED
@@ -0,0 +1,25 @@
1
+ export declare const USER_PATH = "/_api/user/me";
2
+ export declare const SIGNIN_PATH = "/_api/user/signin";
3
+ export declare const SIGNOUT_PATH = "/_api/user/signout";
4
+ export declare const ACCOUNT_PATH = "/_api/user/account";
5
+ export interface User {
6
+ id: string;
7
+ name: string;
8
+ developer: boolean;
9
+ }
10
+ export interface Auth {
11
+ user(): Promise<User | null>;
12
+ onChange(cb: (user: User | null) => void): () => void;
13
+ signIn(opts?: {
14
+ returnTo?: string;
15
+ }): Promise<void>;
16
+ signOut(): Promise<void>;
17
+ accountPage(): void;
18
+ }
19
+ interface Env {
20
+ fetch: typeof fetch;
21
+ location: Pick<Location, "hostname" | "pathname" | "search" | "assign">;
22
+ }
23
+ export declare function createAuth(env?: () => Env, track?: boolean): Auth;
24
+ export declare const auth: Auth;
25
+ export {};
package/dist/auth.js ADDED
@@ -0,0 +1,159 @@
1
+ import { BuildersError, codeOfStatus } from "./errors.js";
2
+ import { isLocalHost, local, localUserId, setLocalUser } from "./local.js";
3
+ import { notifyUser } from "./db.js";
4
+ import { believed } from "./session.js";
5
+ // Sign-in of app users (docs/login-and-data.md 4.1, 8.1). The app calls
6
+ // auth.signIn(); the page goes to /_api/user/signin on its own host, then
7
+ // to the Builders sign-in page with Google, and comes back signed in. The
8
+ // session is a cookie that app code cannot read.
9
+ export const USER_PATH = "/_api/user/me";
10
+ export const SIGNIN_PATH = "/_api/user/signin";
11
+ export const SIGNOUT_PATH = "/_api/user/signout";
12
+ export const ACCOUNT_PATH = "/_api/user/account";
13
+ function parseUser(v) {
14
+ if (typeof v !== "object" || v === null)
15
+ return undefined;
16
+ const u = v.user;
17
+ if (u === null)
18
+ return null;
19
+ if (typeof u !== "object")
20
+ return undefined;
21
+ const o = u;
22
+ if (typeof o.id !== "string" || !o.id || typeof o.name !== "string" || typeof o.developer !== "boolean")
23
+ return undefined;
24
+ return { id: o.id, name: o.name, developer: o.developer };
25
+ }
26
+ const same = (a, b) => a === b || (!!a && !!b && a.id === b.id && a.name === b.name && a.developer === b.developer);
27
+ // An auth for one page. `env` is for tests; the app uses `auth`.
28
+ export function createAuth(env, track = !env) {
29
+ const get = () => env?.() ?? { fetch: (...a) => globalThis.fetch(...a), location: globalThis.location };
30
+ const listeners = new Set();
31
+ let current;
32
+ let loading = null;
33
+ const isLocal = () => isLocalHost(get().location?.hostname);
34
+ function changed(u) {
35
+ if (track)
36
+ believed.uid = u?.id ?? null;
37
+ if (current !== undefined && same(current, u))
38
+ return;
39
+ const was = current;
40
+ current = u;
41
+ for (const l of [...listeners])
42
+ l(u);
43
+ // A watch of mine data ends at a sign-out (8.1). Only a change of the
44
+ // user id is a change of the user (not of the name or the developer flag).
45
+ if (was !== undefined && (was?.id ?? null) !== (u?.id ?? null))
46
+ notifyUser();
47
+ }
48
+ local.listeners.add(() => {
49
+ if (isLocal())
50
+ changed(local.user ? { ...local.user } : null);
51
+ });
52
+ async function load() {
53
+ const { fetch: f } = get();
54
+ let res;
55
+ try {
56
+ res = await f(USER_PATH, { credentials: "same-origin", cache: "no-store", headers: { accept: "application/json" } });
57
+ }
58
+ catch {
59
+ throw new BuildersError("Could not reach Builders to read the signed-in user. Check the connection and try again.", 0);
60
+ }
61
+ // No session, no developer grant (a preview), or no sign-in on this
62
+ // host: nobody is signed in.
63
+ if (res.status === 401 || res.status === 403 || res.status === 404)
64
+ return null;
65
+ if (!res.ok)
66
+ throw new BuildersError(`Builders did not give the signed-in user (status ${res.status}).`, res.status, codeOfStatus(res.status));
67
+ const u = parseUser(await res.json().catch(() => undefined));
68
+ if (u === undefined)
69
+ throw new BuildersError("The answer of Builders about the signed-in user is not valid.", res.status, "invalid");
70
+ return u;
71
+ }
72
+ async function user() {
73
+ if (isLocal()) {
74
+ const u = local.user ? { ...local.user } : null;
75
+ changed(u);
76
+ return u;
77
+ }
78
+ loading ??= load().finally(() => {
79
+ loading = null;
80
+ });
81
+ const u = await loading;
82
+ changed(u);
83
+ return u;
84
+ }
85
+ if (track)
86
+ believed.refresh = () => user();
87
+ // The first read for onChange. When it fails (offline, a short error of
88
+ // the platform), it tries again later and when the device is online, so
89
+ // that the listeners get the user in the end.
90
+ let wait = 0;
91
+ let retry = null;
92
+ function first() {
93
+ if (retry)
94
+ return;
95
+ void user().catch(() => {
96
+ if (retry || current !== undefined || !listeners.size)
97
+ return;
98
+ wait = Math.min(60_000, wait ? wait * 2 : 2_000);
99
+ const again = () => {
100
+ if (retry)
101
+ clearTimeout(retry);
102
+ retry = null;
103
+ globalThis.removeEventListener?.("online", again);
104
+ if (current === undefined && listeners.size)
105
+ first();
106
+ };
107
+ retry = setTimeout(again, wait);
108
+ globalThis.addEventListener?.("online", again);
109
+ });
110
+ }
111
+ return {
112
+ user,
113
+ onChange(cb) {
114
+ listeners.add(cb);
115
+ if (current !== undefined)
116
+ cb(current);
117
+ else
118
+ first();
119
+ return () => listeners.delete(cb);
120
+ },
121
+ async signIn(opts = {}) {
122
+ const { location } = get();
123
+ const returnTo = opts.returnTo ?? `${location.pathname}${location.search}`;
124
+ if (typeof returnTo !== "string" || !returnTo.startsWith("/") || returnTo.startsWith("//")) {
125
+ throw new BuildersError('returnTo must be a path of this app, for example "/notes".', 400, "invalid");
126
+ }
127
+ if (isLocal()) {
128
+ setLocalUser({ id: localUserId("Test user 1"), name: "Test user 1", developer: false });
129
+ return;
130
+ }
131
+ location.assign(`${SIGNIN_PATH}?return=${encodeURIComponent(returnTo)}`);
132
+ // The page leaves now.
133
+ return new Promise(() => { });
134
+ },
135
+ async signOut() {
136
+ if (isLocal())
137
+ return setLocalUser(null);
138
+ const { fetch: f } = get();
139
+ let res;
140
+ try {
141
+ res = await f(SIGNOUT_PATH, { method: "POST", credentials: "same-origin", cache: "no-store", headers: { "content-type": "application/json", "x-builders": "1" }, body: "{}" });
142
+ }
143
+ catch {
144
+ throw new BuildersError("Could not reach Builders to sign out. Check the connection and try again.", 0);
145
+ }
146
+ if (!res.ok)
147
+ throw new BuildersError(`Builders could not sign out (status ${res.status}). Try again.`, res.status);
148
+ changed(null);
149
+ },
150
+ accountPage() {
151
+ if (isLocal()) {
152
+ console.info("builders.auth.accountPage(): the account page is on the platform only. In the local mode it does nothing.");
153
+ return;
154
+ }
155
+ get().location.assign(ACCOUNT_PATH);
156
+ },
157
+ };
158
+ }
159
+ export const auth = createAuth();
package/dist/data.d.ts ADDED
@@ -0,0 +1,3 @@
1
+ import { type Db } from "./db.js";
2
+ export type { Collection, Db, FileSet, Item, Page, Query, StoredFile } from "./db.js";
3
+ export declare const db: Db;
package/dist/data.js ADDED
@@ -0,0 +1,4 @@
1
+ import { createDb } from "./db.js";
2
+ // App data (docs/login-and-data.md 8.1): db.collection(name) of
3
+ // builders.data.json.
4
+ export const db = createDb();
package/dist/db.d.ts ADDED
@@ -0,0 +1,125 @@
1
+ import { BuildersError } from "./errors.js";
2
+ import { type FileOut, type ItemOut } from "./rules.js";
3
+ export type Item<T> = ItemOut<T>;
4
+ export interface Query<F extends string = string> {
5
+ where?: Partial<Record<F, string | number | boolean | null>>;
6
+ orderBy?: "createdAt" | "updatedAt" | F;
7
+ direction?: "asc" | "desc";
8
+ limit?: number;
9
+ after?: string;
10
+ mine?: boolean;
11
+ }
12
+ export interface Page<T> {
13
+ items: Item<T>[];
14
+ next: string | null;
15
+ }
16
+ export interface Collection<T> {
17
+ add(data: T): Promise<Item<T>>;
18
+ get(id: string): Promise<Item<T> | null>;
19
+ set(id: string, data: T, opts?: {
20
+ ifRev?: number;
21
+ }): Promise<Item<T>>;
22
+ update(id: string, patch: Partial<T>, opts?: {
23
+ ifRev?: number;
24
+ }): Promise<Item<T>>;
25
+ remove(id: string): Promise<void>;
26
+ list(q?: Query): Promise<Page<T>>;
27
+ count(q?: Pick<Query, "where" | "mine">): Promise<number>;
28
+ watch(cb: (items: Item<T>[]) => void, onError?: (e: BuildersError) => void): () => void;
29
+ watch(q: Query, cb: (items: Item<T>[]) => void, onError?: (e: BuildersError) => void): () => void;
30
+ }
31
+ export type StoredFile = FileOut;
32
+ export interface FileSet {
33
+ upload(file: Blob, opts?: {
34
+ name?: string;
35
+ }): Promise<StoredFile>;
36
+ list(opts?: {
37
+ limit?: number;
38
+ after?: string;
39
+ }): Promise<{
40
+ files: StoredFile[];
41
+ next: string | null;
42
+ }>;
43
+ remove(id: string): Promise<void>;
44
+ }
45
+ export interface Db {
46
+ collection<T = Record<string, unknown>>(name: string): Collection<T>;
47
+ files(name: string): FileSet;
48
+ usage(): Promise<{
49
+ bytes: number;
50
+ bytesLimit: number;
51
+ fileBytes: number;
52
+ fileBytesLimit: number;
53
+ }>;
54
+ }
55
+ export type WatchList = {
56
+ c: string;
57
+ cursor: string;
58
+ items: ItemOut[];
59
+ removed: string[];
60
+ } | {
61
+ c: string;
62
+ resync: true;
63
+ } | {
64
+ c: string;
65
+ error: string;
66
+ message: string;
67
+ };
68
+ export interface Transport {
69
+ get(c: string, id: string): Promise<{
70
+ item: ItemOut | null;
71
+ }>;
72
+ list(c: string, q: Query): Promise<{
73
+ items: ItemOut[];
74
+ next: string | null;
75
+ cursor: string;
76
+ }>;
77
+ count(c: string, q: Query): Promise<{
78
+ count: number;
79
+ }>;
80
+ add(c: string, data: unknown): Promise<{
81
+ item: ItemOut;
82
+ }>;
83
+ set(c: string, id: string, data: unknown, ifRev?: number): Promise<{
84
+ item: ItemOut;
85
+ }>;
86
+ update(c: string, id: string, patch: unknown, ifRev?: number): Promise<{
87
+ item: ItemOut;
88
+ }>;
89
+ remove(c: string, id: string): Promise<void>;
90
+ usage(): Promise<{
91
+ bytes: number;
92
+ bytesLimit: number;
93
+ fileBytes: number;
94
+ fileBytesLimit: number;
95
+ }>;
96
+ upload(set: string, file: Blob, name: string | undefined): Promise<{
97
+ file: FileOut;
98
+ }>;
99
+ listFiles(set: string, q: {
100
+ limit?: number;
101
+ after?: string;
102
+ }): Promise<{
103
+ files: FileOut[];
104
+ next: string | null;
105
+ }>;
106
+ removeFile(set: string, id: string): Promise<void>;
107
+ watch(lists: Array<{
108
+ c: string;
109
+ cursor: string;
110
+ }>, signal: AbortSignal): Promise<{
111
+ lists: WatchList[];
112
+ next: number;
113
+ }>;
114
+ onUser(cb: () => void): () => void;
115
+ }
116
+ export declare function userChanged(): BuildersError;
117
+ export declare function errorOf(status: number, body: unknown): BuildersError;
118
+ interface Env {
119
+ fetch: typeof fetch;
120
+ }
121
+ export declare function httpTransport(env: () => Env, onUser: (cb: () => void) => () => void, claim?: () => Promise<string | null | undefined>): Transport;
122
+ export declare function createDb(transport?: () => Transport): Db;
123
+ export declare function userListeners(cb: () => void): () => void;
124
+ export declare function notifyUser(): void;
125
+ export {};