@teable/app 0.0.0-stage → 5.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/LICENSE +21 -0
- package/README.md +227 -2
- package/dist/build/cli.d.ts +2 -0
- package/dist/build/cli.js +19 -0
- package/dist/build/index.d.ts +31 -0
- package/dist/build/index.js +8 -0
- package/dist/chunks/323GVFSV.js +117 -0
- package/dist/chunks/5QIBCQL5.js +52 -0
- package/dist/chunks/EVNB2DU2.js +1126 -0
- package/dist/chunks/JQWQD45Z.js +116 -0
- package/dist/chunks/LV3ZHKKL.js +157 -0
- package/dist/client.d.ts +100 -0
- package/dist/client.js +9 -0
- package/dist/index.d.ts +12 -0
- package/dist/index.js +14 -0
- package/dist/protocol.d.ts +401 -0
- package/dist/protocol.js +38 -0
- package/dist/schema.d.ts +45 -0
- package/dist/schema.js +13 -0
- package/dist/server/app.d.ts +138 -0
- package/dist/server/changefeed.d.ts +52 -0
- package/dist/server/cron.d.ts +26 -0
- package/dist/server/errors.d.ts +21 -0
- package/dist/server/migrations.d.ts +36 -0
- package/dist/server/schedules.d.ts +16 -0
- package/dist/server/tasks.d.ts +51 -0
- package/dist/testing.d.ts +38 -0
- package/dist/testing.js +69 -0
- package/package.json +55 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Teable, Inc.
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,228 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @teable/app
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Write a Teable app as a Drizzle schema plus methods. The platform runs it in
|
|
4
|
+
its own Durable Object with its own SQLite database, and turns its methods into
|
|
5
|
+
an HTTP API and MCP tools.
|
|
6
|
+
|
|
7
|
+
## Install
|
|
8
|
+
|
|
9
|
+
```sh
|
|
10
|
+
bun add @teable/app drizzle-orm
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
Or start from the blank app: `npx @teable/create-app my-app`. Apps run in
|
|
14
|
+
workerd, their pages in browsers; `@teable/app/build`, `@teable/app/schema`,
|
|
15
|
+
`@teable/app/protocol` and `@teable/app/client` also load in Node 18 or
|
|
16
|
+
later, and the `teable-app` command runs with Bun. The server's declarations
|
|
17
|
+
use the Workers types (`@cloudflare/workers-types`).
|
|
18
|
+
|
|
19
|
+
## An app
|
|
20
|
+
|
|
21
|
+
The shop template is the reference app; every file in it is tested.
|
|
22
|
+
|
|
23
|
+
| File | Shows |
|
|
24
|
+
| ---------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------- |
|
|
25
|
+
| [`src/server/schema.ts`](../../templates/shop/src/server/schema.ts) | Drizzle tables, `col.money()` and `col.attachments()`, checks, generated columns |
|
|
26
|
+
| [`src/server/index.ts`](../../templates/shop/src/server/index.ts) | reads and writes with their outputs, a task a write enqueues, a scheduled task, `export const App = app.define()` |
|
|
27
|
+
| [`drizzle/`](../../templates/shop/drizzle) | migrations from `drizzle-kit generate`, one keeping a business rule in triggers |
|
|
28
|
+
| [`src/web/app.ts`](../../templates/shop/src/web/app.ts), [`orders.tsx`](../../templates/shop/src/web/orders.tsx) | pages: the typed client, the grid saving through a write |
|
|
29
|
+
| [`test/shop.test.ts`](../../templates/shop/test/shop.test.ts) | method tests, in workerd |
|
|
30
|
+
|
|
31
|
+
Its shape:
|
|
32
|
+
|
|
33
|
+
```ts
|
|
34
|
+
const app = createApp({ schema, migrations, capabilities: ["files"] });
|
|
35
|
+
|
|
36
|
+
export const listSkus = app.read({
|
|
37
|
+
output: z.array(schemaOf(skus)), // from @teable/app/schema
|
|
38
|
+
handler: ({ db }) => db.select().from(skus).all(),
|
|
39
|
+
});
|
|
40
|
+
|
|
41
|
+
export const sell = app.write({
|
|
42
|
+
input: z.object({ skuId: z.string(), qty: z.number().int().positive() }),
|
|
43
|
+
handler: ({ db, input, enqueue }) => {
|
|
44
|
+
// ...change rows with db; fail("CONFLICT", "...") to refuse
|
|
45
|
+
enqueue(notifyWarehouse, { skuId: input.skuId });
|
|
46
|
+
},
|
|
47
|
+
});
|
|
48
|
+
|
|
49
|
+
export const notifyWarehouse = app.task({
|
|
50
|
+
input: z.object({ skuId: z.string() }),
|
|
51
|
+
handler: async ({ input, attempt, call, files }) => {
|
|
52
|
+
// talk to the outside world here, then record the result with call(aWrite, ...)
|
|
53
|
+
},
|
|
54
|
+
});
|
|
55
|
+
|
|
56
|
+
export const App = app.define({ listSkus, sell, notifyWarehouse });
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
The server module must export the class `define` returns as `App`.
|
|
60
|
+
|
|
61
|
+
## The rules
|
|
62
|
+
|
|
63
|
+
- **Data is touched only through methods.** Pages, tables, tasks, the API and
|
|
64
|
+
MCP tools all call them.
|
|
65
|
+
- **`read`** handlers are synchronous and must not write. **`write`** handlers
|
|
66
|
+
are synchronous and atomic: if they throw, nothing they wrote is kept,
|
|
67
|
+
including tasks they enqueued. Returning a Promise from either is an error.
|
|
68
|
+
- **`task`** handlers are async. Use them for anything that waits: payment
|
|
69
|
+
providers, email, AI, other apps. They are retried with exponential backoff
|
|
70
|
+
(1 s, 2 s, 4 s, … up to 1 h) until they succeed or reach `maxAttempts`
|
|
71
|
+
(default 8), so make them idempotent.
|
|
72
|
+
- **Schedules** go on the task: `app.task({ schedule: { cron: "0 9 * * *",
|
|
73
|
+
timezone: "Asia/Shanghai" }, handler })`. Five-field cron in an IANA time
|
|
74
|
+
zone (default UTC); a run missed while the app slept fires once.
|
|
75
|
+
- **Input** is a `z.object(...)`; it becomes the JSON Schema of the API endpoint
|
|
76
|
+
and MCP tool, where a part JSON Schema cannot describe (`z.coerce.date()`,
|
|
77
|
+
`z.custom()`) accepts any value and zod checks it. Use `z` from
|
|
78
|
+
`@teable/app`. Inputs arrive as JSON: take a date as `z.iso.datetime()` or
|
|
79
|
+
`z.coerce.date()`, never `z.date()`, which JSON cannot satisfy. A task's
|
|
80
|
+
input is checked as JSON when it is enqueued, so the write fails, not every
|
|
81
|
+
run of the task.
|
|
82
|
+
- **Results** are JSON: return rows and plain objects; Dates become ISO
|
|
83
|
+
strings. Columns JSON cannot carry (bigint, binary) are refused when the app
|
|
84
|
+
is defined.
|
|
85
|
+
- **Output**: say what a read or write returns with `output`, a zod schema;
|
|
86
|
+
the API's response body and the MCP tool's output schema come from it, and
|
|
87
|
+
the builder shows results by it. Every result is checked against it, and
|
|
88
|
+
callers get what it outputs, so keys it does not declare are dropped; a
|
|
89
|
+
result it refuses fails the call as `INTERNAL`, and a write keeps nothing.
|
|
90
|
+
The handler must return what it accepts, and pages are typed with what it
|
|
91
|
+
outputs. Build it from your tables with `schemaOf` (`@teable/app/schema`):
|
|
92
|
+
`schemaOf(orders.amount)` for a value like a column's, `schemaOf(skus)` for
|
|
93
|
+
a row (`.pick`, `.omit`, `.extend` as with any zod object). They carry the
|
|
94
|
+
column's kind, so callers know money from a number, and its currency.
|
|
95
|
+
- **Access** is a minimum space role (`viewer`, `commenter`, `editor`,
|
|
96
|
+
`creator`, `owner`), `public`, or `internal`. Reads default to `viewer`,
|
|
97
|
+
writes to `editor`. Write finer rules in the handler with `ctx.caller`.
|
|
98
|
+
- **Errors**: `fail(code, message)` with `BAD_INPUT`, `FORBIDDEN`, `NOT_FOUND`
|
|
99
|
+
or `CONFLICT`, the only codes an app raises. SQLite constraint violations
|
|
100
|
+
surface as `CONSTRAINT`; anything else thrown is `INTERNAL`.
|
|
101
|
+
- **Put rules SQLite can enforce in SQLite**: `notNull`, `check`, foreign keys,
|
|
102
|
+
`unique`, generated columns, triggers.
|
|
103
|
+
- **Migrations** come from `drizzle-kit generate` (driver `durable-sqlite`,
|
|
104
|
+
`bun run db:generate`) and are append-only: never edit or delete one that
|
|
105
|
+
may have run. The app does not start when its database lacks a table or
|
|
106
|
+
column `schema.ts` declares (a schema change without a migration), or when a
|
|
107
|
+
migration loses one of the app's triggers: a table rebuild drops them, so
|
|
108
|
+
re-create them in the same migration. Nor does it start when a rebuild would
|
|
109
|
+
delete or change rows that reference the table with `onDelete: "cascade"`,
|
|
110
|
+
`"set null"` or `"set default"`; the error says how to write the migration.
|
|
111
|
+
- Every row change is recorded with the call that made it (the changefeed),
|
|
112
|
+
and history is kept for 30 days. Table names starting with `_teable_` are
|
|
113
|
+
reserved.
|
|
114
|
+
|
|
115
|
+
## Tasks
|
|
116
|
+
|
|
117
|
+
A task's handler receives:
|
|
118
|
+
|
|
119
|
+
- `input`, parsed by its schema;
|
|
120
|
+
- `attempt`, 1 on the first run;
|
|
121
|
+
- `call(method, input)`, which runs one of the app's reads or writes and is the
|
|
122
|
+
only way a task touches data;
|
|
123
|
+
- the capabilities the app declared, such as `files`.
|
|
124
|
+
|
|
125
|
+
App code has no network unless it declares `http`; every other service
|
|
126
|
+
outside the app arrives as a capability too.
|
|
127
|
+
|
|
128
|
+
## Capabilities
|
|
129
|
+
|
|
130
|
+
An app declares the platform services it uses:
|
|
131
|
+
`createApp({ schema, migrations, capabilities: ["files"] })`. The manifest lists
|
|
132
|
+
them, and the platform wires only those into the app. Using one the app did
|
|
133
|
+
not declare fails with a message that says how to declare it.
|
|
134
|
+
|
|
135
|
+
`files`, in tasks as `ctx.files`:
|
|
136
|
+
|
|
137
|
+
- `put({ name, type, data })` stores a file and returns an `Attachment`
|
|
138
|
+
(`{ key, name, size, type }`) to keep in a `col.attachments()` column
|
|
139
|
+
through a write;
|
|
140
|
+
- `get(key)` returns `{ name, type, data }`, or null;
|
|
141
|
+
- `share(key, { expiresInSeconds })` returns `{ url, expiresAt }`, a link
|
|
142
|
+
anyone can open until it expires (default 30 days, at most a year).
|
|
143
|
+
|
|
144
|
+
Inputs that take files validate them with `z.array(attachment)`, from
|
|
145
|
+
`@teable/app/schema`.
|
|
146
|
+
|
|
147
|
+
`http`: the app's own `fetch()` reaches other services, so npm SDKs (Stripe,
|
|
148
|
+
Feishu, ...) work as they are; `ctx.http.fetch` is the same. Only tasks can
|
|
149
|
+
wait for a response (reads and writes are synchronous). The platform meters
|
|
150
|
+
every request for the app's space and refuses its own hosts. Without `http`,
|
|
151
|
+
`fetch()` fails with "This worker is not permitted to access the internet".
|
|
152
|
+
|
|
153
|
+
## Layout
|
|
154
|
+
|
|
155
|
+
```
|
|
156
|
+
src/server/schema.ts Drizzle tables (also loaded by drizzle-kit in Node)
|
|
157
|
+
src/server/index.ts methods; exports App
|
|
158
|
+
src/web/ pages (Vite + TanStack Router), in the browser
|
|
159
|
+
src/components/ registry components, e.g. `npx shadcn add @teable/grid`
|
|
160
|
+
drizzle/ generated migrations
|
|
161
|
+
test/ method tests, in workerd
|
|
162
|
+
```
|
|
163
|
+
|
|
164
|
+
Pages import server code with `import type` only (enforced); the bundle the
|
|
165
|
+
browser loads never contains server code.
|
|
166
|
+
|
|
167
|
+
## Pages
|
|
168
|
+
|
|
169
|
+
```ts
|
|
170
|
+
// src/web/app.ts
|
|
171
|
+
import { createClient, type MethodOutput } from "@teable/app/client";
|
|
172
|
+
import type * as server from "../server";
|
|
173
|
+
|
|
174
|
+
export const shop = createClient<typeof server>({ appId });
|
|
175
|
+
export type Order = MethodOutput<typeof server, "recentOrders">[number];
|
|
176
|
+
|
|
177
|
+
// anywhere in a page
|
|
178
|
+
const orders = await shop.call("recentOrders", { limit: 50 }); // typed by name
|
|
179
|
+
```
|
|
180
|
+
|
|
181
|
+
- Names, inputs and results come from the `App` the server module exports:
|
|
182
|
+
the names `define()` registered, and a method's results from its `output`
|
|
183
|
+
when it declares one. Internal methods and tasks are not
|
|
184
|
+
callable from pages, and calling one is a type error.
|
|
185
|
+
- Results are JSON: Dates arrive as ISO strings (the types say so).
|
|
186
|
+
- Failures throw `MethodError` with `error.code`, `error.message`, the HTTP
|
|
187
|
+
`status`, and `retryable`: false for a refusal (below 500), which asking
|
|
188
|
+
again does not change.
|
|
189
|
+
- With TanStack Query: `queryKey: shop.queryKey(method, input)` for methods
|
|
190
|
+
and `shop.manifestKey` for the manifest. `shop.subscribe(listener)` reports
|
|
191
|
+
`changes` (a call changed data: every method's result, under
|
|
192
|
+
`shop.dataKey`, is stale, the manifest is not), `deployed` (a new version
|
|
193
|
+
went live) and `reconnected` (the connection is back after dropping); after
|
|
194
|
+
those two anything may have changed, the manifest included. The shop
|
|
195
|
+
template sets this up once for all its pages (`refetchAfter` in
|
|
196
|
+
`src/web/app.ts`, subscribed in `src/web/main.tsx`).
|
|
197
|
+
- `shop.manifest()` describes the app's tables and methods, as far as the
|
|
198
|
+
caller may see them; the grid renders columns from it.
|
|
199
|
+
- Files: `shop.upload(file)` (editors, up to 100 MB) returns an `Attachment`
|
|
200
|
+
to save with a write; `shop.fileUrl(attachment)` is where members read it;
|
|
201
|
+
`shop.share(attachment, { expiresInSeconds })` makes a link anyone can open
|
|
202
|
+
until it expires.
|
|
203
|
+
|
|
204
|
+
## Testing
|
|
205
|
+
|
|
206
|
+
```ts
|
|
207
|
+
import { env } from "cloudflare:test";
|
|
208
|
+
import { testApp } from "@teable/app/testing";
|
|
209
|
+
import { sell } from "../src/server";
|
|
210
|
+
|
|
211
|
+
it("sells", async () => {
|
|
212
|
+
const app = testApp(env.APP.getByName("t1"));
|
|
213
|
+
await app.call(sell, { skuId: "tee", qty: 1 });
|
|
214
|
+
await app.runTasks();
|
|
215
|
+
});
|
|
216
|
+
```
|
|
217
|
+
|
|
218
|
+
`testApp(stub, caller?)` calls the app the way the platform does:
|
|
219
|
+
|
|
220
|
+
- `call(method, input)` returns the value as callers get it, through JSON, and
|
|
221
|
+
throws what pages get when the method fails: a `MethodError` (from
|
|
222
|
+
`@teable/app/client`) with the code's HTTP status;
|
|
223
|
+
- `invoke(method, input)` returns the raw result, with errors and effects;
|
|
224
|
+
- `runTasks(until?)` runs every task due by then (default: a year from now);
|
|
225
|
+
- `changes(since?)` reads the changefeed; `as(caller)` calls as someone else.
|
|
226
|
+
|
|
227
|
+
Build what the platform deploys with `teable-app build` (`dist/server.js`,
|
|
228
|
+
one ES module exporting only `App`).
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
#!/usr/bin/env bun
|
|
2
|
+
import {
|
|
3
|
+
buildServer
|
|
4
|
+
} from "../chunks/5QIBCQL5.js";
|
|
5
|
+
|
|
6
|
+
// src/build/cli.ts
|
|
7
|
+
import { mkdirSync, writeFileSync } from "node:fs";
|
|
8
|
+
import { join } from "node:path";
|
|
9
|
+
var [command] = process.argv.slice(2);
|
|
10
|
+
var root = process.cwd();
|
|
11
|
+
if (command === "build") {
|
|
12
|
+
const bundle = await buildServer({ root });
|
|
13
|
+
mkdirSync(join(root, "dist"), { recursive: true });
|
|
14
|
+
writeFileSync(join(root, "dist/server.js"), bundle.code);
|
|
15
|
+
console.log(`dist/server.js ${(bundle.bytes / 1024).toFixed(0)} KiB`);
|
|
16
|
+
} else {
|
|
17
|
+
console.error("usage: teable-app build");
|
|
18
|
+
process.exit(1);
|
|
19
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
export interface ServerBundle {
|
|
2
|
+
/** One ES module; imports only `cloudflare:*`. */
|
|
3
|
+
code: string;
|
|
4
|
+
bytes: number;
|
|
5
|
+
}
|
|
6
|
+
/**
|
|
7
|
+
* Bundle an app's server code into the single ES module the platform loads as a facet.
|
|
8
|
+
*
|
|
9
|
+
* The bundle exports only `App`: the Worker Loader treats every export of the
|
|
10
|
+
* main module as an entrypoint and refuses to start if one is a plain value,
|
|
11
|
+
* and apps export their methods and constants for tests.
|
|
12
|
+
*/
|
|
13
|
+
export declare function buildServer(options: {
|
|
14
|
+
root: string;
|
|
15
|
+
entry?: string;
|
|
16
|
+
minify?: boolean;
|
|
17
|
+
/** Build-time constants, as in esbuild's `define`. */
|
|
18
|
+
define?: Record<string, string>;
|
|
19
|
+
}): Promise<ServerBundle>;
|
|
20
|
+
/**
|
|
21
|
+
* Vite / Vitest plugin: import `.sql` files as text, as the server build does.
|
|
22
|
+
* drizzle-kit's durable-sqlite migrations import their SQL files directly.
|
|
23
|
+
*/
|
|
24
|
+
export declare function sqlAsText(): {
|
|
25
|
+
name: string;
|
|
26
|
+
enforce: "pre";
|
|
27
|
+
transform(code: string, id: string): {
|
|
28
|
+
code: string;
|
|
29
|
+
map: null;
|
|
30
|
+
} | undefined;
|
|
31
|
+
};
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
import {
|
|
2
|
+
APPS_PATH,
|
|
3
|
+
ERROR_STATUS,
|
|
4
|
+
FILE_NAME_HEADER,
|
|
5
|
+
fileKeyPath
|
|
6
|
+
} from "./JQWQD45Z.js";
|
|
7
|
+
|
|
8
|
+
// src/client.ts
|
|
9
|
+
var MethodError = class extends Error {
|
|
10
|
+
error;
|
|
11
|
+
status;
|
|
12
|
+
/**
|
|
13
|
+
* Whether asking again may get another answer. Below 500 the call itself
|
|
14
|
+
* was refused (its input, the caller's access, no such app, one of the
|
|
15
|
+
* app's rules), and the same call gets the same refusal, except 429: too
|
|
16
|
+
* many calls, which pass a little later. From 500 something failed that may
|
|
17
|
+
* pass.
|
|
18
|
+
*/
|
|
19
|
+
retryable;
|
|
20
|
+
constructor(error, status) {
|
|
21
|
+
super(error.message);
|
|
22
|
+
this.name = "MethodError";
|
|
23
|
+
this.error = error;
|
|
24
|
+
this.status = status;
|
|
25
|
+
this.retryable = status >= 500 || status === ERROR_STATUS.RATE_LIMITED;
|
|
26
|
+
}
|
|
27
|
+
};
|
|
28
|
+
function createClient(options) {
|
|
29
|
+
const page = globalThis.location;
|
|
30
|
+
const base = () => options.baseUrl ?? page?.origin ?? "";
|
|
31
|
+
const doFetch = options.fetch ?? globalThis.fetch.bind(globalThis);
|
|
32
|
+
const dataKey = ["teable-app", options.appId];
|
|
33
|
+
async function request(path, init = {
|
|
34
|
+
method: "GET"
|
|
35
|
+
}) {
|
|
36
|
+
const token = options.token?.();
|
|
37
|
+
const response = await doFetch(`${base()}${APPS_PATH}/${options.appId}${path}`, {
|
|
38
|
+
method: init.method,
|
|
39
|
+
headers: { ...token ? { Authorization: `Bearer ${token}` } : {}, ...init.headers },
|
|
40
|
+
body: init.body ?? null
|
|
41
|
+
});
|
|
42
|
+
const body = await response.json().catch(() => null);
|
|
43
|
+
if (!response.ok) {
|
|
44
|
+
const error = body?.error ?? {
|
|
45
|
+
code: "INTERNAL",
|
|
46
|
+
message: `HTTP ${response.status}`
|
|
47
|
+
};
|
|
48
|
+
throw new MethodError(error, response.status);
|
|
49
|
+
}
|
|
50
|
+
return body;
|
|
51
|
+
}
|
|
52
|
+
function json(value) {
|
|
53
|
+
return {
|
|
54
|
+
method: "POST",
|
|
55
|
+
body: value === void 0 ? "" : JSON.stringify(value),
|
|
56
|
+
headers: { "Content-Type": "application/json" }
|
|
57
|
+
};
|
|
58
|
+
}
|
|
59
|
+
function subscribe(listener) {
|
|
60
|
+
let socket;
|
|
61
|
+
let closed = false;
|
|
62
|
+
let attempt = 0;
|
|
63
|
+
let timer;
|
|
64
|
+
const connect = (retry) => {
|
|
65
|
+
const url = new URL(`${base()}${APPS_PATH}/${options.appId}/realtime`);
|
|
66
|
+
url.protocol = url.protocol === "https:" ? "wss:" : "ws:";
|
|
67
|
+
socket = new WebSocket(url.toString());
|
|
68
|
+
socket.onopen = () => {
|
|
69
|
+
attempt = 0;
|
|
70
|
+
if (retry) listener({ type: "reconnected" });
|
|
71
|
+
};
|
|
72
|
+
socket.onmessage = (event) => {
|
|
73
|
+
listener(JSON.parse(String(event.data)));
|
|
74
|
+
};
|
|
75
|
+
socket.onclose = () => {
|
|
76
|
+
if (closed) return;
|
|
77
|
+
attempt++;
|
|
78
|
+
timer = setTimeout(() => connect(true), Math.min(1e3 * 2 ** attempt, 3e4));
|
|
79
|
+
};
|
|
80
|
+
};
|
|
81
|
+
connect(false);
|
|
82
|
+
return () => {
|
|
83
|
+
closed = true;
|
|
84
|
+
if (timer) clearTimeout(timer);
|
|
85
|
+
socket?.close();
|
|
86
|
+
};
|
|
87
|
+
}
|
|
88
|
+
return {
|
|
89
|
+
appId: options.appId,
|
|
90
|
+
dataKey,
|
|
91
|
+
manifestKey: ["teable-manifest", options.appId],
|
|
92
|
+
call: ((method, input) => request(`/methods/${method}`, json(input))),
|
|
93
|
+
manifest: async () => await request("/manifest"),
|
|
94
|
+
queryKey: (method, input) => [...dataKey, method, input ?? {}],
|
|
95
|
+
subscribe,
|
|
96
|
+
upload: async (file, name) => await request("/files", {
|
|
97
|
+
method: "POST",
|
|
98
|
+
body: file,
|
|
99
|
+
headers: {
|
|
100
|
+
"Content-Type": file.type || "application/octet-stream",
|
|
101
|
+
[FILE_NAME_HEADER]: encodeURIComponent(
|
|
102
|
+
name ?? file.name ?? "file"
|
|
103
|
+
)
|
|
104
|
+
}
|
|
105
|
+
}),
|
|
106
|
+
fileUrl: (file) => `${base()}${APPS_PATH}/${options.appId}/files/${fileKeyPath(file.key)}`,
|
|
107
|
+
share: async (file, shareOptions) => await request(
|
|
108
|
+
`/files/${fileKeyPath(file.key)}/public`,
|
|
109
|
+
json(shareOptions ?? {})
|
|
110
|
+
)
|
|
111
|
+
};
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
export {
|
|
115
|
+
MethodError,
|
|
116
|
+
createClient
|
|
117
|
+
};
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
// src/build/index.ts
|
|
2
|
+
import { build } from "esbuild";
|
|
3
|
+
var SERVER_ENTRY = "src/server/index.ts";
|
|
4
|
+
async function buildServer(options) {
|
|
5
|
+
const entry = options.entry ?? SERVER_ENTRY;
|
|
6
|
+
const result = await build({
|
|
7
|
+
absWorkingDir: options.root,
|
|
8
|
+
stdin: {
|
|
9
|
+
contents: `export { App } from ${JSON.stringify(`./${entry}`)};`,
|
|
10
|
+
resolveDir: options.root,
|
|
11
|
+
sourcefile: "teable-app-entry.js",
|
|
12
|
+
loader: "js"
|
|
13
|
+
},
|
|
14
|
+
define: options.define ?? {},
|
|
15
|
+
bundle: true,
|
|
16
|
+
format: "esm",
|
|
17
|
+
platform: "neutral",
|
|
18
|
+
target: "es2024",
|
|
19
|
+
conditions: ["workerd", "worker", "browser"],
|
|
20
|
+
mainFields: ["module", "main"],
|
|
21
|
+
external: ["cloudflare:*"],
|
|
22
|
+
loader: { ".sql": "text" },
|
|
23
|
+
minify: options.minify ?? true,
|
|
24
|
+
legalComments: "none",
|
|
25
|
+
write: false,
|
|
26
|
+
logLevel: "silent"
|
|
27
|
+
}).catch((error) => {
|
|
28
|
+
const reasons = error.errors?.map((e) => e.text) ?? [String(error)];
|
|
29
|
+
if (reasons.some((r) => r.includes("No matching export") && r.includes('"App"'))) {
|
|
30
|
+
throw new Error(`${entry} must export the class from define() as "App"`);
|
|
31
|
+
}
|
|
32
|
+
throw new Error(`Could not build ${entry}: ${reasons.join("; ")}`);
|
|
33
|
+
});
|
|
34
|
+
const [output] = result.outputFiles;
|
|
35
|
+
if (output === void 0) throw new Error("esbuild produced no output");
|
|
36
|
+
return { code: output.text, bytes: output.contents.byteLength };
|
|
37
|
+
}
|
|
38
|
+
function sqlAsText() {
|
|
39
|
+
return {
|
|
40
|
+
name: "teable:sql-as-text",
|
|
41
|
+
enforce: "pre",
|
|
42
|
+
transform(code, id) {
|
|
43
|
+
if (!id.endsWith(".sql")) return void 0;
|
|
44
|
+
return { code: `export default ${JSON.stringify(code)};`, map: null };
|
|
45
|
+
}
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export {
|
|
50
|
+
buildServer,
|
|
51
|
+
sqlAsText
|
|
52
|
+
};
|