@teable/app 5.0.1 → 6.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/build/cli.js +12 -3
- package/dist/build/index.d.ts +105 -0
- package/dist/build/index.js +8 -3
- package/dist/chunks/{EVNB2DU2.js → 33OZ5YAY.js} +16 -6
- package/dist/chunks/{323GVFSV.js → L6RROFUY.js} +14 -4
- package/dist/chunks/{LV3ZHKKL.js → N7LBNIRZ.js} +1 -1
- package/dist/chunks/TXLTJKEX.js +353 -0
- package/dist/chunks/{JQWQD45Z.js → VMIIUPHE.js} +17 -1
- package/dist/client.d.ts +24 -3
- package/dist/client.js +2 -2
- package/dist/dev/host.d.ts +74 -0
- package/dist/dev/host.js +388 -0
- package/dist/index.js +3 -3
- package/dist/protocol.d.ts +107 -4
- package/dist/protocol.js +13 -3
- package/dist/schema.js +2 -2
- package/dist/server/app.d.ts +8 -1
- package/dist/testing.js +4 -4
- package/dist/worker.d.ts +59 -0
- package/dist/worker.js +33 -0
- package/package.json +10 -1
- package/dist/chunks/5QIBCQL5.js +0 -52
package/dist/client.d.ts
CHANGED
|
@@ -11,9 +11,13 @@
|
|
|
11
11
|
* JSON, so Dates are ISO strings. Works with TanStack Query: `queryKey` and
|
|
12
12
|
* `manifestKey` name the queries, `subscribe` tells you when they went stale,
|
|
13
13
|
* and `MethodError.retryable` which failures to ask again.
|
|
14
|
+
*
|
|
15
|
+
* Pages are served at the app's own host, signed in with a session the
|
|
16
|
+
* platform keeps there (ADR 0014): `session()` says who is signed in,
|
|
17
|
+
* `signIn()` and `signOut()` change it.
|
|
14
18
|
*/
|
|
15
19
|
import type { z } from "zod";
|
|
16
|
-
import { type AppErrorShape, type Attachment, type Jsonify, type JsonValue, type ManifestResponse, type PublicLink, type RealtimeMessage } from "./protocol.js";
|
|
20
|
+
import { type AppErrorShape, type Attachment, type Jsonify, type JsonValue, type ManifestResponse, type PublicLink, type RealtimeMessage, type SessionResponse } from "./protocol.js";
|
|
17
21
|
/** An app's server module as its pages see it: `App` is the class `define()` returned. */
|
|
18
22
|
export type ServerModule = {
|
|
19
23
|
App: {
|
|
@@ -36,10 +40,18 @@ export type MethodName<S> = S extends Untyped ? string : {
|
|
|
36
40
|
access: infer A;
|
|
37
41
|
} ? [A] extends ["internal"] ? never : K : never;
|
|
38
42
|
}[keyof Methods<S>] & string;
|
|
39
|
-
|
|
43
|
+
/** Names of every read and write, internal ones included: what the app itself may call. */
|
|
44
|
+
export type AppMethodName<S> = S extends Untyped ? string : {
|
|
45
|
+
[K in keyof Methods<S>]: Methods<S>[K] extends {
|
|
46
|
+
kind: "read" | "write";
|
|
47
|
+
} ? K : never;
|
|
48
|
+
}[keyof Methods<S>] & string;
|
|
49
|
+
/** What a method takes: its input schema's input type (JSON for an untyped client). */
|
|
50
|
+
export type MethodInput<S, K extends string> = S extends Untyped ? JsonValue : K extends keyof Methods<S> ? Methods<S>[K] extends {
|
|
40
51
|
input: infer I extends z.ZodType;
|
|
41
52
|
} ? z.input<I> : never : never;
|
|
42
|
-
|
|
53
|
+
/** What a method gives callers: its value as JSON carries it (Dates become strings). */
|
|
54
|
+
export type MethodOutput<S, K extends string> = S extends Untyped ? unknown : K extends keyof Methods<S> ? Methods<S>[K] extends {
|
|
43
55
|
handler(ctx: never): infer R;
|
|
44
56
|
} ? Jsonify<R> : never : never;
|
|
45
57
|
/** A method failed; `error` is what the app reported. */
|
|
@@ -95,6 +107,15 @@ export interface AppClient<S> {
|
|
|
95
107
|
share(file: Pick<Attachment, "key">, options?: {
|
|
96
108
|
expiresInSeconds?: number;
|
|
97
109
|
}): Promise<PublicLink>;
|
|
110
|
+
/** Who is signed in to the app's pages, on its own host, and until when. */
|
|
111
|
+
session(): Promise<SessionResponse>;
|
|
112
|
+
/**
|
|
113
|
+
* Sign in to the app's pages with Teable, on its own host: the browser goes
|
|
114
|
+
* there and comes back to `returnTo` (a path; this page by default).
|
|
115
|
+
*/
|
|
116
|
+
signIn(returnTo?: string): void;
|
|
117
|
+
/** Sign out of the app's pages, on its own host. Signing out of Teable is Teable's. */
|
|
118
|
+
signOut(): Promise<void>;
|
|
98
119
|
}
|
|
99
120
|
export declare function createClient<S extends ServerModule | Untyped = Untyped>(options: ClientOptions): AppClient<S>;
|
|
100
121
|
export {};
|
package/dist/client.js
CHANGED
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The runtime's stand-in for local development (ADR 0014, 7.): one app, on
|
|
3
|
+
* the developer's own host. `teable()`, the Vite plugin in
|
|
4
|
+
* `@teable/app/build`, runs this Worker in workerd and sends it what the
|
|
5
|
+
* runtime answers on an app's host: signing in (faked: the developer picks
|
|
6
|
+
* who to be), the app's API, and the app's own Worker, with the props it
|
|
7
|
+
* gets on the platform. The app's server code runs as a facet of a host
|
|
8
|
+
* Durable Object on a local database, as on the platform: calls are
|
|
9
|
+
* admitted with the protocol's `admit`, tasks run from the host's alarm,
|
|
10
|
+
* and realtime tells open pages what changed.
|
|
11
|
+
*/
|
|
12
|
+
import { DurableObject, WorkerEntrypoint } from "cloudflare:workers";
|
|
13
|
+
import { type AppManifest, type Attachment, type Caller, type FilesCapability, type JsonValue, type MethodValue, type PublicLink, type Result } from "../protocol.js";
|
|
14
|
+
interface DevEnv {
|
|
15
|
+
HOST: DurableObjectNamespace;
|
|
16
|
+
LOADER: WorkerLoader;
|
|
17
|
+
FILES: R2Bucket;
|
|
18
|
+
/** The app's id, from teable.json. */
|
|
19
|
+
APP_ID: string;
|
|
20
|
+
/** Where Vite serves the pages, which the app's Worker's ASSETS fetch. */
|
|
21
|
+
PAGES: string;
|
|
22
|
+
}
|
|
23
|
+
/** The app's host, in development: its code, its facet, its alarm and its sockets. */
|
|
24
|
+
export declare class DevHost extends DurableObject<DevEnv> {
|
|
25
|
+
#private;
|
|
26
|
+
/**
|
|
27
|
+
* Run new code on the local database at once, its migrations with it (no
|
|
28
|
+
* copy first: the data is the developer's own). Code that does not start
|
|
29
|
+
* leaves the code that ran before.
|
|
30
|
+
*/
|
|
31
|
+
deploy(code: string, worker: string | null): Promise<Result<AppManifest>>;
|
|
32
|
+
describe(): Promise<{
|
|
33
|
+
manifest: AppManifest;
|
|
34
|
+
version: number;
|
|
35
|
+
worker: string | null;
|
|
36
|
+
} | null>;
|
|
37
|
+
call(caller: Caller, method: string, input: JsonValue | undefined, readOnly?: boolean): Promise<Result<MethodValue>>;
|
|
38
|
+
alarm(): Promise<void>;
|
|
39
|
+
fetch(): Promise<Response>;
|
|
40
|
+
}
|
|
41
|
+
/** Files for the app's tasks and its Worker, as the `files` capability. */
|
|
42
|
+
export declare class Files extends WorkerEntrypoint<DevEnv> implements FilesCapability {
|
|
43
|
+
put(file: {
|
|
44
|
+
name: string;
|
|
45
|
+
type: string;
|
|
46
|
+
data: ArrayBuffer | string;
|
|
47
|
+
}): Promise<Attachment>;
|
|
48
|
+
get(key: string): Promise<{
|
|
49
|
+
name: string;
|
|
50
|
+
type: string;
|
|
51
|
+
data: ArrayBuffer;
|
|
52
|
+
} | null>;
|
|
53
|
+
share(key: string, options?: {
|
|
54
|
+
expiresInSeconds?: number;
|
|
55
|
+
}): Promise<PublicLink>;
|
|
56
|
+
}
|
|
57
|
+
/** The pages' files for the app's Worker (`env.ASSETS`): what Vite serves. */
|
|
58
|
+
export declare class Assets extends WorkerEntrypoint<DevEnv> {
|
|
59
|
+
fetch(request: Request): Promise<Response>;
|
|
60
|
+
}
|
|
61
|
+
/** The app's methods for its Worker, as the visitor. */
|
|
62
|
+
export declare class AsCaller extends WorkerEntrypoint<DevEnv, {
|
|
63
|
+
caller: Caller;
|
|
64
|
+
}> {
|
|
65
|
+
call(method: string, input?: JsonValue): Promise<Result<JsonValue>>;
|
|
66
|
+
}
|
|
67
|
+
/** The app's methods for its Worker, as the app itself. */
|
|
68
|
+
export declare class AsApp extends WorkerEntrypoint<DevEnv> {
|
|
69
|
+
call(method: string, input?: JsonValue): Promise<Result<JsonValue>>;
|
|
70
|
+
}
|
|
71
|
+
declare const _default: {
|
|
72
|
+
fetch(request: Request, env: DevEnv, ctx: ExecutionContext): Promise<Response>;
|
|
73
|
+
};
|
|
74
|
+
export default _default;
|
package/dist/dev/host.js
ADDED
|
@@ -0,0 +1,388 @@
|
|
|
1
|
+
import {
|
|
2
|
+
APPS_PATH,
|
|
3
|
+
APP_COMPATIBILITY_DATE,
|
|
4
|
+
ASSETS_HEADER,
|
|
5
|
+
DEV_PATHS,
|
|
6
|
+
ERROR_STATUS,
|
|
7
|
+
SESSION_PATH,
|
|
8
|
+
SPACE_ROLES,
|
|
9
|
+
admit,
|
|
10
|
+
callableMethods,
|
|
11
|
+
checkAccess,
|
|
12
|
+
isMember
|
|
13
|
+
} from "../chunks/VMIIUPHE.js";
|
|
14
|
+
|
|
15
|
+
// src/dev/host.ts
|
|
16
|
+
import { DurableObject, WorkerEntrypoint } from "cloudflare:workers";
|
|
17
|
+
var DEV_SESSION = "teable_dev_session";
|
|
18
|
+
var PICKS = [
|
|
19
|
+
{ who: "owner", label: "Owner" },
|
|
20
|
+
{ who: "creator", label: "Creator" },
|
|
21
|
+
{ who: "editor", label: "Editor" },
|
|
22
|
+
{ who: "commenter", label: "Commenter" },
|
|
23
|
+
{ who: "viewer", label: "Viewer" },
|
|
24
|
+
{ who: "outsider", label: "Signed in, not a member of the app's space" },
|
|
25
|
+
{ who: "anonymous", label: "Signed out" }
|
|
26
|
+
];
|
|
27
|
+
function callerOf(request) {
|
|
28
|
+
const cookie = request.headers.get("Cookie") ?? "";
|
|
29
|
+
const who = cookie.match(new RegExp(`(?:^|;\\s*)${DEV_SESSION}=([^;]+)`))?.[1];
|
|
30
|
+
if (!PICKS.some((pick) => pick.who === who) || who === "anonymous") {
|
|
31
|
+
return { kind: "anonymous", via: "web" };
|
|
32
|
+
}
|
|
33
|
+
const role = SPACE_ROLES.find((name) => name === who) ?? null;
|
|
34
|
+
return { kind: "user", userId: `dev-${who}`, role, via: "web" };
|
|
35
|
+
}
|
|
36
|
+
function errorBody(code, message) {
|
|
37
|
+
return Response.json({ error: { code, message } }, { status: ERROR_STATUS[code] });
|
|
38
|
+
}
|
|
39
|
+
function answer(result) {
|
|
40
|
+
if (!result.ok) {
|
|
41
|
+
return Response.json({ error: result.error }, { status: ERROR_STATUS[result.error.code] });
|
|
42
|
+
}
|
|
43
|
+
return Response.json(result.value ?? null);
|
|
44
|
+
}
|
|
45
|
+
async function sha256(text) {
|
|
46
|
+
const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(text));
|
|
47
|
+
return [...new Uint8Array(digest)].map((b) => b.toString(16).padStart(2, "0")).join("");
|
|
48
|
+
}
|
|
49
|
+
var KV = {
|
|
50
|
+
code: "code",
|
|
51
|
+
codeId: "codeId",
|
|
52
|
+
worker: "worker",
|
|
53
|
+
manifest: "manifest",
|
|
54
|
+
version: "version"
|
|
55
|
+
};
|
|
56
|
+
var DevHost = class extends DurableObject {
|
|
57
|
+
/**
|
|
58
|
+
* Run new code on the local database at once, its migrations with it (no
|
|
59
|
+
* copy first: the data is the developer's own). Code that does not start
|
|
60
|
+
* leaves the code that ran before.
|
|
61
|
+
*/
|
|
62
|
+
async deploy(code, worker) {
|
|
63
|
+
const kept = { code: this.#kv(KV.code), codeId: this.#kv(KV.codeId) };
|
|
64
|
+
this.ctx.storage.kv.put(KV.code, code);
|
|
65
|
+
this.ctx.storage.kv.put(KV.codeId, await sha256(code));
|
|
66
|
+
this.ctx.facets.abort("live", new Error("New code"));
|
|
67
|
+
let manifest;
|
|
68
|
+
try {
|
|
69
|
+
manifest = await this.#facet().manifest();
|
|
70
|
+
} catch (error) {
|
|
71
|
+
this.ctx.facets.abort("live", new Error("Not started"));
|
|
72
|
+
for (const [key, value] of Object.entries(kept)) {
|
|
73
|
+
if (value === void 0) this.ctx.storage.kv.delete(key);
|
|
74
|
+
else this.ctx.storage.kv.put(key, value);
|
|
75
|
+
}
|
|
76
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
77
|
+
return { ok: false, error: { code: "BAD_INPUT", message: `Not started: ${message}` } };
|
|
78
|
+
}
|
|
79
|
+
const version = (this.#kv(KV.version) ?? 0) + 1;
|
|
80
|
+
this.ctx.storage.kv.put(KV.manifest, manifest);
|
|
81
|
+
this.ctx.storage.kv.put(KV.version, version);
|
|
82
|
+
this.ctx.storage.kv.put(KV.worker, worker);
|
|
83
|
+
this.ctx.facets.abort("live", new Error("Restarted with its capabilities"));
|
|
84
|
+
await this.ctx.storage.setAlarm(Date.now());
|
|
85
|
+
this.#broadcast({ type: "deployed", version });
|
|
86
|
+
return { ok: true, value: manifest };
|
|
87
|
+
}
|
|
88
|
+
async describe() {
|
|
89
|
+
const manifest = this.#kv(KV.manifest);
|
|
90
|
+
const version = this.#kv(KV.version);
|
|
91
|
+
if (manifest === void 0 || version === void 0) return null;
|
|
92
|
+
return { manifest, version, worker: this.#kv(KV.worker) ?? null };
|
|
93
|
+
}
|
|
94
|
+
async call(caller, method, input, readOnly = false) {
|
|
95
|
+
const manifest = this.#kv(KV.manifest);
|
|
96
|
+
if (manifest === void 0) {
|
|
97
|
+
return { ok: false, error: { code: "NOT_FOUND", message: "The app has not started" } };
|
|
98
|
+
}
|
|
99
|
+
const admitted = admit(manifest, method, caller);
|
|
100
|
+
if (!admitted.ok) return admitted;
|
|
101
|
+
if (readOnly && admitted.value.kind !== "read") {
|
|
102
|
+
const message = `"${method}" changes data; call it with POST`;
|
|
103
|
+
return { ok: false, error: { code: "BAD_INPUT", message } };
|
|
104
|
+
}
|
|
105
|
+
const result = await this.#facet().invoke({ method, input, caller });
|
|
106
|
+
await this.#apply(result.effects);
|
|
107
|
+
return result.ok ? { ok: true, value: result.value } : { ok: false, error: result.error };
|
|
108
|
+
}
|
|
109
|
+
async alarm() {
|
|
110
|
+
if (this.#kv(KV.code) === void 0) return;
|
|
111
|
+
const { failed, effects } = await this.#facet().wake(Date.now());
|
|
112
|
+
for (const { method, attempt, error } of failed) {
|
|
113
|
+
console.warn(`Task ${method}, attempt ${attempt}: ${error.code}: ${error.message}`);
|
|
114
|
+
}
|
|
115
|
+
await this.#apply(effects);
|
|
116
|
+
}
|
|
117
|
+
async fetch() {
|
|
118
|
+
const [client, server] = Object.values(new WebSocketPair());
|
|
119
|
+
this.ctx.acceptWebSocket(server);
|
|
120
|
+
return new Response(null, { status: 101, webSocket: client });
|
|
121
|
+
}
|
|
122
|
+
#kv(key) {
|
|
123
|
+
return this.ctx.storage.kv.get(key);
|
|
124
|
+
}
|
|
125
|
+
async #apply(effects) {
|
|
126
|
+
if (effects.wakeAt !== null) {
|
|
127
|
+
const current = await this.ctx.storage.getAlarm();
|
|
128
|
+
if (current === null || effects.wakeAt < current) {
|
|
129
|
+
await this.ctx.storage.setAlarm(effects.wakeAt);
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
if (effects.changedTables.length > 0) {
|
|
133
|
+
this.#broadcast({ type: "changes", cursor: effects.cursor, tables: effects.changedTables });
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
#broadcast(message) {
|
|
137
|
+
for (const ws of this.ctx.getWebSockets()) {
|
|
138
|
+
try {
|
|
139
|
+
ws.send(JSON.stringify(message));
|
|
140
|
+
} catch {
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
#facet() {
|
|
145
|
+
const code = this.#kv(KV.code) ?? "";
|
|
146
|
+
const declared = this.#kv(KV.manifest)?.capabilities ?? [];
|
|
147
|
+
const files = this.ctx.exports.Files;
|
|
148
|
+
const stub = this.ctx.facets.get("live", () => {
|
|
149
|
+
const worker = this.env.LOADER.get(`${this.#kv(KV.codeId)}+${declared.join(",")}`, () => ({
|
|
150
|
+
compatibilityDate: APP_COMPATIBILITY_DATE,
|
|
151
|
+
mainModule: "app.js",
|
|
152
|
+
modules: { "app.js": code },
|
|
153
|
+
env: declared.includes("files") ? { files: files({ props: {} }) } : {},
|
|
154
|
+
// The developer's machine: an app that declared `http` reaches the internet.
|
|
155
|
+
globalOutbound: declared.includes("http") ? void 0 : null
|
|
156
|
+
}));
|
|
157
|
+
return { class: worker.getDurableObjectClass("App") };
|
|
158
|
+
});
|
|
159
|
+
return stub;
|
|
160
|
+
}
|
|
161
|
+
};
|
|
162
|
+
async function putFile(env, file) {
|
|
163
|
+
const name = file.name.replace(/[\\/]/g, "_") || "file";
|
|
164
|
+
const key = `${crypto.randomUUID()}/${name}`;
|
|
165
|
+
const type = file.type || "application/octet-stream";
|
|
166
|
+
await env.FILES.put(key, file.data, { httpMetadata: { contentType: type } });
|
|
167
|
+
return { key, name, size: file.data.byteLength, type };
|
|
168
|
+
}
|
|
169
|
+
function shareFile(env, key, seconds = 30 * 86400) {
|
|
170
|
+
const [id, name = ""] = [key.slice(0, key.indexOf("/")), key.slice(key.indexOf("/") + 1)];
|
|
171
|
+
const url = `${env.PAGES}${APPS_PATH}/${env.APP_ID}/public/${id}/${encodeURIComponent(name)}`;
|
|
172
|
+
return { url, expiresAt: Math.floor(Date.now() / 1e3) + seconds };
|
|
173
|
+
}
|
|
174
|
+
var Files = class extends WorkerEntrypoint {
|
|
175
|
+
async put(file) {
|
|
176
|
+
const data = typeof file.data === "string" ? new TextEncoder().encode(file.data) : file.data;
|
|
177
|
+
return putFile(this.env, {
|
|
178
|
+
...file,
|
|
179
|
+
data: data instanceof Uint8Array ? data.slice().buffer : data
|
|
180
|
+
});
|
|
181
|
+
}
|
|
182
|
+
async get(key) {
|
|
183
|
+
const object = await this.env.FILES.get(key);
|
|
184
|
+
if (object === null) return null;
|
|
185
|
+
const name = key.slice(key.indexOf("/") + 1);
|
|
186
|
+
return { name, type: object.httpMetadata?.contentType ?? "", data: await object.arrayBuffer() };
|
|
187
|
+
}
|
|
188
|
+
async share(key, options) {
|
|
189
|
+
return shareFile(this.env, key, options?.expiresInSeconds);
|
|
190
|
+
}
|
|
191
|
+
};
|
|
192
|
+
var Assets = class extends WorkerEntrypoint {
|
|
193
|
+
async fetch(request) {
|
|
194
|
+
const url = new URL(request.url);
|
|
195
|
+
return fetch(new URL(`${url.pathname}${url.search}`, this.env.PAGES), {
|
|
196
|
+
headers: { Accept: request.headers.get("Accept") ?? "*/*", [ASSETS_HEADER]: "1" }
|
|
197
|
+
});
|
|
198
|
+
}
|
|
199
|
+
};
|
|
200
|
+
var asJson = (result) => result.ok ? { ok: true, value: JSON.parse(JSON.stringify(result.value ?? null)) } : result;
|
|
201
|
+
var host = (env) => env.HOST.getByName("app");
|
|
202
|
+
var AsCaller = class extends WorkerEntrypoint {
|
|
203
|
+
async call(method, input) {
|
|
204
|
+
return asJson(await host(this.env).call(this.ctx.props.caller, method, input));
|
|
205
|
+
}
|
|
206
|
+
};
|
|
207
|
+
var AsApp = class extends WorkerEntrypoint {
|
|
208
|
+
async call(method, input) {
|
|
209
|
+
return asJson(await host(this.env).call({ kind: "system", via: "worker" }, method, input));
|
|
210
|
+
}
|
|
211
|
+
};
|
|
212
|
+
var escapeHtml = (text) => text.replace(/[&<>"']/g, (char) => `&#${char.charCodeAt(0)};`);
|
|
213
|
+
function pathOnHost(value) {
|
|
214
|
+
const base = "https://host.invalid";
|
|
215
|
+
try {
|
|
216
|
+
const url = new URL(value ?? "/", base);
|
|
217
|
+
if (url.origin !== base || !value?.startsWith("/")) return "/";
|
|
218
|
+
return `${url.pathname}${url.search}${url.hash}`;
|
|
219
|
+
} catch {
|
|
220
|
+
return "/";
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
function html(body, status = 200) {
|
|
224
|
+
const page = `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>Teable app (development)</title><style>body{font:16px/1.5 system-ui,sans-serif;max-width:30rem;margin:12vh auto;padding:0 1.5rem;color:#171717}button{display:block;width:100%;margin:.4rem 0;padding:.6rem .8rem;font:inherit;text-align:left;border:1px solid #d4d4d4;border-radius:.5rem;background:#fff;cursor:pointer}button[aria-current]{border-color:#171717;font-weight:600}p{color:#525252}</style></head><body>${body}</body></html>`;
|
|
225
|
+
return new Response(page, { status, headers: { "Content-Type": "text/html; charset=utf-8" } });
|
|
226
|
+
}
|
|
227
|
+
function picker(returnTo, current) {
|
|
228
|
+
const now = current.kind === "user" ? current.role ?? "outsider" : "anonymous";
|
|
229
|
+
const buttons = PICKS.map(
|
|
230
|
+
({ who, label }) => `<button name="who" value="${who}"${who === now ? " aria-current=true" : ""}>${label}</button>`
|
|
231
|
+
).join("");
|
|
232
|
+
return html(
|
|
233
|
+
`<h1>Sign in to the app</h1><p>Development: pick who to be. On Teable, people sign in with their account, and have the role they have in the app's space.</p><form method="post"><input type="hidden" name="return" value="${escapeHtml(returnTo)}">${buttons}</form>`
|
|
234
|
+
);
|
|
235
|
+
}
|
|
236
|
+
async function session(request, url) {
|
|
237
|
+
const route = `${request.method} ${url.pathname.slice(SESSION_PATH.length)}`;
|
|
238
|
+
const cookie = (who) => `${DEV_SESSION}=${who}; Path=/; HttpOnly; SameSite=Lax`;
|
|
239
|
+
switch (route) {
|
|
240
|
+
case "GET /sign-in": {
|
|
241
|
+
const returnTo = pathOnHost(url.searchParams.get("return"));
|
|
242
|
+
const caller = callerOf(request);
|
|
243
|
+
if (caller.kind === "user" && !url.searchParams.has("choose")) {
|
|
244
|
+
return new Response(null, { status: 302, headers: { Location: returnTo } });
|
|
245
|
+
}
|
|
246
|
+
return picker(returnTo, caller);
|
|
247
|
+
}
|
|
248
|
+
case "POST /sign-in": {
|
|
249
|
+
const form = await request.formData();
|
|
250
|
+
const pick = PICKS.find((p) => p.who === form.get("who"))?.who ?? "anonymous";
|
|
251
|
+
const to = pathOnHost(String(form.get("return") ?? "/"));
|
|
252
|
+
return new Response(null, {
|
|
253
|
+
status: 303,
|
|
254
|
+
headers: { Location: to, "Set-Cookie": cookie(pick) }
|
|
255
|
+
});
|
|
256
|
+
}
|
|
257
|
+
case "GET /session":
|
|
258
|
+
return Response.json({ caller: callerOf(request), expiresAt: null });
|
|
259
|
+
case "POST /sign-out":
|
|
260
|
+
return new Response(null, { status: 204, headers: { "Set-Cookie": cookie("anonymous") } });
|
|
261
|
+
}
|
|
262
|
+
return errorBody("NOT_FOUND", "Not found");
|
|
263
|
+
}
|
|
264
|
+
async function api(request, env, url) {
|
|
265
|
+
const [appId = "", ...rest] = url.pathname.slice(APPS_PATH.length + 1).split("/");
|
|
266
|
+
if (appId !== env.APP_ID) return errorBody("NOT_FOUND", "No such app");
|
|
267
|
+
const caller = callerOf(request);
|
|
268
|
+
const path = rest.join("/");
|
|
269
|
+
const app = host(env);
|
|
270
|
+
const needs = (role) => {
|
|
271
|
+
const denied = checkAccess(caller, role);
|
|
272
|
+
return denied && errorBody(denied, `Needs ${role} access to this app`);
|
|
273
|
+
};
|
|
274
|
+
if (path === "manifest" && request.method === "GET") {
|
|
275
|
+
const described = await app.describe();
|
|
276
|
+
if (described === null) return errorBody("NOT_FOUND", "The app has not started");
|
|
277
|
+
const { manifest, version } = described;
|
|
278
|
+
const visible = isMember(caller) ? manifest : { ...manifest, methods: callableMethods(manifest, caller), tables: [] };
|
|
279
|
+
return Response.json({
|
|
280
|
+
...visible,
|
|
281
|
+
appId,
|
|
282
|
+
version,
|
|
283
|
+
caller,
|
|
284
|
+
pagesUrl: env.PAGES
|
|
285
|
+
});
|
|
286
|
+
}
|
|
287
|
+
const method = path.match(/^methods\/([A-Za-z][A-Za-z0-9_]*)$/)?.[1];
|
|
288
|
+
if (method) {
|
|
289
|
+
const raw = request.method === "GET" ? url.searchParams.get("input") : await request.text();
|
|
290
|
+
let input;
|
|
291
|
+
try {
|
|
292
|
+
input = raw === null || raw.trim() === "" ? void 0 : JSON.parse(raw);
|
|
293
|
+
} catch {
|
|
294
|
+
return errorBody("BAD_INPUT", "The input must be JSON");
|
|
295
|
+
}
|
|
296
|
+
return answer(await app.call(caller, method, input, request.method === "GET"));
|
|
297
|
+
}
|
|
298
|
+
if (path === "realtime") return needs("viewer") ?? app.fetch(request);
|
|
299
|
+
if (path === "files" && request.method === "POST") {
|
|
300
|
+
const refused = needs("editor");
|
|
301
|
+
if (refused) return refused;
|
|
302
|
+
let name = "file";
|
|
303
|
+
try {
|
|
304
|
+
name = decodeURIComponent(request.headers.get("X-File-Name") ?? "file");
|
|
305
|
+
} catch {
|
|
306
|
+
}
|
|
307
|
+
const type = request.headers.get("Content-Type") ?? "";
|
|
308
|
+
const file2 = await putFile(env, { name, type, data: await request.arrayBuffer() });
|
|
309
|
+
return Response.json(file2, { status: 201 });
|
|
310
|
+
}
|
|
311
|
+
const file = path.match(/^(files|public)\/([0-9a-f-]{36})\/([^/]+)(\/public)?$/);
|
|
312
|
+
if (file) {
|
|
313
|
+
const [, kind, id, name = "", share] = file;
|
|
314
|
+
const key = `${id}/${decodeURIComponent(name)}`;
|
|
315
|
+
if (share) return needs("editor") ?? Response.json(shareFile(env, key));
|
|
316
|
+
const refused = kind === "files" ? needs("viewer") : null;
|
|
317
|
+
if (refused) return refused;
|
|
318
|
+
const object = await env.FILES.get(key);
|
|
319
|
+
if (object === null) return errorBody("NOT_FOUND", "No such file");
|
|
320
|
+
const type = object.httpMetadata?.contentType ?? "application/octet-stream";
|
|
321
|
+
return new Response(object.body, { headers: { "Content-Type": type } });
|
|
322
|
+
}
|
|
323
|
+
return errorBody("NOT_FOUND", "Not found");
|
|
324
|
+
}
|
|
325
|
+
async function gate(request, env, url) {
|
|
326
|
+
const access = (await host(env).describe())?.manifest.pages?.access ?? "viewer";
|
|
327
|
+
const denied = checkAccess(callerOf(request), access);
|
|
328
|
+
const path = pathOnHost(url.searchParams.get("path"));
|
|
329
|
+
const signIn = `${SESSION_PATH}/sign-in?return=${encodeURIComponent(path)}`;
|
|
330
|
+
const someoneElse = `${signIn}&choose`;
|
|
331
|
+
if (denied === "UNAUTHENTICATED") {
|
|
332
|
+
return new Response(null, { status: 302, headers: { Location: signIn } });
|
|
333
|
+
}
|
|
334
|
+
if (denied !== null) {
|
|
335
|
+
return html(
|
|
336
|
+
`<h1>You cannot open this app</h1><p>Its pages are for members of its space with ${escapeHtml(access)} access or more.</p><p><a href="${someoneElse}">Sign in as someone else</a></p>`,
|
|
337
|
+
403
|
|
338
|
+
);
|
|
339
|
+
}
|
|
340
|
+
return new Response(null, { status: 204 });
|
|
341
|
+
}
|
|
342
|
+
async function toWorker(request, env, ctx, url) {
|
|
343
|
+
const described = await host(env).describe();
|
|
344
|
+
if (!described?.worker) return new Response("Not found", { status: 404 });
|
|
345
|
+
const caller = callerOf(request);
|
|
346
|
+
const exports = ctx.exports;
|
|
347
|
+
const props = {
|
|
348
|
+
appId: env.APP_ID,
|
|
349
|
+
caller,
|
|
350
|
+
asCaller: exports.AsCaller({ props: { caller } }),
|
|
351
|
+
asApp: exports.AsApp({ props: {} }),
|
|
352
|
+
...described.manifest.capabilities.includes("files") ? { files: exports.Files({ props: {} }) } : {}
|
|
353
|
+
};
|
|
354
|
+
const code = described.worker;
|
|
355
|
+
const worker = env.LOADER.get(`worker-${await sha256(code)}`, () => ({
|
|
356
|
+
compatibilityDate: APP_COMPATIBILITY_DATE,
|
|
357
|
+
mainModule: "worker.js",
|
|
358
|
+
modules: { "worker.js": code },
|
|
359
|
+
env: { ASSETS: exports.Assets({ props: {} }) }
|
|
360
|
+
}));
|
|
361
|
+
const path = url.pathname.slice(DEV_PATHS.worker.length) || "/";
|
|
362
|
+
const forwarded = new Request(new URL(`${path}${url.search}`, url.origin), request);
|
|
363
|
+
return worker.getEntrypoint(void 0, { props }).fetch(forwarded);
|
|
364
|
+
}
|
|
365
|
+
var host_default = {
|
|
366
|
+
async fetch(request, env, ctx) {
|
|
367
|
+
const url = new URL(request.url);
|
|
368
|
+
if (url.pathname === DEV_PATHS.deploy) {
|
|
369
|
+
const { server, worker } = await request.json();
|
|
370
|
+
return answer(await host(env).deploy(server, worker));
|
|
371
|
+
}
|
|
372
|
+
if (url.pathname === DEV_PATHS.gate) return gate(request, env, url);
|
|
373
|
+
if (url.pathname === DEV_PATHS.worker || url.pathname.startsWith(`${DEV_PATHS.worker}/`)) {
|
|
374
|
+
return toWorker(request, env, ctx, url);
|
|
375
|
+
}
|
|
376
|
+
if (url.pathname.startsWith(`${SESSION_PATH}/`)) return session(request, url);
|
|
377
|
+
if (url.pathname.startsWith(`${APPS_PATH}/`)) return api(request, env, url);
|
|
378
|
+
return errorBody("NOT_FOUND", "Not found");
|
|
379
|
+
}
|
|
380
|
+
};
|
|
381
|
+
export {
|
|
382
|
+
AsApp,
|
|
383
|
+
AsCaller,
|
|
384
|
+
Assets,
|
|
385
|
+
DevHost,
|
|
386
|
+
Files,
|
|
387
|
+
host_default as default
|
|
388
|
+
};
|
package/dist/index.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
import {
|
|
2
2
|
createApp,
|
|
3
3
|
fail
|
|
4
|
-
} from "./chunks/
|
|
5
|
-
import "./chunks/
|
|
6
|
-
import "./chunks/
|
|
4
|
+
} from "./chunks/33OZ5YAY.js";
|
|
5
|
+
import "./chunks/N7LBNIRZ.js";
|
|
6
|
+
import "./chunks/VMIIUPHE.js";
|
|
7
7
|
|
|
8
8
|
// src/index.ts
|
|
9
9
|
import { z } from "zod";
|