create-orchid-orm 0.0.1

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/bin.js ADDED
@@ -0,0 +1,729 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+
4
+ var prompts = require('prompts');
5
+ var path = require('path');
6
+ var fs = require('fs/promises');
7
+ var https = require('https');
8
+
9
+ async function readFileSafe(path) {
10
+ try {
11
+ return await fs.readFile(path, "utf-8");
12
+ } catch (err) {
13
+ if (err.code === "ENOENT") {
14
+ return void 0;
15
+ }
16
+ throw err;
17
+ }
18
+ }
19
+ function makeFileTimeStamp(now) {
20
+ return [
21
+ now.getUTCFullYear(),
22
+ now.getUTCMonth() + 1,
23
+ now.getUTCDate(),
24
+ now.getUTCHours(),
25
+ now.getUTCMinutes(),
26
+ now.getUTCSeconds()
27
+ ].map((value) => value < 10 ? `0${value}` : value).join("");
28
+ }
29
+ function getLatestPackageVersion(name, kind) {
30
+ return new Promise((resolve, reject) => {
31
+ https.get(`https://registry.npmjs.org/${name}/latest`, (res) => {
32
+ let data = "";
33
+ res.on("data", (chunk) => data += chunk);
34
+ res.on(
35
+ "end",
36
+ () => resolve([name, { version: `^${JSON.parse(data).version}`, kind }])
37
+ );
38
+ }).on("error", reject);
39
+ });
40
+ }
41
+ function getPackageManagerName() {
42
+ const { npm_execpath } = process.env;
43
+ if (npm_execpath) {
44
+ const name = path.basename(npm_execpath);
45
+ if (/npm/.test(name)) {
46
+ return "npm";
47
+ }
48
+ if (/yarn/.test(name)) {
49
+ return "yarn";
50
+ }
51
+ if (/bun/.test(name)) {
52
+ return "bun";
53
+ }
54
+ }
55
+ return "pnpm";
56
+ }
57
+
58
+ var __defProp$1 = Object.defineProperty;
59
+ var __defProps = Object.defineProperties;
60
+ var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
61
+ var __getOwnPropSymbols$1 = Object.getOwnPropertySymbols;
62
+ var __hasOwnProp$1 = Object.prototype.hasOwnProperty;
63
+ var __propIsEnum$1 = Object.prototype.propertyIsEnumerable;
64
+ var __defNormalProp$1 = (obj, key, value) => key in obj ? __defProp$1(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
65
+ var __spreadValues$1 = (a, b) => {
66
+ for (var prop in b || (b = {}))
67
+ if (__hasOwnProp$1.call(b, prop))
68
+ __defNormalProp$1(a, prop, b[prop]);
69
+ if (__getOwnPropSymbols$1)
70
+ for (var prop of __getOwnPropSymbols$1(b)) {
71
+ if (__propIsEnum$1.call(b, prop))
72
+ __defNormalProp$1(a, prop, b[prop]);
73
+ }
74
+ return a;
75
+ };
76
+ var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
77
+ async function getConfig(logger = console) {
78
+ let cancelled = false;
79
+ logger.log("Welcome to Orchid ORM installer!");
80
+ const isBun = getPackageManagerName() === "bun";
81
+ const response = await prompts(
82
+ [
83
+ {
84
+ type: "text",
85
+ name: "path",
86
+ message: "Where to install Orchid ORM?",
87
+ initial: process.cwd()
88
+ },
89
+ ...isBun ? [] : [
90
+ {
91
+ type: "select",
92
+ name: "runner",
93
+ message: "Choose a tool for executing TS files",
94
+ choices: [
95
+ {
96
+ title: "tsx",
97
+ value: "tsx"
98
+ },
99
+ {
100
+ title: "vite-node",
101
+ value: "vite-node"
102
+ },
103
+ {
104
+ title: "ts-node",
105
+ value: "ts-node"
106
+ }
107
+ ]
108
+ }
109
+ ],
110
+ {
111
+ type: "select",
112
+ name: "timestamp",
113
+ message: "Return timestamps as:",
114
+ choices: [
115
+ {
116
+ title: "string (as returned from db)",
117
+ value: "string"
118
+ },
119
+ {
120
+ title: "number (epoch)",
121
+ value: "number"
122
+ },
123
+ {
124
+ title: "Date object",
125
+ value: "date"
126
+ }
127
+ ]
128
+ },
129
+ {
130
+ type: "confirm",
131
+ name: "testDatabase",
132
+ message: "Add a separate database for tests?"
133
+ },
134
+ {
135
+ type: "confirm",
136
+ name: "addSchemaToZod",
137
+ message: "Add Zod for validations?"
138
+ },
139
+ {
140
+ type: "confirm",
141
+ name: "addTestFactory",
142
+ message: "Add record factories for writing tests?"
143
+ },
144
+ {
145
+ type: "confirm",
146
+ name: "demoTables",
147
+ message: "Add demo tables?"
148
+ }
149
+ ],
150
+ {
151
+ onCancel() {
152
+ cancelled = true;
153
+ }
154
+ }
155
+ );
156
+ if (isBun)
157
+ response.runner = "bun";
158
+ if (cancelled)
159
+ return;
160
+ const path$1 = path.resolve(response.path);
161
+ const tsConfigPath = path.join(path$1, "tsconfig.json");
162
+ const hasTsConfig = await readFileSafe(tsConfigPath);
163
+ const dbDirPath = path.join(path$1, "src", "db");
164
+ return __spreadProps(__spreadValues$1({}, response), {
165
+ hasTsConfig: !!hasTsConfig,
166
+ path: path.resolve(response.path),
167
+ dbDirPath,
168
+ projectName: path.basename(path$1),
169
+ esm: response.runner !== "ts-node"
170
+ });
171
+ }
172
+
173
+ var __defProp = Object.defineProperty;
174
+ var __getOwnPropSymbols = Object.getOwnPropertySymbols;
175
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
176
+ var __propIsEnum = Object.prototype.propertyIsEnumerable;
177
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
178
+ var __spreadValues = (a, b) => {
179
+ for (var prop in b || (b = {}))
180
+ if (__hasOwnProp.call(b, prop))
181
+ __defNormalProp(a, prop, b[prop]);
182
+ if (__getOwnPropSymbols)
183
+ for (var prop of __getOwnPropSymbols(b)) {
184
+ if (__propIsEnum.call(b, prop))
185
+ __defNormalProp(a, prop, b[prop]);
186
+ }
187
+ return a;
188
+ };
189
+ async function setupPackageJSON(config) {
190
+ const pairs = await Promise.all([
191
+ getLatestPackageVersion("dotenv", "dependencies"),
192
+ getLatestPackageVersion("orchid-orm", "dependencies"),
193
+ getLatestPackageVersion("pqb", "dependencies"),
194
+ config.addSchemaToZod && getLatestPackageVersion("orchid-orm-schema-to-zod", "dependencies"),
195
+ getLatestPackageVersion("rake-db", "devDependencies"),
196
+ config.addTestFactory && getLatestPackageVersion("orchid-orm-test-factory", "devDependencies"),
197
+ getLatestPackageVersion("@types/node", "devDependencies"),
198
+ getLatestPackageVersion("typescript", "devDependencies"),
199
+ config.runner === "vite-node" && getLatestPackageVersion("vite", "devDependencies"),
200
+ config.runner !== "bun" && getLatestPackageVersion(config.runner, "devDependencies"),
201
+ config.runner === "vite-node" && getLatestPackageVersion(
202
+ "rollup-plugin-node-externals",
203
+ "devDependencies"
204
+ ),
205
+ config.runner === "tsx" && getLatestPackageVersion("esbuild", "devDependencies"),
206
+ config.runner === "tsx" && getLatestPackageVersion("rimraf", "devDependencies")
207
+ ]);
208
+ const deps = {};
209
+ const devDeps = {};
210
+ for (const item of pairs) {
211
+ if (!item)
212
+ continue;
213
+ const [key, { version, kind }] = item;
214
+ (kind === "dependencies" ? deps : devDeps)[key] = version;
215
+ }
216
+ const packageJsonPath = path.join(config.path, "package.json");
217
+ const content = await readFileSafe(packageJsonPath);
218
+ let json = content ? JSON.parse(content) : {
219
+ name: config.projectName
220
+ };
221
+ if (config.esm)
222
+ json = __spreadValues({ name: json.name, type: "module" }, json);
223
+ if (!json.scripts)
224
+ json.scripts = {};
225
+ let db;
226
+ let build;
227
+ let compiledDb;
228
+ if (config.runner === "vite-node") {
229
+ db = "vite-node src/db/dbScript.ts --";
230
+ build = "vite build --config vite.migrations.ts";
231
+ compiledDb = "node dist/db/dbScript.js";
232
+ } else if (config.runner === "tsx") {
233
+ db = "NODE_ENV=development tsx src/db/dbScript.ts";
234
+ build = "rimraf dist/db && node esbuild.migrations.js";
235
+ compiledDb = "NODE_ENV=production node dist/db/dbScript.js";
236
+ } else {
237
+ db = `${config.runner} src/db/dbScript.ts`;
238
+ }
239
+ json.scripts.db = db;
240
+ if (build) {
241
+ json.scripts["build:migrations"] = build;
242
+ }
243
+ if (compiledDb) {
244
+ json.scripts["db:compiled"] = compiledDb;
245
+ }
246
+ if (!json.dependencies)
247
+ json.dependencies = {};
248
+ for (const key in deps) {
249
+ json.dependencies[key] = deps[key];
250
+ }
251
+ if (!json.devDependencies)
252
+ json.devDependencies = {};
253
+ for (const key in devDeps) {
254
+ json.devDependencies[key] = devDeps[key];
255
+ }
256
+ await fs.writeFile(packageJsonPath, JSON.stringify(json, null, " ") + "\n");
257
+ }
258
+
259
+ async function setupTSConfig(config) {
260
+ if (config.hasTsConfig)
261
+ return;
262
+ const module = config.runner === "ts-node" ? "commonjs" : "esnext";
263
+ const moduleResolution = config.runner === "ts-node" ? "" : `
264
+ "moduleResolution": "bundler",`;
265
+ const types = config.runner === "vite-node" ? `["vite/client"]` : void 0;
266
+ const tsConfigPath = path.join(config.path, "tsconfig.json");
267
+ await fs.writeFile(
268
+ tsConfigPath,
269
+ `{
270
+ "compilerOptions": {
271
+ "target": "es2017",
272
+ "module": "${module}",${moduleResolution}
273
+ "esModuleInterop": true,
274
+ "forceConsistentCasingInFileNames": true,
275
+ "strict": true,
276
+ "skipLibCheck": true${types ? `,
277
+ "types": ${types}` : ""}
278
+ }
279
+ }
280
+ `
281
+ );
282
+ }
283
+
284
+ async function setupEnv(config) {
285
+ const envPath = path.join(config.path, ".env");
286
+ let content = (await readFileSafe(envPath) || "").trim();
287
+ let changed = false;
288
+ const user = process.platform === "darwin" ? process.env.USER : "postgres";
289
+ if (!content.match(/^DATABASE_URL=/m)) {
290
+ content += `
291
+ DATABASE_URL=postgres://${user}:@localhost:5432/dbname?ssl=false`;
292
+ changed = true;
293
+ }
294
+ if (config.testDatabase && !content.match(/^DATABASE_TEST_URL=/m)) {
295
+ content += `
296
+ DATABASE_TEST_URL=postgres://${user}:@localhost:5432/dbname-test?ssl=false`;
297
+ changed = true;
298
+ }
299
+ if (changed) {
300
+ await fs.writeFile(envPath, `${content.trim()}
301
+ `);
302
+ }
303
+ }
304
+
305
+ async function setupGitIgnore(config) {
306
+ const gitignorePath = path.join(config.path, ".gitignore");
307
+ let content = (await readFileSafe(gitignorePath) || "").trim();
308
+ let changed = false;
309
+ if (!content.match(/^node_modules\b/m)) {
310
+ content += `
311
+ node_modules`;
312
+ changed = true;
313
+ }
314
+ if (!content.match(/^.env\b/m)) {
315
+ content += `
316
+ .env.?*
317
+ !.env.example`;
318
+ changed = true;
319
+ }
320
+ if (changed) {
321
+ await fs.writeFile(gitignorePath, `${content.trim()}
322
+ `);
323
+ }
324
+ }
325
+
326
+ async function setupBaseTable(config) {
327
+ const filePath = path.join(config.dbDirPath, "baseTable.ts");
328
+ let content = `import { createBaseTable } from 'orchid-orm';${config.addSchemaToZod ? `
329
+ import { zodSchemaProvider } from 'orchid-orm-schema-to-zod';` : ""}
330
+
331
+ export const BaseTable = createBaseTable({
332
+ // Customize column types for all tables.
333
+ columnTypes: (t) => ({
334
+ ...t,${config.addSchemaToZod ? `
335
+ // Set min and max validations for all text columns,
336
+ // it is only checked when validating with Zod schemas derived from the table.
337
+ text: (min = 0, max = Infinity) => t.text(min, max),` : ""}`;
338
+ const { timestamp } = config;
339
+ if (timestamp && timestamp !== "string") {
340
+ content += `
341
+ // Parse timestamps to ${timestamp === "number" ? "number" : "Date object"}.
342
+ timestamp: <P extends number>(precision?: P) =>
343
+ t.timestamp<P>(precision).${timestamp === "date" ? "asDate" : "asNumber"}(),`;
344
+ }
345
+ content += `
346
+ }),${config.addSchemaToZod ? `
347
+ schemaProvider: zodSchemaProvider,` : ""}
348
+ });
349
+ `;
350
+ await fs.writeFile(filePath, content);
351
+ }
352
+
353
+ async function setupDemoTables(config) {
354
+ if (!config.demoTables)
355
+ return;
356
+ const tablesDir = path.join(config.dbDirPath, "tables");
357
+ await fs.mkdir(tablesDir, { recursive: true });
358
+ await fs.writeFile(
359
+ path.join(tablesDir, "post.table.ts"),
360
+ `import { Selectable, Updateable, Insertable, Queryable } from 'orchid-orm';
361
+ import { BaseTable } from '../baseTable';
362
+ import { CommentTable } from './comment.table';
363
+
364
+ // Post type returned from database.
365
+ export type Post = Selectable<PostTable>;
366
+ // Post type for insertion.
367
+ export type PostNew = Insertable<PostTable>;
368
+ // Post type for updates.
369
+ export type PostUpdate = Updateable<PostTable>;
370
+ // Post type used by query methods such as \`where\`.
371
+ export type PostForQuery = Queryable<PostTable>;
372
+
373
+ export class PostTable extends BaseTable {
374
+ readonly table = 'post';
375
+ columns = this.setColumns((t) => ({
376
+ id: t.identity().primaryKey(),
377
+ title: t.text(3, 100).unique(),
378
+ text: t.text(20, 10000),
379
+ ...t.timestamps(),
380
+ }));
381
+
382
+ relations = {
383
+ comments: this.hasMany(() => CommentTable, {
384
+ primaryKey: 'id',
385
+ foreignKey: 'postId',
386
+ }),
387
+ };
388
+ }
389
+ `
390
+ );
391
+ await fs.writeFile(
392
+ path.join(tablesDir, "comment.table.ts"),
393
+ `import { Selectable, Updateable, Insertable, Queryable } from 'orchid-orm';
394
+ import { BaseTable } from '../baseTable';
395
+ import { PostTable } from './post.table';
396
+
397
+ // Comment type returned from database.
398
+ export type Comment = Selectable<CommentTable>;
399
+ // Comment type for insertion.
400
+ export type CommentNew = Insertable<CommentTable>;
401
+ // Comment type for updates.
402
+ export type CommentUpdate = Updateable<CommentTable>;
403
+ // Comment type used by query methods such as \`where\`.
404
+ export type CommentForQuery = Queryable<CommentTable>;
405
+
406
+ export class CommentTable extends BaseTable {
407
+ readonly table = 'comment';
408
+ columns = this.setColumns((t) => ({
409
+ id: t.identity().primaryKey(),
410
+ postId: t
411
+ .integer()
412
+ .foreignKey(() => PostTable, 'id')
413
+ .index(),
414
+ text: t.text(5, 1000),
415
+ ...t.timestamps(),
416
+ }));
417
+
418
+ relations = {
419
+ post: this.belongsTo(() => PostTable, {
420
+ primaryKey: 'id',
421
+ foreignKey: 'postId',
422
+ }),
423
+ };
424
+ }
425
+ `
426
+ );
427
+ }
428
+
429
+ async function setupConfig(config) {
430
+ const configPath = path.join(config.dbDirPath, "config.ts");
431
+ let content = `import 'dotenv/config';
432
+
433
+ const database = {
434
+ databaseURL: process.env.DATABASE_URL,
435
+ };
436
+ if (!database.databaseURL) throw new Error('DATABASE_URL is missing in .env');`;
437
+ if (config.testDatabase) {
438
+ content += `
439
+
440
+ const testDatabase = {
441
+ databaseURL: process.env.DATABASE_TEST_URL,
442
+ };
443
+
444
+ const allDatabases = [database];
445
+
446
+ if (testDatabase.databaseURL) {
447
+ allDatabases.push(testDatabase);
448
+ }`;
449
+ }
450
+ content += `
451
+
452
+ export const config = {`;
453
+ if (config.testDatabase) {
454
+ content += `
455
+ allDatabases,`;
456
+ }
457
+ if (config.testDatabase) {
458
+ content += `
459
+ database: process.env.NODE_ENV === 'test' ? testDatabase : database,`;
460
+ } else {
461
+ content += `
462
+ database,`;
463
+ }
464
+ content += `
465
+ };
466
+ `;
467
+ await fs.writeFile(configPath, content);
468
+ }
469
+
470
+ async function setupMainDb(config) {
471
+ let imports = "";
472
+ let tables = "";
473
+ if (config.demoTables) {
474
+ imports += `
475
+ import { PostTable } from './tables/post.table';
476
+ import { CommentTable } from './tables/comment.table';`;
477
+ tables += `
478
+ post: PostTable,
479
+ comment: CommentTable,`;
480
+ }
481
+ const dbPath = path.join(config.dbDirPath, "db.ts");
482
+ await fs.writeFile(
483
+ dbPath,
484
+ `import { orchidORM } from 'orchid-orm';
485
+ import { config } from './config';${imports}
486
+
487
+ export const db = orchidORM(config.database, {${tables}
488
+ });
489
+ `
490
+ );
491
+ }
492
+
493
+ async function setupMigrationScript(config) {
494
+ const filePath = path.join(config.dbDirPath, "dbScript.ts");
495
+ const migrations = config.runner === "vite-node" ? "migrations: import.meta.glob('./migrations/*.ts')" : "migrationsPath: './migrations'";
496
+ const useCodeUpdater = config.runner === "vite-node" ? "import.meta.env.DEV" : `process.env.NODE_ENV === 'development'`;
497
+ await fs.writeFile(
498
+ filePath,
499
+ `import { rakeDb } from 'rake-db';
500
+ import { appCodeUpdater } from 'orchid-orm/codegen';
501
+ import { config } from './config';
502
+ import { BaseTable } from './baseTable';
503
+
504
+ export const change = rakeDb(${config.testDatabase ? "config.allDatabases" : "config.database"}, {
505
+ baseTable: BaseTable,
506
+ ${migrations},
507
+ appCodeUpdater: appCodeUpdater({
508
+ tablePath: (tableName) => \`./tables/\${tableName}.table.ts\`,
509
+ ormPath: './db.ts',
510
+ }),
511
+ // set to false to disable code updater
512
+ useCodeUpdater: ${useCodeUpdater},
513
+ commands: {
514
+ async seed() {
515
+ const { seed } = await import('./seed');
516
+ await seed();
517
+ },
518
+ },
519
+ import: (path) => import(path),
520
+ });
521
+ `
522
+ );
523
+ }
524
+
525
+ async function createDemoMigrations(config) {
526
+ const migrationsPath = path.join(config.dbDirPath, "migrations");
527
+ await fs.mkdir(migrationsPath, { recursive: true });
528
+ if (!config.demoTables)
529
+ return;
530
+ const now = /* @__PURE__ */ new Date();
531
+ const postPath = path.join(
532
+ migrationsPath,
533
+ `${makeFileTimeStamp(now)}_createPost.ts`
534
+ );
535
+ await fs.writeFile(
536
+ postPath,
537
+ `import { change } from '../dbScript';
538
+
539
+ change(async (db) => {
540
+ await db.createTable('post', (t) => ({
541
+ id: t.identity().primaryKey(),
542
+ title: t.text().unique(),
543
+ text: t.text(),
544
+ ...t.timestamps(),
545
+ }));
546
+ });
547
+ `
548
+ );
549
+ now.setTime(now.getTime() + 1e3);
550
+ const commentPath = path.join(
551
+ migrationsPath,
552
+ `${makeFileTimeStamp(now)}_createComment.ts`
553
+ );
554
+ await fs.writeFile(
555
+ commentPath,
556
+ `import { change } from '../dbScript';
557
+
558
+ change(async (db) => {
559
+ await db.createTable('comment', (t) => ({
560
+ id: t.identity().primaryKey(),
561
+ postId: t.integer().foreignKey('post', 'id').index(),
562
+ text: t.text(),
563
+ ...t.timestamps(),
564
+ }));
565
+ });
566
+ `
567
+ );
568
+ }
569
+
570
+ async function createDemoSeed(config) {
571
+ const filePath = path.join(config.dbDirPath, "seed.ts");
572
+ let content;
573
+ if (config.demoTables) {
574
+ content = `await db.post.findBy({ title: 'Sample post' }).orCreate({
575
+ title: 'Post',
576
+ text: 'This is a text for a sample post. It contains words, spaces, and punctuation.',
577
+ comments: {
578
+ create: [
579
+ {
580
+ text: 'Nice post!',
581
+ },
582
+ {
583
+ text: \`Too long, didn't read\`,
584
+ },
585
+ ],
586
+ },
587
+ });`;
588
+ } else {
589
+ content = `// create records here`;
590
+ }
591
+ await fs.writeFile(
592
+ filePath,
593
+ `import { db } from './db';
594
+
595
+ export const seed = async () => {
596
+ ${content}
597
+
598
+ await db.$close();
599
+ };
600
+ `
601
+ );
602
+ }
603
+
604
+ async function setupRunner(config) {
605
+ if (config.runner === "vite-node") {
606
+ await fs.writeFile(
607
+ path.join(config.path, "vite.migrations.ts"),
608
+ `import { resolve } from 'path'
609
+ import { defineConfig, PluginOption } from 'vite'
610
+ import { nodeExternals } from 'rollup-plugin-node-externals';
611
+
612
+ export default defineConfig({
613
+ plugins: [
614
+ {
615
+ ...nodeExternals(),
616
+ name: 'node-externals',
617
+ enforce: 'pre',
618
+ apply: 'build',
619
+ } as PluginOption
620
+ ],
621
+ build: {
622
+ outDir: resolve(__dirname, 'dist', 'db'),
623
+ lib: {
624
+ entry: resolve(__dirname, 'src/db/dbScript.ts'),
625
+ formats: ['es'],
626
+ fileName: 'dbScript',
627
+ },
628
+ rollupOptions: {
629
+ external: ["pqb", "rake-db"],
630
+ },
631
+ },
632
+ })
633
+ `
634
+ );
635
+ } else if (config.runner === "tsx") {
636
+ await fs.writeFile(
637
+ path.join(config.path, "esbuild.migrations.js"),
638
+ `import { build } from "esbuild";
639
+
640
+ await Promise.all([
641
+ build({
642
+ entryPoints: ["src/db/dbScript.ts"],
643
+ bundle: true,
644
+ platform: "node",
645
+ format: "esm",
646
+ outdir: "dist/db",
647
+ banner: {
648
+ js: \`
649
+ import __path from 'node:path';
650
+ import { fileURLToPath as __fileURLToPath } from 'node:url';
651
+ import { createRequire as __createRequire } from 'module';
652
+ const require = __createRequire(import.meta.url);
653
+ const __filename = __fileURLToPath(import.meta.url);
654
+ const __dirname = __path.dirname(__filename);
655
+ \`,
656
+ },
657
+ }),
658
+ build({
659
+ entryPoints: ["src/db/migrations/*.ts"],
660
+ bundle: true,
661
+ platform: "node",
662
+ format: "esm",
663
+ outdir: "dist/db/migrations",
664
+ external: ['../dbScript'],
665
+ plugins: [{
666
+ name: 'add-js-suffix',
667
+ setup(build) {
668
+ build.onResolve({ filter: /.*/ }, (args) => {
669
+ if (args.importer) {
670
+ return { path: args.path + '.js', external: true }
671
+ }
672
+ })
673
+ },
674
+ }],
675
+ }),
676
+ ]);
677
+ `
678
+ );
679
+ }
680
+ }
681
+
682
+ async function init(config) {
683
+ await fs.mkdir(config.dbDirPath, { recursive: true });
684
+ for (const key in initSteps) {
685
+ await initSteps[key](config);
686
+ }
687
+ }
688
+ const initSteps = {
689
+ setupPackageJSON,
690
+ setupTSConfig,
691
+ setupEnv,
692
+ setupGitIgnore,
693
+ setupBaseTable,
694
+ setupDemoTables,
695
+ setupConfig,
696
+ setupMainDb,
697
+ setupMigrationScript,
698
+ createDemoMigrations,
699
+ createDemoSeed,
700
+ setupRunner
701
+ };
702
+
703
+ function greetAfterInstall(config, logger = console) {
704
+ const relativePath = path.relative(process.cwd(), config.path);
705
+ const manager = getPackageManagerName();
706
+ const run = manager === "npm" ? `npm run` : manager;
707
+ logger.log(`
708
+ Thank you for trying Orchid ORM!
709
+
710
+ To finish setup,${relativePath ? ` cd to the project and` : ""} install dependencies:
711
+ ${relativePath ? `
712
+ > cd ${relativePath}` : ""}
713
+ > ${manager} i
714
+
715
+ Enter the correct database credentials to the .env file,
716
+ then create the database:
717
+
718
+ > ${run} db create
719
+
720
+ And run the migrations:
721
+
722
+ > ${run} db migrate
723
+ `);
724
+ }
725
+
726
+ getConfig().then(
727
+ (config) => config && init(config).then(() => greetAfterInstall(config))
728
+ );
729
+ //# sourceMappingURL=bin.js.map