zitejs 0.9.53 → 0.9.55

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.
Files changed (42) hide show
  1. package/dist/cjs/backend/index.d.ts +10 -4
  2. package/dist/cjs/backend/index.js +1 -1
  3. package/dist/cjs/caller/index.d.ts +5 -0
  4. package/dist/cjs/caller/index.js +100 -8
  5. package/dist/cjs/dev/index.js +6 -1
  6. package/dist/cjs/internal/sdkCall.d.ts +2 -0
  7. package/dist/cjs/internal/sdkCall.js +10 -0
  8. package/dist/cjs/pdf/index.d.ts +10 -7
  9. package/dist/cjs/pdf/index.js +6 -3
  10. package/dist/cjs/runtime/index.js +14 -20
  11. package/dist/cjs/schedules/index.d.ts +101 -11
  12. package/dist/cjs/schedules/index.js +15 -9
  13. package/dist/cjs/sync/index.js +7 -4
  14. package/dist/cjs/sync/lib.d.ts +5 -1
  15. package/dist/cjs/sync/lib.js +58 -13
  16. package/dist/cjs/upload/index.d.ts +11 -1
  17. package/dist/cjs/upload/index.js +107 -1
  18. package/dist/esm/backend/index.d.ts +10 -4
  19. package/dist/esm/backend/index.js +1 -1
  20. package/dist/esm/caller/index.d.ts +5 -0
  21. package/dist/esm/caller/index.js +99 -8
  22. package/dist/esm/cli.js +0 -0
  23. package/dist/esm/dev/index.js +6 -1
  24. package/dist/esm/internal/sdkCall.d.ts +2 -0
  25. package/dist/esm/internal/sdkCall.js +7 -0
  26. package/dist/esm/pdf/index.d.ts +10 -7
  27. package/dist/esm/pdf/index.js +5 -2
  28. package/dist/esm/runtime/index.js +1 -7
  29. package/dist/esm/schedules/index.d.ts +101 -11
  30. package/dist/esm/schedules/index.js +13 -7
  31. package/dist/esm/sync/index.js +7 -4
  32. package/dist/esm/sync/lib.d.ts +5 -1
  33. package/dist/esm/sync/lib.js +58 -13
  34. package/dist/esm/upload/index.d.ts +11 -1
  35. package/dist/esm/upload/index.js +104 -1
  36. package/package.json +1 -1
  37. package/dist/cjs/api/index.js +0 -5
  38. package/dist/cjs/db/index.js +0 -5
  39. package/dist/esm/api/index.d.ts +0 -2
  40. package/dist/esm/api/index.js +0 -1
  41. package/dist/esm/db/index.d.ts +0 -2
  42. package/dist/esm/db/index.js +0 -1
@@ -1,6 +1,112 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.FileUploadError = void 0;
4
+ exports.uploadFile = uploadFile;
3
5
  exports.useUpload = useUpload;
