zitejs 0.0.1 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md ADDED
@@ -0,0 +1,30 @@
1
+ # zitejs
2
+
3
+ The Zite framework package. Provides typed access to your Zite Database, API endpoints, authentication, and more.
4
+
5
+ ## Usage
6
+
7
+ ```ts
8
+ // Database client (generated per-project by `zite sync`)
9
+ import { zite } from 'zitejs/db';
10
+ const users = await zite.users.findMany();
11
+
12
+ // Define API endpoints
13
+ import { createEndpoint, ZiteError } from 'zitejs/api';
14
+ export default createEndpoint({
15
+ execute: async ({ input }) => { ... },
16
+ });
17
+
18
+ // Authentication
19
+ import { useAuth } from 'zitejs/auth';
20
+ const { user } = useAuth();
21
+
22
+ // File uploads
23
+ import { useUpload } from 'zitejs/upload';
24
+
25
+ // PDF generation
26
+ import { ZitePdf } from 'zitejs/pdf';
27
+
28
+ // Scheduled tasks
29
+ import { ZiteSchedule } from 'zitejs/schedules';
30
+ ```
package/api/index.d.ts ADDED
@@ -0,0 +1,42 @@
1
+ /**
2
+ * zitejs/api — Server-side endpoint definition.
3
+ *
4
+ * Usage:
5
+ * import { createEndpoint, ZiteError } from 'zitejs/api';
6
+ *
7
+ * export default createEndpoint({
8
+ * description: 'Get user by ID',
9
+ * inputSchema: z.object({ id: z.string() }),
10
+ * outputSchema: z.object({ name: z.string() }),
11
+ * execute: async ({ input }) => {
12
+ * const user = await zite.users.findOne(input.id);
13
+ * return { name: user.name };
14
+ * },
15
+ * });
16
+ */
17
+
18
+ export interface ZiteRequestContext {
19
+ userId?: string;
20
+ organizationId?: string;
21
+ [key: string]: unknown;
22
+ }
23
+
24
+ export interface ZiteScheduledContext extends ZiteRequestContext {
25
+ scheduledAt: string;
26
+ }
27
+
28
+ export declare class ZiteError extends Error {
29
+ constructor(message: string, options?: { statusCode?: number });
30
+ statusCode: number;
31
+ }
32
+
33
+ export declare function createEndpoint<TInput = unknown, TOutput = unknown>(config: {
34
+ description?: string;
35
+ inputSchema?: unknown;
36
+ outputSchema?: unknown;
37
+ stream?: boolean;
38
+ execute: (params: {
39
+ input: TInput;
40
+ context: ZiteRequestContext | ZiteScheduledContext;
41
+ }) => Promise<TOutput> | TOutput;
42
+ }): unknown;
package/api/index.js ADDED
@@ -0,0 +1,13 @@
1
+ // zitejs/api — runtime stub.
2
+ // The actual implementations are injected by the Zite sandbox at runtime.
3
+ export class ZiteError extends Error {
4
+ constructor(message, options) {
5
+ super(message);
6
+ this.name = 'ZiteError';
7
+ this.statusCode = options?.statusCode ?? 500;
8
+ }
9
+ }
10
+
11
+ export function createEndpoint(config) {
12
+ return config;
13
+ }
@@ -0,0 +1,23 @@
1
+ /**
2
+ * zitejs/auth — Authentication helpers.
3
+ *
4
+ * Usage:
5
+ * import { useAuth } from 'zitejs/auth';
6
+ * const { user, isLoading } = useAuth();
7
+ */
8
+
9
+ export interface ZiteUser {
10
+ id: string;
11
+ email?: string;
12
+ name?: string;
13
+ [key: string]: unknown;
14
+ }
15
+
16
+ export declare function useAuth(): {
17
+ user: ZiteUser | null;
18
+ isLoading: boolean;
19
+ authLoading: boolean;
20
+ logout: () => void;
21
+ };
22
+
23
+ export declare function getCurrentUser(): ZiteUser | null;
package/auth/index.js ADDED
@@ -0,0 +1,8 @@
1
+ // zitejs/auth — runtime stub.
2
+ export function useAuth() {
3
+ return { user: null, isLoading: true, authLoading: true, logout: () => {} };
4
+ }
5
+
6
+ export function getCurrentUser() {
7
+ return null;
8
+ }
package/db/index.d.ts ADDED
@@ -0,0 +1,34 @@
1
+ /**
2
+ * zitejs/db — The database client.
3
+ *
4
+ * The `zite` object is generated per-project by `zite sync` and provides
5
+ * typed access to your Zite Database tables.
6
+ *
7
+ * Usage:
8
+ * import { zite } from 'zitejs/db';
9
+ * const users = await zite.users.findMany();
10
+ *
11
+ * The actual `zite` object is generated into `.zite/db.ts` in your project.
12
+ * This module re-exports it. If you see type errors, run `zite sync` to
13
+ * regenerate the client.
14
+ */
15
+
16
+ export declare const zite: Record<
17
+ string,
18
+ {
19
+ findMany(params?: Record<string, unknown>): Promise<{
20
+ records: Record<string, unknown>[];
21
+ hasMore: boolean;
22
+ }>;
23
+ findOne(id: string): Promise<Record<string, unknown>>;
24
+ create(data: Record<string, unknown>): Promise<Record<string, unknown>>;
25
+ update(
26
+ id: string,
27
+ data: Record<string, unknown>,
28
+ ): Promise<Record<string, unknown>>;
29
+ delete(id: string): Promise<void>;
30
+ bulkCreate(
31
+ items: Record<string, unknown>[],
32
+ ): Promise<Record<string, unknown>[]>;
33
+ }
34
+ >;
package/db/index.js ADDED
@@ -0,0 +1,23 @@
1
+ // zitejs/db — runtime stub.
2
+ // The actual `zite` object is generated by `zite sync` into .zite/db.ts.
3
+ // This stub exists so the package resolves; the generated code overrides it.
4
+ export const zite = new Proxy(
5
+ {},
6
+ {
7
+ get(_, tableName) {
8
+ const notGenerated = () => {
9
+ throw new Error(
10
+ `zite.${String(tableName)} is not available. Run \`zite sync\` to generate the database client.`,
11
+ );
12
+ };
13
+ return {
14
+ findMany: notGenerated,
15
+ findOne: notGenerated,
16
+ create: notGenerated,
17
+ update: notGenerated,
18
+ delete: notGenerated,
19
+ bulkCreate: notGenerated,
20
+ };
21
+ },
22
+ },
23
+ );
package/package.json CHANGED
@@ -1,13 +1,50 @@
1
1
  {
2
2
  "name": "zitejs",
3
- "version": "0.0.1",
4
- "main": "index.js",
5
- "scripts": {
6
- "test": "echo \"Error: no test specified\" && exit 1"
3
+ "version": "0.2.0",
4
+ "description": "The Zite framework — build apps on Zite Database",
5
+ "type": "module",
6
+ "bin": {
7
+ "zitejs": "./sync/index.js"
7
8
  },
8
- "keywords": [],
9
- "author": "",
10
- "license": "ISC",
11
- "description": "Official Zite JavaScript SDK",
12
- "types": "index.d.ts"
9
+ "exports": {
10
+ "./db": {
11
+ "types": "./db/index.d.ts",
12
+ "default": "./db/index.js"
13
+ },
14
+ "./api": {
15
+ "types": "./api/index.d.ts",
16
+ "default": "./api/index.js"
17
+ },
18
+ "./auth": {
19
+ "types": "./auth/index.d.ts",
20
+ "default": "./auth/index.js"
21
+ },
22
+ "./upload": {
23
+ "types": "./upload/index.d.ts",
24
+ "default": "./upload/index.js"
25
+ },
26
+ "./pdf": {
27
+ "types": "./pdf/index.d.ts",
28
+ "default": "./pdf/index.js"
29
+ },
30
+ "./schedules": {
31
+ "types": "./schedules/index.d.ts",
32
+ "default": "./schedules/index.js"
33
+ }
34
+ },
35
+ "files": [
36
+ "db",
37
+ "api",
38
+ "auth",
39
+ "upload",
40
+ "pdf",
41
+ "schedules",
42
+ "sync"
43
+ ],
44
+ "keywords": ["zite", "zitejs", "framework", "database", "vibe-coding"],
45
+ "license": "MIT",
46
+ "repository": {
47
+ "type": "git",
48
+ "url": "https://github.com/zite/zitejs"
49
+ }
13
50
  }
package/pdf/index.d.ts ADDED
@@ -0,0 +1,15 @@
1
+ /**
2
+ * zitejs/pdf — PDF generation.
3
+ *
4
+ * Usage:
5
+ * import { ZitePdf } from 'zitejs/pdf';
6
+ * const pdf = new ZitePdf();
7
+ * const result = await pdf.generate({ html: '<h1>Hello</h1>' });
8
+ */
9
+
10
+ export declare class ZitePdf {
11
+ generate(options: { html: string; [key: string]: unknown }): Promise<{
12
+ url: string;
13
+ [key: string]: unknown;
14
+ }>;
15
+ }
package/pdf/index.js ADDED
@@ -0,0 +1,6 @@
1
+ // zitejs/pdf — runtime stub.
2
+ export class ZitePdf {
3
+ async generate() {
4
+ throw new Error('ZitePdf is not available outside the Zite sandbox.');
5
+ }
6
+ }
@@ -0,0 +1,19 @@
1
+ /**
2
+ * zitejs/schedules — Scheduled task helpers.
3
+ *
4
+ * Usage:
5
+ * import { ZiteSchedule } from 'zitejs/schedules';
6
+ */
7
+
8
+ export declare class ZiteSchedule {
9
+ static create(config: {
10
+ name: string;
11
+ cron: string;
12
+ endpoint: string;
13
+ input?: Record<string, unknown>;
14
+ }): Promise<{ id: string }>;
15
+
16
+ static delete(id: string): Promise<void>;
17
+
18
+ static list(): Promise<Array<{ id: string; name: string; cron: string }>>;
19
+ }
@@ -0,0 +1,12 @@
1
+ // zitejs/schedules — runtime stub.
2
+ export class ZiteSchedule {
3
+ static async create() {
4
+ throw new Error('ZiteSchedule is not available outside the Zite sandbox.');
5
+ }
6
+ static async delete() {
7
+ throw new Error('ZiteSchedule is not available outside the Zite sandbox.');
8
+ }
9
+ static async list() {
10
+ throw new Error('ZiteSchedule is not available outside the Zite sandbox.');
11
+ }
12
+ }
package/sync/index.js ADDED
@@ -0,0 +1,221 @@
1
+ #!/usr/bin/env node
2
+
3
+ /**
4
+ * zitejs sync — fetches your Zite Database schema and generates
5
+ * a typed .zite/db.ts client with a fetch()-based runtime.
6
+ *
7
+ * Usage:
8
+ * ZITE_DB_TOKEN=sk_prod_... npx zitejs sync
9
+ *
10
+ * Environment:
11
+ * ZITE_DB_TOKEN — API token (required)
12
+ * ZITE_DB_URL — Base URL (default: https://tables.fillout.com/api/v1)
13
+ * ZITE_BASE_ID — Database ID (auto-detected from zite.config.json if omitted)
14
+ */
15
+
16
+ import { readFileSync, writeFileSync, mkdirSync, existsSync } from 'fs';
17
+ import { join, dirname } from 'path';
18
+
19
+ const BASE_URL =
20
+ process.env.ZITE_DB_URL ?? 'https://tables.fillout.com/api/v1';
21
+ const TOKEN = process.env.ZITE_DB_TOKEN ?? '';
22
+
23
+ // Field type → TypeScript type mapping
24
+ const FIELD_TYPE_MAP = {
25
+ single_line_text: 'string',
26
+ long_text: 'string',
27
+ email: 'string',
28
+ url: 'string',
29
+ phone_number: 'string',
30
+ number: 'number',
31
+ currency: 'number',
32
+ percent: 'number',
33
+ rating: 'number',
34
+ duration: 'number',
35
+ single_select: 'string',
36
+ multiple_select: 'string[]',
37
+ checkbox: 'boolean',
38
+ date: 'string',
39
+ datetime: 'string',
40
+ attachments: 'Array<{ url: string; name?: string }>',
41
+ linked_record: 'string[]',
42
+ lookup: 'unknown',
43
+ autonumber: 'number',
44
+ source: 'string',
45
+ };
46
+
47
+ function toLowerCamel(name) {
48
+ return name.charAt(0).toLowerCase() + name.slice(1);
49
+ }
50
+
51
+ function toPascalCase(name) {
52
+ return name
53
+ .replace(/[^a-zA-Z0-9]+(.)/g, (_, c) => c.toUpperCase())
54
+ .replace(/^(.)/, (_, c) => c.toUpperCase());
55
+ }
56
+
57
+ function toCamelCase(name) {
58
+ const pascal = toPascalCase(name);
59
+ return toLowerCamel(pascal);
60
+ }
61
+
62
+ function tsTypeForField(field) {
63
+ return FIELD_TYPE_MAP[field.type] ?? 'unknown';
64
+ }
65
+
66
+ async function fetchBaseMetadata(baseId) {
67
+ const url = `${BASE_URL}/bases/${encodeURIComponent(baseId)}`;
68
+ const res = await fetch(url, {
69
+ headers: { Authorization: `Bearer ${TOKEN}` },
70
+ });
71
+ if (!res.ok) {
72
+ throw new Error(
73
+ `Failed to fetch base metadata (${res.status}): ${await res.text()}`,
74
+ );
75
+ }
76
+ return res.json();
77
+ }
78
+
79
+ function generateSchema(base) {
80
+ const schema = { tables: {} };
81
+ for (const table of base.tables ?? []) {
82
+ const tableName = toCamelCase(table.name);
83
+ const fields = {};
84
+ for (const field of table.fields ?? []) {
85
+ fields[toCamelCase(field.name)] = { id: field.id };
86
+ }
87
+ schema.tables[tableName] = { id: table.id, fields };
88
+ }
89
+ return schema;
90
+ }
91
+
92
+ function generateDbTs(base, schema, baseId) {
93
+ const lines = [];
94
+
95
+ lines.push('// Auto-generated by zitejs sync. Do not edit manually.');
96
+ lines.push('');
97
+
98
+ // Runtime
99
+ lines.push(`const BASE_URL = process.env.ZITE_DB_URL ?? 'https://tables.fillout.com/api/v1';`);
100
+ lines.push(`const TOKEN = process.env.ZITE_DB_TOKEN ?? '';`);
101
+ lines.push('');
102
+ lines.push('async function dbFetch(method: string, path: string, body?: unknown) {');
103
+ lines.push(' const res = await fetch(BASE_URL + path, {');
104
+ lines.push(' method,');
105
+ lines.push(' headers: {');
106
+ lines.push(' Authorization: `Bearer ${TOKEN}`,');
107
+ lines.push(" ...(body ? { 'Content-Type': 'application/json' } : {}),");
108
+ lines.push(' },');
109
+ lines.push(' body: body ? JSON.stringify(body) : undefined,');
110
+ lines.push(' });');
111
+ lines.push(' if (!res.ok) {');
112
+ lines.push(" const text = await res.text().catch(() => '');");
113
+ lines.push(' throw new Error(`Zite DB request failed (${res.status}): ${text}`);');
114
+ lines.push(' }');
115
+ lines.push(' return res.json();');
116
+ lines.push('}');
117
+ lines.push('');
118
+
119
+ // Per-table types + client
120
+ for (const table of base.tables ?? []) {
121
+ const className = toPascalCase(table.name);
122
+ const propName = toCamelCase(table.name);
123
+ const recordType = `${className}RecordType`;
124
+
125
+ // Record type
126
+ lines.push(`export type ${recordType} = {`);
127
+ lines.push(' id: string;');
128
+ for (const field of table.fields ?? []) {
129
+ const fieldName = toCamelCase(field.name);
130
+ const tsType = tsTypeForField(field);
131
+ lines.push(` ${fieldName}: ${tsType};`);
132
+ }
133
+ lines.push(' createdAt: string;');
134
+ lines.push(' updatedAt: string;');
135
+ lines.push('};');
136
+ lines.push('');
137
+ }
138
+
139
+ // createTableClient helper
140
+ lines.push('function createTableClient<T>(baseId: string, tableId: string) {');
141
+ lines.push(' const base = `/bases/${encodeURIComponent(baseId)}/tables/${encodeURIComponent(tableId)}`;');
142
+ lines.push(' return {');
143
+ lines.push(' findMany: (options?: { limit?: number; offset?: number; sort?: unknown[]; filter?: unknown }): Promise<{ records: T[]; total: number; hasMore: boolean }> =>');
144
+ lines.push(' dbFetch("POST", `${base}/records/list`, options),');
145
+ lines.push(' findOne: (recordId: string): Promise<T> =>');
146
+ lines.push(' dbFetch("GET", `${base}/records/${encodeURIComponent(recordId)}`),');
147
+ lines.push(' create: (data: Partial<T>): Promise<T> =>');
148
+ lines.push(' dbFetch("POST", `${base}/records`, { record: data }),');
149
+ lines.push(' update: (recordId: string, data: Partial<T>): Promise<T> =>');
150
+ lines.push(' dbFetch("PATCH", `${base}/records/${encodeURIComponent(recordId)}`, { record: data }),');
151
+ lines.push(' delete: (recordId: string): Promise<{ deleted: true }> =>');
152
+ lines.push(' dbFetch("DELETE", `${base}/records/${encodeURIComponent(recordId)}`),');
153
+ lines.push(' bulkCreate: (records: Partial<T>[]): Promise<T[]> =>');
154
+ lines.push(' dbFetch("POST", `${base}/records/bulk`, { records }),');
155
+ lines.push(' };');
156
+ lines.push('}');
157
+ lines.push('');
158
+
159
+ // Singleton
160
+ lines.push(`const BASE_ID = '${baseId}';`);
161
+ lines.push('');
162
+ lines.push('export const zite = {');
163
+ for (const table of base.tables ?? []) {
164
+ const className = toPascalCase(table.name);
165
+ const propName = toCamelCase(table.name);
166
+ const tableId = schema.tables[propName]?.id ?? table.id;
167
+ lines.push(` ${propName}: createTableClient<${className}RecordType>(BASE_ID, '${tableId}'),`);
168
+ }
169
+ lines.push('};');
170
+ lines.push('');
171
+
172
+ return lines.join('\n');
173
+ }
174
+
175
+ async function main() {
176
+ if (!TOKEN) {
177
+ console.error('Error: ZITE_DB_TOKEN is required. Set it in your .env or environment.');
178
+ process.exit(1);
179
+ }
180
+
181
+ // Find base ID from zite.config.json or env
182
+ let baseId = process.env.ZITE_BASE_ID;
183
+ if (!baseId) {
184
+ try {
185
+ const config = JSON.parse(readFileSync('zite.config.json', 'utf-8'));
186
+ baseId = config.project?.basePublicIdentifier;
187
+ } catch {
188
+ // ignore
189
+ }
190
+ }
191
+
192
+ if (!baseId) {
193
+ console.error('Error: Could not determine base ID. Set ZITE_BASE_ID or ensure zite.config.json exists.');
194
+ process.exit(1);
195
+ }
196
+
197
+ console.log(`Syncing database ${baseId}...`);
198
+
199
+ const base = await fetchBaseMetadata(baseId);
200
+ console.log(`Found ${base.tables?.length ?? 0} tables`);
201
+
202
+ const schema = generateSchema(base);
203
+
204
+ // Write zite.schema.json
205
+ writeFileSync('zite.schema.json', JSON.stringify(schema, null, 2));
206
+ console.log('Wrote zite.schema.json');
207
+
208
+ // Write .zite/db.ts
209
+ const dbTs = generateDbTs(base, schema, baseId);
210
+ const dbPath = join('.zite', 'db.ts');
211
+ mkdirSync(dirname(dbPath), { recursive: true });
212
+ writeFileSync(dbPath, dbTs);
213
+ console.log(`Wrote ${dbPath}`);
214
+
215
+ console.log('Done!');
216
+ }
217
+
218
+ main().catch(err => {
219
+ console.error('Sync failed:', err.message);
220
+ process.exit(1);
221
+ });
@@ -0,0 +1,11 @@
1
+ /**
2
+ * zitejs/upload — File upload helpers.
3
+ *
4
+ * Usage:
5
+ * import { useUpload } from 'zitejs/upload';
6
+ */
7
+
8
+ export declare function useUpload(): {
9
+ upload: (file: File) => Promise<{ url: string }>;
10
+ isUploading: boolean;
11
+ };
@@ -0,0 +1,4 @@
1
+ // zitejs/upload — runtime stub.
2
+ export function useUpload() {
3
+ return { upload: async () => ({ url: '' }), isUploading: false };
4
+ }
package/index.d.ts DELETED
@@ -1 +0,0 @@
1
- export {};
package/index.js DELETED
@@ -1 +0,0 @@
1
- module.exports = {};