cloesce 0.0.3

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 ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,23 @@
1
+ # cloesce
2
+
3
+ View the [internal documentation](https://cloesce.pages.dev)
4
+
5
+ ### Unit Tests
6
+
7
+ - `src/extractor/ts` run `npm test`
8
+ - `src/generator` run `cargo test`
9
+
10
+ ### Integration Tests
11
+
12
+ - To run the regression tests: `cargo run --bin test regression`
13
+ - To run the pass fail extractor tests: `cargo run --bin test run-fail`
14
+
15
+ Optionally, pass `--check` if new snapshots should not be created.
16
+
17
+ ### E2E
18
+
19
+ - `tests/e2e` run `npm test`
20
+
21
+ ### Code Formatting
22
+
23
+ - `cargo fmt`, `cargo clippy`, `npm run format:fix`
package/dist/cli.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=cli.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cli.d.ts","sourceRoot":"","sources":["../src/cli.ts"],"names":[],"mappings":""}
package/dist/cli.js ADDED
@@ -0,0 +1,337 @@
1
+ #!/usr/bin/env node
2
+ import { WASI } from "node:wasi";
3
+ import fs from "node:fs";
4
+ import path from "node:path";
5
+ import { fileURLToPath } from "node:url";
6
+ import { command, run, subcommands, flag, option, optional, string, } from "cmd-ts";
7
+ import { Project } from "ts-morph";
8
+ import { CidlExtractor } from "./extract.js";
9
+ import { ExtractorError, ExtractorErrorCode, getErrorInfo } from "./common.js";
10
+ const __filename = fileURLToPath(import.meta.url);
11
+ const __dirname = path.dirname(__filename);
12
+ const WASM_PATH = path.join(__dirname, "..", "dist", "cli.wasm");
13
+ function loadCloesceConfig(root, debug = false) {
14
+ const configPath = path.join(root, "cloesce-config.json");
15
+ if (fs.existsSync(configPath)) {
16
+ try {
17
+ const config = JSON.parse(fs.readFileSync(configPath, "utf8"));
18
+ if (debug)
19
+ console.log(`Loaded config from ${configPath}`);
20
+ return config;
21
+ }
22
+ catch (err) {
23
+ console.warn(`Failed to parse cloesce-config.json: ${err}`);
24
+ }
25
+ }
26
+ return {};
27
+ }
28
+ function readPackageJsonProjectName(cwd) {
29
+ const pkgPath = path.join(cwd, "package.json");
30
+ let projectName = path.basename(cwd);
31
+ if (fs.existsSync(pkgPath)) {
32
+ const pkg = JSON.parse(fs.readFileSync(pkgPath, "utf8"));
33
+ projectName = pkg.name ?? projectName;
34
+ }
35
+ return projectName;
36
+ }
37
+ function findCloesceProject(root, searchPaths, project) {
38
+ for (const searchPath of searchPaths) {
39
+ let fullPath;
40
+ if (path.isAbsolute(searchPath) || searchPath.startsWith(root)) {
41
+ fullPath = path.normalize(searchPath);
42
+ }
43
+ else {
44
+ fullPath = path.resolve(root, searchPath);
45
+ }
46
+ if (!fs.existsSync(fullPath)) {
47
+ console.warn(`Warning: Path "${searchPath}" does not exist`);
48
+ continue;
49
+ }
50
+ const stats = fs.statSync(fullPath);
51
+ if (stats.isFile() && /\.cloesce\.ts$/i.test(fullPath)) {
52
+ project.addSourceFileAtPath(fullPath);
53
+ }
54
+ else if (stats.isDirectory()) {
55
+ walkDirectory(fullPath, project);
56
+ }
57
+ }
58
+ function walkDirectory(dir, project) {
59
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
60
+ const fullPath = path.join(dir, entry.name);
61
+ if (entry.isDirectory() && !entry.name.startsWith(".")) {
62
+ walkDirectory(fullPath, project);
63
+ }
64
+ else if (entry.isFile() && /\.cloesce\.ts$/i.test(entry.name)) {
65
+ project.addSourceFileAtPath(fullPath);
66
+ }
67
+ }
68
+ }
69
+ }
70
+ function formatErr(e) {
71
+ const { description, suggestion } = getErrorInfo(e.code);
72
+ const contextLine = e.context ? `Context: ${e.context}\n` : "";
73
+ const snippetLine = e.snippet ? `${e.snippet}\n\n` : "";
74
+ return `==== CLOESCE ERROR ====
75
+ Error [${ExtractorErrorCode[e.code]}]: ${description}
76
+ Phase: TypeScript IDL Extraction
77
+ ${contextLine}${snippetLine}Suggested fix: ${suggestion}`;
78
+ }
79
+ async function runExtractor(opts) {
80
+ const root = process.cwd();
81
+ const projectRoot = process.cwd();
82
+ const config = loadCloesceConfig(projectRoot, opts.debug);
83
+ const searchPaths = opts.inp ? [opts.inp] : (config.paths ?? [root]);
84
+ const outputDir = config.outputDir ?? ".generated";
85
+ const outPath = opts.out ?? path.join(outputDir, "cidl.json");
86
+ const truncate = opts.truncateSourcePaths ?? config.truncateSourcePaths ?? false;
87
+ const cloesceProjectName = opts.projectName ??
88
+ config.projectName ??
89
+ readPackageJsonProjectName(projectRoot);
90
+ const project = new Project({
91
+ compilerOptions: {
92
+ strictNullChecks: true,
93
+ },
94
+ });
95
+ findCloesceProject(root, searchPaths, project);
96
+ const fileCount = project.getSourceFiles().length;
97
+ if (fileCount === 0) {
98
+ new ExtractorError(ExtractorErrorCode.MissingFile);
99
+ }
100
+ if (opts.debug)
101
+ console.log(`Found ${fileCount} .cloesce.ts files`);
102
+ try {
103
+ const extractor = new CidlExtractor(cloesceProjectName, "v0.0.3");
104
+ const result = extractor.extract(project);
105
+ if (!result.ok) {
106
+ console.error(formatErr(result.value));
107
+ process.exit(1);
108
+ }
109
+ let ast = result.value;
110
+ if (truncate) {
111
+ ast.wrangler_env.source_path =
112
+ "./" + path.basename(ast.wrangler_env.source_path);
113
+ for (const model of Object.values(ast.models)) {
114
+ model.source_path =
115
+ "./" + path.basename(model.source_path);
116
+ }
117
+ if (ast.poos) {
118
+ for (const poo of Object.values(ast.poos)) {
119
+ poo.source_path =
120
+ "./" + path.basename(poo.source_path);
121
+ }
122
+ }
123
+ }
124
+ const json = JSON.stringify(ast, null, 4);
125
+ fs.mkdirSync(path.dirname(outPath), { recursive: true });
126
+ fs.writeFileSync(outPath, json);
127
+ console.log(`CIDL generated successfully at ${outPath}`);
128
+ return { outPath, projectName: cloesceProjectName };
129
+ }
130
+ catch (err) {
131
+ console.error("Critical uncaught error. Submit a ticket to https://github.com/bens-schreiber/cloesce: ", err?.message ?? err);
132
+ process.exit(1);
133
+ }
134
+ }
135
+ async function runWasmCommand(config) {
136
+ const root = process.cwd();
137
+ const outputDir = ".generated";
138
+ const wranglerPath = path.join(root, outputDir, "wrangler.toml");
139
+ if (!fs.existsSync(wranglerPath)) {
140
+ fs.mkdirSync(path.dirname(wranglerPath), { recursive: true });
141
+ fs.writeFileSync(wranglerPath, "");
142
+ }
143
+ const wasi = new WASI({
144
+ version: "preview1",
145
+ args: [path.basename(WASM_PATH), ...config.args],
146
+ env: { ...process.env, ...config.env },
147
+ preopens: { "/": root },
148
+ });
149
+ const bytes = fs.readFileSync(WASM_PATH);
150
+ const mod = await WebAssembly.compile(bytes);
151
+ const instance = await WebAssembly.instantiate(mod, {
152
+ wasi_snapshot_preview1: wasi.wasiImport,
153
+ });
154
+ try {
155
+ wasi.start(instance);
156
+ }
157
+ catch (err) {
158
+ console.error(`WASM execution failed for ${config.name}:`, err);
159
+ }
160
+ }
161
+ const runCmd = command({
162
+ name: "run",
163
+ description: "Extract CIDL and run all code generators",
164
+ args: {
165
+ debug: flag({
166
+ long: "debug",
167
+ short: "d",
168
+ description: "Show debug output",
169
+ }),
170
+ },
171
+ handler: async (args) => {
172
+ const config = loadCloesceConfig(process.cwd(), args.debug);
173
+ if (!config.workersUrl || !config.clientUrl) {
174
+ console.error("Error: workersUrl and clientUrl must be defined in cloesce-config.json");
175
+ process.exit(1);
176
+ }
177
+ await runExtractor({ debug: args.debug });
178
+ // in case the user wants to dump their generated files somewhere else
179
+ // we should allow them to define that directory in the config
180
+ const outputDir = config.outputDir ?? ".generated";
181
+ const allConfig = {
182
+ name: "all",
183
+ wasmFile: "cli.wasm",
184
+ args: [
185
+ "generate",
186
+ "all",
187
+ path.join(outputDir, "cidl.json"),
188
+ path.join(outputDir, "wrangler.toml"),
189
+ path.join(outputDir, "migrations.sql"),
190
+ path.join(outputDir, "workers.ts"),
191
+ path.join(outputDir, "client.ts"),
192
+ config.clientUrl,
193
+ config.workersUrl,
194
+ ],
195
+ };
196
+ await runWasmCommand(allConfig);
197
+ },
198
+ });
199
+ // In case the user wants to run individual steps we should probably allow them
200
+ const wranglerCmd = command({
201
+ name: "wrangler",
202
+ description: "Generate wrangler.toml configuration",
203
+ args: {},
204
+ handler: async () => {
205
+ const config = loadCloesceConfig(process.cwd());
206
+ const outputDir = config.outputDir ?? ".generated";
207
+ await runWasmCommand({
208
+ name: "wrangler",
209
+ wasmFile: "cli.wasm",
210
+ args: ["generate", "wrangler", path.join(outputDir, "wrangler.toml")],
211
+ });
212
+ },
213
+ });
214
+ const d1Cmd = command({
215
+ name: "d1",
216
+ description: "Generate database schema",
217
+ args: {},
218
+ handler: async () => {
219
+ const config = loadCloesceConfig(process.cwd());
220
+ const outputDir = config.outputDir ?? ".generated";
221
+ await runWasmCommand({
222
+ name: "d1",
223
+ wasmFile: "cli.wasm",
224
+ args: [
225
+ "generate",
226
+ "d1",
227
+ path.join(outputDir, "cidl.json"),
228
+ path.join(outputDir, "migrations.sql"),
229
+ ],
230
+ });
231
+ },
232
+ });
233
+ const workersCmd = command({
234
+ name: "workers",
235
+ description: "Generate workers TypeScript",
236
+ args: {},
237
+ handler: async () => {
238
+ const config = loadCloesceConfig(process.cwd());
239
+ const outputDir = config.outputDir ?? ".generated";
240
+ if (!config.workersUrl) {
241
+ console.error("Error: workersUrl must be defined in cloesce-config.json");
242
+ process.exit(1);
243
+ }
244
+ await runWasmCommand({
245
+ name: "workers",
246
+ wasmFile: "cli.wasm",
247
+ args: [
248
+ "generate",
249
+ "workers",
250
+ path.join(outputDir, "cidl.json"),
251
+ path.join(outputDir, "workers.ts"),
252
+ path.join(outputDir, "wrangler.toml"),
253
+ config.workersUrl,
254
+ ],
255
+ });
256
+ },
257
+ });
258
+ const clientCmd = command({
259
+ name: "client",
260
+ description: "Generate client TypeScript",
261
+ args: {},
262
+ handler: async () => {
263
+ const config = loadCloesceConfig(process.cwd());
264
+ const outputDir = config.outputDir ?? ".generated";
265
+ if (!config.clientUrl) {
266
+ console.error("Error: clientUrl must be defined in cloesce-config.json");
267
+ process.exit(1);
268
+ }
269
+ await runWasmCommand({
270
+ name: "client",
271
+ wasmFile: "cli.wasm",
272
+ args: [
273
+ "generate",
274
+ "client",
275
+ path.join(outputDir, "cidl.json"),
276
+ path.join(outputDir, "client.ts"),
277
+ config.clientUrl,
278
+ ],
279
+ });
280
+ },
281
+ });
282
+ const extractCmd = command({
283
+ name: "extract",
284
+ description: "Extract models and write cidl.json only",
285
+ args: {
286
+ projectName: option({
287
+ long: "project-name",
288
+ type: optional(string),
289
+ description: "Project name",
290
+ }),
291
+ out: option({
292
+ long: "out",
293
+ short: "o",
294
+ type: optional(string),
295
+ description: "Output path (default: .generated/cidl.json)",
296
+ }),
297
+ inp: option({
298
+ long: "in",
299
+ short: "i",
300
+ type: optional(string),
301
+ description: "Input file or directory",
302
+ }),
303
+ location: option({
304
+ long: "location",
305
+ short: "l",
306
+ type: optional(string),
307
+ description: "Project directory (default: cwd)",
308
+ }),
309
+ truncateSourcePaths: flag({
310
+ long: "truncateSourcePaths",
311
+ description: "Sets all source paths to just their file name",
312
+ }),
313
+ debug: flag({
314
+ long: "debug",
315
+ short: "d",
316
+ description: "Show debug output",
317
+ }),
318
+ },
319
+ handler: async (args) => {
320
+ await runExtractor({ ...args });
321
+ },
322
+ });
323
+ const router = subcommands({
324
+ name: "cloesce",
325
+ cmds: {
326
+ run: runCmd,
327
+ extract: extractCmd,
328
+ wrangler: wranglerCmd,
329
+ d1: d1Cmd,
330
+ workers: workersCmd,
331
+ client: clientCmd,
332
+ },
333
+ });
334
+ run(router, process.argv.slice(2)).catch((err) => {
335
+ console.error(err);
336
+ process.exit(1);
337
+ });
package/dist/cli.wasm ADDED
Binary file
@@ -0,0 +1,108 @@
1
+ import { D1Database } from "@cloudflare/workers-types/experimental/index.js";
2
+ import { HttpResult, Either, ModelMethod, CloesceAst, Model } from "./common.js";
3
+ import { IncludeTree } from "./index.js";
4
+ /**
5
+ * A map of model names to their respective constructor.
6
+ *
7
+ * The value accepted into the `cloesce` function is generated by the Cloesce compiler, and
8
+ * is guaranteed to contain all model definitions.
9
+ */
10
+ type ModelConstructorRegistry = Record<string, new () => UserDefinedModel>;
11
+ /**
12
+ * A dependency injection container, mapping an object type name to an instance of that object.
13
+ *
14
+ * The value accepted into the `cloesce` function is generated by the Cloesce compiler, and is
15
+ * guaranteed to contain all injected model method parameters.
16
+ */
17
+ type InstanceRegistry = Map<string, any>;
18
+ /**
19
+ * Users will create Cloesce models, which have metadata for them in the ast.
20
+ * For TypeScript's purposes, these models can be anything. We can assume any
21
+ * `UserDefinedModel` has been verified by the compiler.
22
+ */
23
+ type UserDefinedModel = any;
24
+ type InstantiatedUserDefinedModel = object;
25
+ /**
26
+ * Given a request, this represents a map of each body / url param name to
27
+ * its actual value. Unknown, as the a request can be anything.
28
+ */
29
+ type RequestParamMap = Record<string, unknown>;
30
+ /**
31
+ * Meta information on the wrangler env and db bindings
32
+ */
33
+ interface MetaWranglerEnv {
34
+ envName: string;
35
+ dbName: string;
36
+ }
37
+ /**
38
+ * Creates model instances given a properly formatted SQL record
39
+ * (either a foreign-key-less model or derived from a Cloesce generated view)
40
+ * @param ctor The type of the model
41
+ * @param records SQL records
42
+ * @param includeTree The include tree to use when parsing the records
43
+ * @returns
44
+ */
45
+ export declare function modelsFromSql<T>(ctor: new () => T, records: Record<string, any>[], includeTree: IncludeTree<T> | null): T[];
46
+ /**
47
+ * Cloesce entry point. Given a request, undergoes routing, validating,
48
+ * hydrating, and method dispatch.
49
+ * @param ast The CIDL AST
50
+ * @param constructorRegistry A mapping of user defined class names to their respective constructor
51
+ * @param instanceRegistry A mapping of a dependency class name to its instantiated object.
52
+ * @param request An incoming request to the workers server
53
+ * @param api_route The url's path to the api, e.g. api/v1/fooapi/
54
+ * @param envMeta Meta information on the wrangler env and D1 databases
55
+ * @returns A Response with an `HttpResult` JSON body.
56
+ */
57
+ export declare function cloesce(request: Request, ast: CloesceAst, constructorRegistry: ModelConstructorRegistry, instanceRegistry: InstanceRegistry, envMeta: MetaWranglerEnv, api_route: string): Promise<Response>;
58
+ /**
59
+ * Matches a request to a method on a model.
60
+ * @param api_route The route from the domain to the actual API, ie https://foo.com/route/to/api => route/to/api/
61
+ * @returns 404 or a `MatchedRoute`
62
+ */
63
+ declare function matchRoute(request: Request, ast: CloesceAst, api_route: string): Either<HttpResult, MatchedRoute>;
64
+ /**
65
+ * Validates the request's body/search params against a ModelMethod
66
+ * @returns 400 or a `RequestParamMap` consisting of each parameters name mapped to its value, and
67
+ * a data source
68
+ */
69
+ declare function validateRequest(request: Request, ast: CloesceAst, model: Model, method: ModelMethod, id: string | null): Promise<Either<HttpResult, [RequestParamMap, string | null]>>;
70
+ /**
71
+ * Queries D1 for a particular model's ID, then transforms the SQL column output into
72
+ * an instance of a model using the provided include tree and metadata as a guide.
73
+ * @returns 404 if no record was found for the provided ID
74
+ * @returns 500 if the D1 database is not synced with Cloesce and yields an error
75
+ * @returns The instantiated model on success
76
+ */
77
+ declare function hydrateModel(ast: CloesceAst, constructorRegistry: ModelConstructorRegistry, d1: D1Database, model: Model, id: string, dataSource: string | null): Promise<Either<HttpResult, object>>;
78
+ /**
79
+ * Calls a method on a model given a list of parameters.
80
+ * @returns 500 on an uncaught client error, 200 with a result body on success
81
+ */
82
+ declare function methodDispatch(instance: InstantiatedUserDefinedModel, instanceRegistry: InstanceRegistry, envMeta: MetaWranglerEnv, method: ModelMethod, params: Record<string, unknown>): Promise<HttpResult<unknown>>;
83
+ /**
84
+ * Actual implementation of sql to model mapping.
85
+ *
86
+ * TODO: If we don't want to write this in every language, would it be possible to create a
87
+ * single WASM binary for this method?
88
+ *
89
+ * @throws generic errors if the metadata is missing some value
90
+ */
91
+ declare function _modelsFromSql(modelName: string, ast: CloesceAst, constructorRegistry: ModelConstructorRegistry, records: Record<string, any>[], includeTree: Record<string, UserDefinedModel> | null): InstantiatedUserDefinedModel[];
92
+ interface MatchedRoute {
93
+ model: Model;
94
+ method: ModelMethod;
95
+ id: string | null;
96
+ }
97
+ /**
98
+ * Each individual state of the `cloesce` function for testing purposes.
99
+ */
100
+ export declare const _cloesceInternal: {
101
+ matchRoute: typeof matchRoute;
102
+ validateRequest: typeof validateRequest;
103
+ hydrateModel: typeof hydrateModel;
104
+ methodDispatch: typeof methodDispatch;
105
+ _modelsFromSql: typeof _modelsFromSql;
106
+ };
107
+ export {};
108
+ //# sourceMappingURL=cloesce.d.ts.map