6
+ const react_1 = require("react");
7
+ const config_js_1 = require("../auth/config.js");
8
+ const constants_js_1 = require("../auth/constants.js");
9
+ class FileUploadError extends Error {
10
+ constructor(message) {
11
+ super(message);
12
+ this.name = 'FileUploadError';
13
+ }
14
+ }
15
+ exports.FileUploadError = FileUploadError;
16
+ function getZiteAppMode(hostname) {
17
+ const maybeId = hostname.split('.')[0];
18
+ if (maybeId?.startsWith(constants_js_1.ZITE_APP_EDITOR_HOSTNAME_PREFIX))
19
+ return 'preview';
20
+ if (maybeId?.startsWith(constants_js_1.ZITE_APP_ACTION_HOSTNAME_PREFIX))
21
+ return 'preview';
22
+ if (constants_js_1.ZITE_SANDBOX_DOMAINS.some(d => hostname === d || hostname.endsWith('.' + d))) {
23
+ return 'preview';
24
+ }
25
+ return 'live';
26
+ }
27
+ function readBlobAsDataUrl(blob) {
28
+ return new Promise((resolve, reject) => {
29
+ const reader = new FileReader();
30
+ reader.onload = () => resolve(reader.result);
31
+ reader.onerror = () => reject(reader.error ?? new Error('Failed to read file'));
32
+ reader.readAsDataURL(blob);
33
+ });
34
+ }
35
+ async function toDataUrl(data) {
36
+ if (data instanceof Blob) {
37
+ return readBlobAsDataUrl(data);
38
+ }
39
+ if (data instanceof ArrayBuffer) {
40
+ const bytes = new Uint8Array(data);
41
+ let binary = '';
42
+ for (let i = 0; i < bytes.byteLength; i++) {
43
+ binary += String.fromCharCode(bytes[i]);
44
+ }
45
+ return 'data:application/octet-stream;base64,' + btoa(binary);
46
+ }
47
+ if (typeof data === 'string') {
48
+ if (data.startsWith('data:'))
49
+ return data;
50
+ if (/^[A-Za-z0-9+/]+=*$/.test(data)) {
51
+ return 'data:application/octet-stream;base64,' + data;
52
+ }
53
+ return 'data:text/plain;base64,' + btoa(unescape(encodeURIComponent(data)));
54
+ }
55
+ throw new FileUploadError('Invalid data format. Expected string, Blob, ArrayBuffer, or File.');
56
+ }
57
+ function resolveFilename(data, filename) {
58
+ if (filename)
59
+ return filename;
60
+ if (typeof File !== 'undefined' && data instanceof File && data.name) {
61
+ return data.name;
62
+ }
63
+ throw new FileUploadError('A filename is required unless the uploaded data is a File.');
64
+ }
65
+ async function performUpload(data, filename) {
66
+ const body = await toDataUrl(data);
67
+ const mode = getZiteAppMode(window.location.hostname);
68
+ const flowId = (0, config_js_1.getFlowId)();
69
+ const token = typeof localStorage !== 'undefined'
70
+ ? localStorage.getItem('zite.auth.token')
71
+ : null;
72
+ const res = await fetch((0, config_js_1.getApiUrl)() + '/v1/zite/public/' + flowId + '/upload?mode=' + mode, {
73
+ method: 'POST',
74
+ headers: {
75
+ 'Content-Type': 'application/json',
76
+ ...(token ? { Authorization: 'Bearer ' + token } : {}),
77
+ },
78
+ body: JSON.stringify({ data: body, filename }),
79
+ });
80
+ if (!res.ok) {
81
+ let message = 'Upload failed';
82
+ try {
83
+ const err = (await res.json());
84
+ if (err.message)
85
+ message = err.message;
86
+ }
87
+ catch { }
88
+ throw new FileUploadError(message);
89
+ }
90
+ const result = (await res.json());
91
+ if (!result.success || !result.fileUrl) {
92
+ throw new FileUploadError(result.message ?? 'Upload failed');
93
+ }
94
+ return result.fileUrl;
95
+ }
96
+ async function uploadFile({ data, filename, }) {
97
+ return { fileUrl: await performUpload(data, filename) };
98
+ }
4
99
  function useUpload() {
5
- throw new Error('useUpload() is only available in the Zite runtime.');
100
+ const [isUploading, setIsUploading] = (0, react_1.useState)(false);
101
+ const upload = (0, react_1.useCallback)(async (file, filename) => {
102
+ setIsUploading(true);
103
+ try {
104
+ const url = await performUpload(file, resolveFilename(file, filename));
105
+ return { url };
106
+ }
107
+ finally {
108
+ setIsUploading(false);
109
+ }
110
+ }, []);
111
+ return { upload, isUploading };
6
112
  }
@@ -21,16 +21,22 @@ type SchemaLike<T> = {
21
21
  _output: T;
22
22
  parse: (data: unknown) => T;
23
23
  };
