@apisurf/ngn-core 0.2.2

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/core.d.ts ADDED
@@ -0,0 +1,292 @@
1
+ import { FsNodeFileDescriptor } from '@apisurf/ngn-os';
2
+ import { Client, InArgs, ResultSet, InStatement } from '@apisurf/ngn-persistence';
3
+ export { initDbFileIfNotExists } from '@apisurf/ngn-persistence';
4
+
5
+ type CompilerOptions = {
6
+ /** Minify output */
7
+ minify?: boolean;
8
+ /** Generate sourcemaps */
9
+ sourcemap?: boolean;
10
+ /** Suppress output */
11
+ silent?: boolean;
12
+ /** Patterns to NOT externalize (will be bundled) */
13
+ noExternal?: (string | RegExp)[];
14
+ };
15
+ declare class Compiler {
16
+ private options;
17
+ private externalizePlugin;
18
+ constructor(options?: CompilerOptions);
19
+ /**
20
+ * Creates an esbuild plugin that externalizes all bare package imports
21
+ * except for those matching the noExternal patterns.
22
+ * This approach automatically handles all dependencies (including transitive ones)
23
+ * without needing to maintain a list or read package.json.
24
+ *
25
+ * NOTE: There are esbuild config options that can be used to externalize dependencies
26
+ * but they are not as flexible as this plugin. This plugin is more flexible and
27
+ * can be used to externalize dependencies that are not in the package.json(alternative approach).
28
+ * Previous implementations used tsup which did this by default or used a list of
29
+ * dependencies to externalize. This approach externalizes everything dynamically.
30
+ * Problematic dependencies were: playwright, playwright-core, chromium-bidi, etc.
31
+ */
32
+ private createExternalizePlugin;
33
+ /**
34
+ * Compile entry files to in-memory strings (no disk I/O)
35
+ * @param entry - Array of input paths
36
+ * @returns Map of input file path to compiled code string
37
+ */
38
+ compile(entry: string[]): Promise<{
39
+ compiled: Map<string, string>;
40
+ }>;
41
+ /**
42
+ * Compile source code from memory (no disk I/O required)
43
+ * @param sourceCode - The source code string to compile
44
+ * @param virtualPath - A virtual file path for the source (used for resolve directory and loader detection)
45
+ * @returns The compiled code string
46
+ */
47
+ compileFromSource(sourceCode: string, virtualPath: string): Promise<string>;
48
+ }
49
+
50
+ /**
51
+ * Executes IIFE-compiled code in an isolated VM context.
52
+ * The code should be compiled with esbuild's iife format and globalName: "__exports".
53
+ *
54
+ * @param code - The IIFE code string to execute
55
+ * @returns The module's exports object
56
+ */
57
+ declare function executeEsm(code: string): Promise<Record<string, unknown>>;
58
+
59
+ /**
60
+ * A database migration
61
+ */
62
+ interface Migration {
63
+ /** Unique identifier (use datetime format e.g., "2024-01-13-001") */
64
+ id: string;
65
+ /** SQL statement(s) to execute */
66
+ up: string;
67
+ }
68
+ /**
69
+ * Options for opening an additional database next to the task file
70
+ */
71
+ interface InitDBOptions {
72
+ /**
73
+ * Database file, relative to the folder the task file lives in
74
+ * (e.g. "cache.db" or "data/cache.db"). A leading "file:" is accepted.
75
+ * Paths that reach outside the task folder are rejected.
76
+ */
77
+ file: string;
78
+ /** Optional migrations to run */
79
+ migrations?: Migration[];
80
+ }
81
+ /**
82
+ * A database instance opened by initDB
83
+ */
84
+ interface DBInstance {
85
+ /** Raw libsql client for advanced usage */
86
+ client: Client;
87
+ /** Absolute path of the database file */
88
+ path: string;
89
+ /** Execute a single SQL statement */
90
+ execute: (sql: string, args?: InArgs) => Promise<ResultSet>;
91
+ /** Execute multiple SQL statements in a batch */
92
+ batch: (statements: InStatement[]) => Promise<ResultSet[]>;
93
+ /** Close the database connection */
94
+ close: () => void;
95
+ }
96
+ /**
97
+ * SQLite API injected into every task as `ctx.sqlite`.
98
+ *
99
+ * Reads and writes are confined to the folder the task file lives in: the
100
+ * default database sits next to the task, and `initDB` only opens paths that
101
+ * resolve inside that folder. A task cannot reach a sibling folder's data by
102
+ * walking up with "..", and cannot open a database by absolute path.
103
+ */
104
+ interface TaskSqlite {
105
+ /** Raw libsql client for the task's own database */
106
+ readonly client: Client;
107
+ /** Absolute path of the task's own database file */
108
+ readonly path: string;
109
+ /** Execute a single SQL statement against the task's own database */
110
+ execute: (sql: string, args?: InArgs) => Promise<ResultSet>;
111
+ /** Execute multiple SQL statements against the task's own database */
112
+ batch: (statements: InStatement[]) => Promise<ResultSet[]>;
113
+ /** Open another database in the task's folder, with optional migrations */
114
+ initDB: (options: InitDBOptions) => Promise<DBInstance>;
115
+ /** Delete a database file in the task's folder */
116
+ destroyDB: (file: string) => Promise<void>;
117
+ }
118
+ /**
119
+ * Close every database opened by a task. Called by the CLI on shutdown.
120
+ */
121
+ declare function closeTaskDatabases(): void;
122
+
123
+ type LiveSourceParams = {
124
+ livePath: `live:${string}`;
125
+ code: string;
126
+ };
127
+ type DbSourceParams = {
128
+ compiledCode: string;
129
+ descriptor: FsNodeFileDescriptor;
130
+ tasksRootDir: string;
131
+ };
132
+ type EntryParams = LiveSourceParams | DbSourceParams;
133
+ /**
134
+ * The single argument every task export receives.
135
+ */
136
+ interface TaskContext {
137
+ meta: {
138
+ fileTaskId: number;
139
+ fileTaskVersionId: number;
140
+ file: FsNodeFileDescriptor;
141
+ tasksRootDir: string;
142
+ };
143
+ env: Record<string, string> | null;
144
+ kv: {
145
+ set(key: string, value: string): Promise<void>;
146
+ get(key: string): Promise<string | null>;
147
+ delete(key: string): Promise<void>;
148
+ };
149
+ log: {
150
+ info(value: string): Promise<void>;
151
+ error(value: string): Promise<void>;
152
+ warning(value: string): Promise<void>;
153
+ };
154
+ timing: {
155
+ start(label: string): () => Promise<void>;
156
+ };
157
+ /**
158
+ * SQLite scoped to the folder this task file lives in. Always present — no
159
+ * configuration required.
160
+ */
161
+ sqlite: TaskSqlite;
162
+ }
163
+
164
+ interface CompiledTaskCallbacks {
165
+ onTaskLoadComplete?: ({ paths, md5Hash, compiledCode, }: {
166
+ paths: {
167
+ compiled: string;
168
+ source: string;
169
+ relativeEntry: string;
170
+ relativeParent: string;
171
+ };
172
+ md5Hash: string;
173
+ compiledCode: string;
174
+ }) => Promise<{
175
+ fileTaskId: number;
176
+ fileTaskVersionId: number;
177
+ }>;
178
+ onTaskExecutionStart?: () => Promise<void>;
179
+ onTaskCodeLoaded?: () => Promise<void>;
180
+ onTaskExportsLoaded?: () => Promise<void>;
181
+ }
182
+ interface TaskRuntimeCallbacks {
183
+ onNotFound?: (meta: {
184
+ path: string;
185
+ }) => Promise<void>;
186
+ onSkip?: (meta: {
187
+ path: string;
188
+ }) => Promise<void>;
189
+ onStart?: (meta: {
190
+ path: string;
191
+ }) => Promise<void>;
192
+ onSuccess?: (meta: {
193
+ path: string;
194
+ }) => Promise<void>;
195
+ onFailure?: (meta: {
196
+ path: string;
197
+ }) => Promise<void>;
198
+ }
199
+ type BuildCompiledTaskConfigFn = ({ sourcePath, compiledPath, }: {
200
+ sourcePath: string;
201
+ compiledPath: string;
202
+ }) => {
203
+ compiledPath: string;
204
+ sourcePath: string;
205
+ taskCallbacks: CompiledTaskCallbacks;
206
+ runtimeCallbacks: TaskRuntimeCallbacks;
207
+ env: TaskContext["env"];
208
+ kv: TaskContext["kv"];
209
+ log: TaskContext["log"];
210
+ timing: TaskContext["timing"];
211
+ sqlite: TaskContext["sqlite"];
212
+ };
213
+
214
+ declare class Task {
215
+ private taskCallbacks;
216
+ private runtimeCallbacks;
217
+ private env;
218
+ private kv;
219
+ private log;
220
+ private timing;
221
+ private sqlite;
222
+ private meta;
223
+ private entry;
224
+ private entryExports;
225
+ constructor({ entryParams, buildConfigFn, }: {
226
+ entryParams: EntryParams;
227
+ buildConfigFn: BuildCompiledTaskConfigFn;
228
+ });
229
+ get sourcePath(): string;
230
+ get compiledPath(): string;
231
+ /**
232
+ * Unique identifier for the task - the relative entry path
233
+ */
234
+ get taskPath(): string;
235
+ get codeHash(): string | null;
236
+ get timingPattern(): string | undefined;
237
+ hasTaskExport(): boolean;
238
+ hasTimingExport(): boolean;
239
+ loadEntry(): Promise<void>;
240
+ execute(): Promise<void>;
241
+ }
242
+
243
+ declare class TaskLibrary {
244
+ private tasks;
245
+ constructor();
246
+ add(taskOrTasks: Task | Array<Task>): void;
247
+ remove(taskPath: string | Array<Task>): void;
248
+ /**
249
+ * Add tasks from in-memory compiled code (stored in DB)
250
+ */
251
+ addFromCompiledCode({ compiledCode, descriptors, tasksRootDir, buildConfigFn, }: {
252
+ compiledCode: Map<string, string>;
253
+ descriptors: Record<string, FsNodeFileDescriptor>;
254
+ tasksRootDir: string;
255
+ buildConfigFn: BuildCompiledTaskConfigFn;
256
+ }): void;
257
+ execute(taskPath: string): Promise<void>;
258
+ getTasks(): Task[];
259
+ }
260
+
261
+ type Options$1 = {
262
+ taskLibrary: TaskLibrary;
263
+ };
264
+ declare class TaskLibraryScheduler {
265
+ private taskLibrary;
266
+ private scheduledTasks;
267
+ constructor(options: Options$1);
268
+ start(): Promise<void>;
269
+ stop(): Promise<void>;
270
+ scheduleTask(task: Task): Promise<void>;
271
+ unscheduleTask(task: Task): void;
272
+ isCronPatternValid(cronPattern: string): boolean;
273
+ }
274
+
275
+ type Options = {
276
+ task: Task;
277
+ };
278
+ declare class TaskOnceRunner {
279
+ private task;
280
+ constructor(options: Options);
281
+ run(): Promise<void>;
282
+ }
283
+
284
+ declare function setupDbClient(dbPath: string): Promise<Client>;
285
+ declare function getDbClient(): Client;
286
+
287
+ declare function createControlsGenerator({ dbClient, env, }: {
288
+ dbClient: Client;
289
+ env: TaskContext["env"];
290
+ }): BuildCompiledTaskConfigFn;
291
+
292
+ export { Compiler, type DBInstance, type InitDBOptions, type Migration, Task, type TaskContext, TaskLibrary, TaskLibraryScheduler, TaskOnceRunner, type TaskSqlite, closeTaskDatabases, createControlsGenerator, executeEsm, getDbClient, setupDbClient };