24
- export interface EndpointConfig<TInput = unknown, TOutput = unknown> {
24
+ export type ZiteStreamInterface = {
25
+ write: (data: unknown) => Promise<void>;
26
+ forward: (asyncIterable: AsyncIterable<string>) => Promise<string>;
27
+ };
28
+ export interface EndpointConfig<TInput = unknown, TOutput = unknown, TStream extends boolean = false> {
25
29
  description?: string;
26
30
  inputSchema?: SchemaLike<TInput>;
27
31
  outputSchema?: SchemaLike<TOutput>;
28
- stream?: boolean;
32
+ stream?: TStream;
29
33
  authenticated?: boolean;
30
34
  execute: (params: {
31
35
  input: TInput;
32
36
  context: ZiteRequestContext | ZiteScheduledContext;
33
- }) => Promise<TOutput> | TOutput;
37
+ } & (TStream extends true ? {
38
+ stream: ZiteStreamInterface;
39
+ } : {})) => Promise<TOutput> | TOutput;
34
40
  }
35
- export declare function createEndpoint<TInput = unknown, TOutput = unknown>(config: EndpointConfig<TInput, TOutput>): EndpointConfig<TInput, TOutput>;
41
+ export declare function createEndpoint<TInput = unknown, TOutput = unknown, TStream extends boolean = false>(config: EndpointConfig<TInput, TOutput, TStream>): EndpointConfig<TInput, TOutput, TStream>;
36
42
  export {};
@@ -2,7 +2,7 @@ export class ZiteError extends Error {
2
2
  statusCode;
3
3
  constructor(message, options) {
4
4
  super(message);
5
- this.name = 'ZiteError';
5
+ this.name = "ZiteError";
6
6
  this.statusCode = options?.statusCode ?? 500;
7
7
  }
8
8
  }
@@ -6,3 +6,8 @@ export interface EndpointConfig<TInput = unknown, TOutput = unknown> {
6
6
  }
7
7
  export declare function createCaller<TInput, TOutput>(name: string, flowId?: string): (input: TInput) => Promise<TOutput>;
8
8
  export declare function createCaller<TInput, TOutput>(endpoint: EndpointConfig<TInput, TOutput>, name: string, flowId?: string): (input: TInput) => Promise<TOutput>;
9
+ export type StreamingResponse<T> = {
10
+ [Symbol.asyncIterator](): AsyncIterator<string>;
11
+ result: Promise<T>;
12
+ };
13
+ export declare function createStreamingCaller<TInput, TOutput>(name: string): (input: TInput) => StreamingResponse<TOutput>;
@@ -29,13 +29,15 @@ function getUsageToken() {
29
29
  }
30
30
  return "";
31
31
  }
32
- export function createCaller(endpointOrName, nameOrFlowId, flowId) {
33
- const name = typeof endpointOrName === "string" ? endpointOrName : nameOrFlowId;
34
- const resolvedFlowId = typeof endpointOrName === "string" ? nameOrFlowId : flowId;
35
- return async (input) => {
36
- const appId = resolvedFlowId ?? getEnv("ZITE_FLOW_ID", "VITE_ZITE_FLOW_ID") ?? "";
37
- const token = getUsageToken();
38
- const res = await fetch(getRunnerUrl() + "/public/" + appId + "/api/" + name, {
32
+ function buildFetchOptions(name, input, extra) {
33
+ const appId = getEnv("ZITE_FLOW_ID", "VITE_ZITE_FLOW_ID") ?? "";
34
+ const token = getUsageToken();
35
+ const ziteAuthToken = typeof localStorage !== "undefined"
36
+ ? localStorage.getItem("zite.auth.token")
37
+ : null;
38
+ return {
39
+ url: getRunnerUrl() + "/public/" + appId + "/api/" + name,
40
+ init: {
39
41
  method: "POST",
40
42
  headers: {
41
43
  ...(token ? { Authorization: `Bearer ${token}` } : {}),
@@ -45,8 +47,17 @@ export function createCaller(endpointOrName, nameOrFlowId, flowId) {
45
47
  inputs: input,
46
48
  mode: "preview",
47
49
  usageToken: token,
50
+ ...(ziteAuthToken ? { ziteAuthToken } : {}),
51
+ ...extra,
48
52
  }),
49
- });
53
+ },
54
+ };
55
+ }
56
+ export function createCaller(endpointOrName, nameOrFlowId, flowId) {
57
+ const name = typeof endpointOrName === "string" ? endpointOrName : nameOrFlowId;
58
+ return async (input) => {
59
+ const { url, init } = buildFetchOptions(name, input);
60
+ const res = await fetch(url, init);
50
61
  if (!res.ok) {
51
62
  const text = await res.text().catch(() => "");
52
63
  throw new Error(`API call failed (${res.status}): ${text}`);
@@ -54,3 +65,83 @@ export function createCaller(endpointOrName, nameOrFlowId, flowId) {
54
65
  return res.json();
55
66
  };
56
67
  }
68
+ export function createStreamingCaller(name) {
69
+ return (input) => {
70
+ let resultResolve;
71
+ let resultReject;
72
+ const resultPromise = new Promise((resolve, reject) => {
73
+ resultResolve = resolve;
74
+ resultReject = reject;
75
+ });
76
+ const { url, init } = buildFetchOptions(name, input, { stream: true });
77
+ const fetchPromise = fetch(url, init);
78
+ return {
79
+ async *[Symbol.asyncIterator]() {
80
+ try {
81
+ const response = await fetchPromise;
82
+ if (!response.ok) {
83
+ const errorData = await response.json().catch(() => ({}));
84
+ const error = new Error(errorData.message ||
85
+ `Error with endpoint ${name}: ${response.status}`);
86
+ resultReject(error);
87
+ throw error;
88
+ }
89
+ if (!response.body) {
90
+ const error = new Error("No response body for streaming endpoint");
91
+ resultReject(error);
92
+ throw error;
93
+ }
94
+ const reader = response.body
95
+ .pipeThrough(new TextDecoderStream())
96
+ .getReader();
97
+ let buffer = "";
98
+ while (true) {
99
+ const { value, done } = await reader.read();
100
+ if (done)
101
+ break;
102
+ buffer += value;
103
+ while (buffer.includes("\n\n")) {
104
+ const eventEnd = buffer.indexOf("\n\n");
105
+ const eventBlock = buffer.substring(0, eventEnd);
106
+ buffer = buffer.substring(eventEnd + 2);
107
+ const eventTypeMatch = eventBlock.match(/^event: (.+)$/m);
108
+ const dataMatch = eventBlock.match(/^data: (.+)$/m);
109
+ const eventType = eventTypeMatch?.[1];
110
+ const dataStr = dataMatch?.[1];
111
+ if (eventType === "data" && dataStr) {
112
+ try {
113
+ yield JSON.parse(dataStr);
114
+ }
115
+ catch {
116
+ yield dataStr;
117
+ }
118
+ }
119
+ else if (eventType === "result" && dataStr) {
120
+ try {
121
+ resultResolve(JSON.parse(dataStr));
122
+ }
123
+ catch {
124
+ resultResolve(dataStr);
125
+ }
126
+ }
127
+ else if (eventType === "error" && dataStr) {
128
+ try {
129
+ const errorData = JSON.parse(dataStr);
130
+ resultReject(new Error(errorData.message || "Streaming error"));
131
+ }
132
+ catch {
133
+ resultReject(new Error(dataStr || "Streaming error"));
134
+ }
135
+ }
136
+ }
137
+ }
138
+ }
139
+ catch (error) {
140
+ resultReject(error);
141
+ throw error;
142
+ }
143
+ },
144
+ result: resultPromise,
145
+ };
146
+ };
147
+ }
package/dist/esm/cli.js CHANGED
File without changes
@@ -40,7 +40,12 @@ function regenerateAppApiTs(appDir) {
40
40
  const apiDir = join("apps", appDir, "src", "api");
41
41
  if (!existsSync(apiDir))
42
42
  return;
43
- const endpointFiles = readdirSync(apiDir).filter((f) => f.endsWith(".ts") || f.endsWith(".js"));
43
+ const endpointFiles = readdirSync(apiDir)
44
+ .filter((f) => f.endsWith(".ts") || f.endsWith(".js"))
45
+ .map((f) => ({
46
+ fileName: f,
47
+ content: readFileSync(join(apiDir, f), "utf-8"),
48
+ }));
44
49
  const content = generateApiTs(endpointFiles);
45
50
  if (content) {
46
51
  const outDir = join("apps", appDir, ".zite");
@@ -0,0 +1,2 @@
1
+ export type SdkCall = (integrationId: string, className: string, methodName: string, params?: unknown) => Promise<unknown>;
2
+ export declare function getSdkCall(): SdkCall;
@@ -0,0 +1,7 @@
1
+ export function getSdkCall() {
2
+ const fn = globalThis.__wrapSdkCall;
3
+ if (!fn) {
4
+ throw new Error('Zite SDK runtime not initialized. Endpoints must run inside the Zite worker.');
5
+ }
6
+ return fn;
7
+ }
@@ -1,9 +1,12 @@
1
+ export interface RenderHtmlParams {
2
+ html: string;
3
+ filename?: string;
4
+ }
5
+ export interface RenderHtmlResult {
6
+ url: string;
7
+ filename: string;
8
+ }
1
9
  export declare class ZitePdf {
2
- generate(options: {
3
- html: string;
4
- [key: string]: unknown;
5
- }): Promise<{
6
- url: string;
7
- [key: string]: unknown;
8
- }>;
10
+ static renderHtml(params: RenderHtmlParams): Promise<RenderHtmlResult>;
9
11
  }
12
+ export declare const Pdf: typeof ZitePdf;
@@ -1,5 +1,8 @@
1
+ import { getSdkCall } from '../internal/sdkCall.js';
2
+ const PDF_LIB_INTEGRATION_ID = '__pdf__';
1
3
  export class ZitePdf {
2
- generate(options) {
3
- throw new Error('ZitePdf is only available in the Zite runtime.');
4
+ static renderHtml(params) {
5
+ return getSdkCall()(PDF_LIB_INTEGRATION_ID, 'ZitePdf', 'renderHtml', params);
4
6
  }
5
7
  }
8
+ export const Pdf = ZitePdf;
@@ -1,10 +1,4 @@
1
- function getSdkCall() {
2
- const fn = globalThis.__wrapSdkCall;
3
- if (!fn) {
4
- throw new Error("Zite SDK runtime not initialized. Endpoints must run inside the Zite worker.");
5
- }
6
- return fn;
7
- }
1
+ import { getSdkCall } from "../internal/sdkCall.js";
8
2
  const DB_INTEGRATION_ID = "databases";
9
3
  function getBaseId() {
10
4
  try {
@@ -1,16 +1,106 @@
1
- export declare class ZiteSchedule {
2
- static create(config: {
3
- name: string;
4
- cron: string;
5
- endpoint: string;
6
- input?: Record<string, unknown>;
1
+ type DayOfWeek = 'sun' | 'mon' | 'tue' | 'wed' | 'thu' | 'fri' | 'sat';
2
+ type ActiveWindow = {
3
+ hoursRange?: {
4
+ from: string;
5
+ to: string;
6
+ };
7
+ daysOfWeek?: DayOfWeek[];
8
+ };
9
+ export type ZiteSchedule = {
10
+ scheduleType: 'recurring';
11
+ schedule: {
12
+ frequency: 'minutely';
13
+ interval: number;
14
+ activeWindow?: ActiveWindow;
15
+ } | {
16
+ frequency: 'hourly';
17
+ interval: number;
18
+ minute?: number;
19
+ activeWindow?: ActiveWindow;
20
+ } | {
21
+ frequency: 'daily';
22
+ interval: number;
23
+ times: string[];
24
+ } | {
25
+ frequency: 'weekly';
26
+ interval: number;
27
+ daysOfWeek: DayOfWeek[];
28
+ times: string[];
29
+ } | {
30
+ frequency: 'monthly';
31
+ interval: 1;
32
+ monthlyDay: {
33
+ type: 'dayOfMonth';
34
+ day: number | 'last';
35
+ } | {
36
+ type: 'weekdayOccurrence';
37
+ weekday: DayOfWeek;
38
+ occurrence: 1 | 2 | 3 | 4 | 'last';
39
+ };
40
+ times: string[];
41
+ };
42
+ endPolicy?: {
43
+ type: 'never';
44
+ } | {
45
+ type: 'onDate';
46
+ endAt: string;
47
+ } | {
48
+ type: 'afterOccurrences';
49
+ occurrences: number;
50
+ };
51
+ overlapPolicy?: 'skip' | 'allow';
52
+ timezone: string;
53
+ paused?: boolean;
54
+ } | {
55
+ scheduleType: 'oneTime';
56
+ fireAt: string;
57
+ timezone: string;
58
+ paused?: boolean;
59
+ };
60
+ export type Schedule = ZiteSchedule;
61
+ export type RuntimeScheduleInfo = {
62
+ id: string;
63
+ cronJobId: string;
64
+ endpointId: string;
65
+ schedule: ZiteSchedule | null;
66
+ inputs?: Record<string, unknown>;
67
+ paused: boolean;
68
+ nextActionTimes: string[];
69
+ recentActions: {
70
+ scheduledAt: string;
71
+ takenAt: string;
72
+ workflowId: string;
73
+ firstExecutionRunId: string;
74
+ }[];
75
+ };
76
+ export declare class ZiteSchedules {
77
+ static add(args: {
78
+ endpointId: string;
79
+ schedule: ZiteSchedule;
80
+ inputs?: Record<string, unknown>;
7
81
  }): Promise<{
8
82
  id: string;
83
+ cronJobId: string;
9
84
  }>;
10
- static delete(id: string): Promise<void>;
11
- static list(): Promise<Array<{
85
+ static list(args?: {
86
+ endpointId?: string;
87
+ }): Promise<{
88
+ schedules: RuntimeScheduleInfo[];
89
+ }>;
90
+ static remove(args: {
12
91
  id: string;
13
- name: string;
14
- cron: string;
15
- }>>;
92
+ }): Promise<{
93
+ id: string;
94
+ deleted: true;
95
+ }>;
96
+ static update(args: {
97
+ id: string;
98
+ schedule?: ZiteSchedule;
99
+ inputs?: Record<string, unknown>;
100
+ }): Promise<{
101
+ id: string;
102
+ updated: true;
103
+ }>;
16
104
  }
105
+ export declare const Schedules: typeof ZiteSchedules;
106
+ export {};
@@ -1,11 +1,17 @@
1
- export class ZiteSchedule {
2
- static create(config) {
3
- throw new Error('ZiteSchedule is only available in the Zite runtime.');
1
+ import { getSdkCall } from '../internal/sdkCall.js';
2
+ const SCHEDULES_SDK_INTEGRATION_ID = '__schedules__';
3
+ export class ZiteSchedules {
4
+ static add(args) {
5
+ return getSdkCall()(SCHEDULES_SDK_INTEGRATION_ID, 'ZiteSchedules', 'add', args);
4
6
  }
5
- static delete(id) {
6
- throw new Error('ZiteSchedule is only available in the Zite runtime.');
7
+ static list(args) {
8
+ return getSdkCall()(SCHEDULES_SDK_INTEGRATION_ID, 'ZiteSchedules', 'list', args ?? {});
7
9
  }
8
- static list() {
9
- throw new Error('ZiteSchedule is only available in the Zite runtime.');
10
+ static remove(args) {
11
+ return getSdkCall()(SCHEDULES_SDK_INTEGRATION_ID, 'ZiteSchedules', 'remove', args);
12
+ }
13
+ static update(args) {
14
+ return getSdkCall()(SCHEDULES_SDK_INTEGRATION_ID, 'ZiteSchedules', 'update', args);
10
15
  }
11
16
  }
17
+ export const Schedules = ZiteSchedules;
@@ -9,9 +9,7 @@ const DB_ENVIRONMENTS = {
9
9
  local: "http://localhost:2507/api/v1",
10
10
  };
11
11
  const env = process.env.ZITE_ENV ?? "production";
12
- const BASE_URL = process.env.ZITE_DB_URL ??
13
- DB_ENVIRONMENTS[env] ??
14
- DB_ENVIRONMENTS.production;
12
+ const BASE_URL = process.env.ZITE_DB_URL ?? DB_ENVIRONMENTS[env] ?? DB_ENVIRONMENTS.production;
15
13
  const TOKEN = process.env.ZITE_DB_TOKEN ?? "";
16
14
  async function fetchDatabase(baseId) {
17
15
  const url = `${BASE_URL}/bases/${encodeURIComponent(baseId)}`;
@@ -70,7 +68,12 @@ export function regenerateApiTs() {
70
68
  const apiDir = join("src", "api");
71
69
  if (!existsSync(apiDir))
72
70
  return;
73
- const endpointFiles = readdirSync(apiDir).filter((f) => f.endsWith(".ts") || f.endsWith(".js"));
71
+ const endpointFiles = readdirSync(apiDir)
72
+ .filter((f) => f.endsWith(".ts") || f.endsWith(".js"))
73
+ .map((f) => ({
74
+ fileName: f,
75
+ content: readFileSync(join(apiDir, f), "utf-8"),
76
+ }));
74
77
  const apiTs = generateApiTs(endpointFiles);
75
78
  if (apiTs) {
76
79
  mkdirSync(".zite", { recursive: true });
@@ -30,7 +30,11 @@ export declare function generateSchema(database: Database, existingSchema?: Zite
30
30
  * Pure function — no external data needed beyond what's in the schema file.
31
31
  */
32
32
  export declare function generateDbTs(schema: ZiteSchema): string;
33
- export declare function generateApiTs(endpointFiles: string[]): string | null;
33
+ export type EndpointFileInfo = {
34
+ fileName: string;
35
+ content?: string;
36
+ };
37
+ export declare function generateApiTs(endpointFiles: (string | EndpointFileInfo)[]): string | null;
34
38
  export declare function generateUserTs(usersTableFields?: Array<{
35
39
  name: string;
36
40
  type: string;
@@ -1,3 +1,4 @@
1
+ import { parse } from "@babel/parser";
1
2
  const FIELD_TYPE_MAP = {
2
3
  single_line_text: "string",
3
4
  long_text: "string",
@@ -258,36 +259,80 @@ export function generateDbTs(schema) {
258
259
  lines.push("");
259
260
  return lines.join("\n");
260
261
  }
262
+ function detectStreamEnabled(source) {
263
+ try {
264
+ const ast = parse(source, {
265
+ sourceType: "module",
266
+ plugins: ["typescript"],
267
+ });
268
+ const defaultExport = ast.program.body.find((n) => n.type === "ExportDefaultDeclaration" &&
269
+ n.declaration.type === "CallExpression");
270
+ if (!defaultExport || defaultExport.type !== "ExportDefaultDeclaration")
271
+ return false;
272
+ const call = defaultExport.declaration;
273
+ if (call.type !== "CallExpression" || call.arguments.length === 0)
274
+ return false;
275
+ const arg = call.arguments[0];
276
+ if (arg.type !== "ObjectExpression")
277
+ return false;
278
+ const streamProp = arg.properties.find((p) => p.type === "ObjectProperty" &&
279
+ ((p.key.type === "Identifier" && p.key.name === "stream") ||
280
+ (p.key.type === "StringLiteral" && p.key.value === "stream")));
281
+ if (!streamProp || streamProp.type !== "ObjectProperty")
282
+ return false;
283
+ return (streamProp.value.type === "BooleanLiteral" &&
284
+ streamProp.value.value === true);
285
+ }
286
+ catch {
287
+ return false;
288
+ }
289
+ }
261
290
  export function generateApiTs(endpointFiles) {
262
291
  if (!endpointFiles || endpointFiles.length === 0)
263
292
  return null;
293
+ const endpoints = [];
294
+ for (const file of endpointFiles) {
295
+ const fileName = typeof file === "string" ? file : file.fileName;
296
+ const content = typeof file === "string" ? undefined : file.content;
297
+ const name = fileName.replace(/\.(ts|js)$/, "");
298
+ const camelName = toCamelCase(name);
299
+ const pascal = toPascalCase(camelName);
300
+ const stream = content ? detectStreamEnabled(content) : false;
301
+ endpoints.push({ camelName, pascal, stream });
302
+ }
303
+ const hasStreaming = endpoints.some((e) => e.stream);
264
304
  const lines = [
265
305
  "// Auto-generated by zitejs sync. Do not edit manually.",
266
306
  "",
267
- "import { createCaller } from 'zitejs/caller';",
307
+ hasStreaming
308
+ ? "import { createCaller, createStreamingCaller } from 'zitejs/caller';"
309
+ : "import { createCaller } from 'zitejs/caller';",
268
310
  "",
269
311
  ];
270
- const endpointNames = [];
271
- for (const file of endpointFiles) {
272
- const name = file.replace(/\.(ts|js)$/, "");
273
- const camelName = toCamelCase(name);
274
- const pascal = toPascalCase(camelName);
275
- lines.push(`import type { default as _${pascal}Ep } from '../src/api/${name}';`);
276
- endpointNames.push(camelName);
312
+ for (const { pascal, camelName } of endpoints) {
313
+ const name = camelName.replace(/([A-Z])/g, "-$1").toLowerCase();
314
+ const rawName = endpointFiles[endpoints.findIndex((e) => e.camelName === camelName)];
315
+ const fileName = typeof rawName === "string" ? rawName : rawName.fileName;
316
+ const baseName = fileName.replace(/\.(ts|js)$/, "");
317
+ lines.push(`import type { default as _${pascal}Ep } from '../src/api/${baseName}';`);
277
318
  }
278
319
  lines.push("");
279
- for (const name of endpointNames) {
280
- const pascal = toPascalCase(name);
320
+ for (const { camelName, pascal, stream } of endpoints) {
281
321
  lines.push(`type _${pascal}Cfg = typeof _${pascal}Ep;`);
282
322
  lines.push(`export type ${pascal}InputType = Parameters<_${pascal}Cfg['execute']>[0]['input'];`);
283
323
  lines.push(`export type ${pascal}OutputType = Awaited<ReturnType<_${pascal}Cfg['execute']>>;`);
284
- lines.push(`export const ${name} = createCaller<${pascal}InputType, ${pascal}OutputType>('${name}');`);
324
+ if (stream) {
325
+ lines.push(`export const ${camelName} = createStreamingCaller<${pascal}InputType, ${pascal}OutputType>('${camelName}');`);
326
+ }
327
+ else {
328
+ lines.push(`export const ${camelName} = createCaller<${pascal}InputType, ${pascal}OutputType>('${camelName}');`);
329
+ }
285
330
  lines.push("");
286
331
  }
287
332
  lines.push("");
288
333
  lines.push("export const api = {");
289
- for (const name of endpointNames) {
290
- lines.push(` ${name},`);
334
+ for (const { camelName } of endpoints) {
335
+ lines.push(` ${camelName},`);
291
336
  }
292
337
  lines.push("};");
293
338
  lines.push("");
@@ -1,5 +1,15 @@
1
+ export type UploadData = string | Blob | ArrayBuffer | File;
2
+ export declare class FileUploadError extends Error {
3
+ constructor(message: string);
4
+ }
5
+ export declare function uploadFile({ data, filename, }: {
6
+ data: UploadData;
7
+ filename: string;
8
+ }): Promise<{
9
+ fileUrl: string;
10
+ }>;
1
11
  export declare function useUpload(): {
2
- upload: (file: File) => Promise<{
12
+ upload: (file: File | Blob | ArrayBuffer | string, filename?: string) => Promise<{
3
13
  url: string;
4
14
  }>;
5
15
  isUploading: boolean;