@cedarjs/cli-data-migrate 9.0.0-canary.1784 → 9.0.0-canary.3124

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 CHANGED
@@ -1,4 +1,4 @@
1
1
  #!/usr/bin/env node
2
- "use strict";var L=Object.create;var w=Object.defineProperty;var N=Object.getOwnPropertyDescriptor;var R=Object.getOwnPropertyNames;var U=Object.getPrototypeOf,V=Object.prototype.hasOwnProperty;var v=(t,r)=>()=>(t&&(r=t(t=0)),r);var W=(t,r,e,i)=>{if(r&&typeof r=="object"||typeof r=="function")for(let a of R(r))!V.call(t,a)&&a!==e&&w(t,a,{get:()=>r[a],enumerable:!(i=N(r,a))||i.enumerable});return t};var l=(t,r,e)=>(e=t!=null?L(U(t)):{},W(r||!t||!t.__esModule?w(e,"default",{value:t,enumerable:!0}):e,t));var o,c,A=v(()=>{"use strict";o=l(require("ansis")),c={error:o.default.bold.red,warning:o.default.hex("#ffa500"),highlight:o.default.hex("#ffa500"),success:o.default.green,info:o.default.gray,bold:o.default.bold,underline:o.default.underline,note:o.default.blue,tip:o.default.green,important:o.default.magenta,caution:o.default.red,link:o.default.hex("#e8e8e8")}});async function P({importDbClientFromDist:t,distPath:r}){let e,i=!1;if(t){if(!g.default.existsSync(r)){console.warn(`Can't find api dist at ${r}. You may need to build first: yarn cedar build api`),process.exitCode=1;return}let p=m.default.join(r,"lib"),d=m.default.join(p,"db.js");if(!g.default.existsSync(d)){console.error(`Can't find db.js at ${d}. CedarJS expects the db.js file to be in the ${p} directory`),process.exitCode=1;return}e=(await import(d)).db}else(0,y.registerApiSideBabelHook)(),i=!0,e=require(m.default.join((0,u.getPaths)().api.lib,"db")).db;let a=await B(e);if(!a.length){console.info(c.success(`
3
- ${G}
4
- `)),process.exitCode=0;return}let s={run:0,skipped:0,error:0},n=a.map(p=>{let d=m.default.basename(p.path,".js");return{title:d,skip(){return s.error>0?(s.skipped++,!0):!1},async task(){i||(0,y.registerApiSideBabelHook)();try{let{startedAt:h,finishedAt:I}=await q(e,p.path);s.run++,await J(e,{version:p.version,name:d,startedAt:h,finishedAt:I})}catch(h){s.error++,console.error(c.error(`Error in data migration: ${h.message}`))}}}}),f=new j.Listr(n,{renderer:"verbose"});try{await f.run(),await e.$disconnect(),console.log(),E(s),console.log(),s.error&&(process.exitCode=1)}catch{process.exitCode=1,await e.$disconnect(),console.log(),E(s),console.log()}}async function B(t){let r=await(0,u.getDataMigrationsPath)((0,u.getPaths)().api.prismaConfig);if(!g.default.existsSync(r))return[];let e=g.default.readdirSync(r).filter(n=>["js",".ts"].some(f=>n.endsWith(f))).map(n=>{let[f]=n.split("-");return{version:f,path:m.default.join(r,n)}}),a=(await t.rW_DataMigration.findMany({orderBy:{version:"asc"}})).map(n=>n.version.toString());return e.filter(({version:n})=>!a.includes(n)).sort(H)}function H(t,r){let e=parseInt(t.version),i=parseInt(r.version);return e>i?1:e<i?-1:0}async function q(t,r){let e=require(r),i=new Date;return await e.default({db:t}),{startedAt:i,finishedAt:new Date}}async function J(t,{version:r,name:e,startedAt:i,finishedAt:a}){await t.rW_DataMigration.create({data:{version:r,name:e,startedAt:i,finishedAt:a}})}function E(t){t.run&&console.info(c.success(`${t.run} data migration(s) completed successfully.`)),t.error&&console.error(c.error(`${t.error} data migration(s) exited with errors.`)),t.skipped&&console.warn(c.warning(`${t.skipped} data migration(s) skipped due to previous error.`))}var g,m,j,y,u,G,S=v(()=>{"use strict";g=l(require("node:fs")),m=l(require("node:path")),j=require("listr2"),y=require("@cedarjs/babel-config"),u=require("@cedarjs/project-config");A();G="No pending data migrations run, already up-to-date."});var D=l(require("path")),O=require("dotenv-defaults"),$=require("yargs/helpers"),_=l(require("yargs/yargs")),M=require("@cedarjs/project-config");var x=require("termi-link"),b=require("@cedarjs/project-config");var C="Run any outstanding Data Migrations against the database";function k(t){return t.option("import-db-client-from-dist",{type:"boolean",alias:["db-from-dist"],description:"Import the db client from dist",default:!1}).option("dist-path",{type:"string",alias:"d",description:"Path to the api dist directory",default:(0,b.getPaths)().api.dist}).epilogue(`Also see the ${(0,x.terminalLink)("CedarJS CLI Reference","https://cedarjs.com/docs/cli-commands#datamigrate-up")}`)}S();process.env.REDWOOD_ENV_FILES_LOADED||((0,O.config)({path:D.default.join((0,M.getPaths)().base,".env"),defaults:D.default.join((0,M.getPaths)().base,".env.defaults"),multiline:!0}),process.env.REDWOOD_ENV_FILES_LOADED="true");(0,_.default)((0,$.hideBin)(process.argv)).scriptName("data-migrate").command("$0",C,k,P).parse();
2
+ var I=(t,n,r)=>()=>{if(r)throw r[0];try{return t&&(n=t(t=0)),n}catch(e){throw r=[e],e}};import d from"node:fs";import m from"node:path";import{Listr as k}from"listr2";import{createServer as _,isRunnableDevEnvironment as L}from"vite";import{colors as f}from"@cedarjs/cli-helpers/colors";import{getPaths as l,getDataMigrationsPath as N,resolveFile as O,importStatementPath as v}from"@cedarjs/project-config";function V(t){if(d.existsSync(t)&&d.statSync(t).isFile())return t;let n=/\.jsx?$/.test(t)?t.replace(/\.jsx?$/,""):t;for(let r of[".ts",".tsx",".js",".jsx"])if(d.existsSync(n+r))return n+r;if(d.existsSync(t)&&d.statSync(t).isDirectory())for(let r of["index",m.basename(t)])for(let e of[".ts",".tsx",".js",".jsx"]){let o=m.join(t,r+e);if(d.existsSync(o))return o}return t}async function x({importDbClientFromDist:t,distPath:n}){let r,e=null,o;async function g(){e||(o||(o=await import("@cedarjs/vite")),e=await _({mode:"production",optimizeDeps:{noDiscovery:!0,include:void 0},server:{hmr:!1,watch:null},environments:{nodeRunnerEnv:{}},resolve:{alias:[{find:/^api\//,replacement:l().api.base+"/"},{find:/^src\//,replacement:"src/",customResolver:(a,p,u)=>{let y=v(l().api.base);if(p?.startsWith(y)){let D=v(l().api.src),b=a.replace("src",D);return{id:V(b)}}return null}}]},plugins:[o.cedarCjsCompatPlugin(),o.cedarjsResolveCedarStyleImportsPlugin(),o.cedarImportDirPlugin(),o.cedarAutoImportsPlugin()]}));let i=e.environments.nodeRunnerEnv;if(!i||!L(i))throw new Error("Vite environment is not runnable.");return i.runner}if(t){if(!d.existsSync(n)){console.warn(`Can't find api dist at ${n}. You may need to build first: yarn cedar build api`),process.exitCode=1;return}let i=m.join(n,"lib"),a=m.join(i,"db.js");if(!d.existsSync(a)){console.error(`Can't find db.js at ${a}. CedarJS expects the db.js file to be in the ${i} directory`),process.exitCode=1;return}r=(await import(a)).db}else{let i=O(m.join(l().api.lib,"db"));if(!i){console.error(`Can't find your db file in ${l().api.lib}`),process.exitCode=1;return}try{r=(await(await g()).import(i)).db}catch(a){throw await e?.close(),a}}let s=await B(r);if(!s.length){console.info(f.success(`
3
+ ${W}
4
+ `)),process.exitCode=0,await e?.close();return}let c={run:0,skipped:0,error:0},C=s.map(i=>{let a=m.basename(i.path,".js");return{title:a,skip(){return c.error>0?(c.skipped++,!0):!1},async task(){try{let{startedAt:p,finishedAt:u}=await A(r,i.path);c.run++,await F(r,{version:i.version,name:a,startedAt:p,finishedAt:u})}catch(p){c.error++;let u=p instanceof Error?p.message:String(p);console.error(f.error(`Error in data migration: ${u}`))}}}}),E=new k(C,{renderer:"verbose"});try{await E.run(),await r.$disconnect(),console.log(),w(c),console.log(),c.error&&(process.exitCode=1)}catch{process.exitCode=1,await r.$disconnect(),console.log(),w(c),console.log()}finally{e&&await e.close()}async function A(i,a){let y=(await(await g()).import(a)).default,D=new Date;return await y({db:i}),{startedAt:D,finishedAt:new Date}}}async function B(t){let n=await N(l().api.prismaConfig);if(!d.existsSync(n))return[];let r=d.readdirSync(n).filter(s=>["js",".ts"].some(c=>s.endsWith(c))).map(s=>{let[c]=s.split("-");return{version:c,path:m.join(n,s)}}),o=(await t.rW_DataMigration.findMany({orderBy:{version:"asc"}})).map(s=>s.version.toString());return r.filter(({version:s})=>!o.includes(s)).sort(U)}function U(t,n){let r=parseInt(t.version),e=parseInt(n.version);return r>e?1:r<e?-1:0}async function F(t,{version:n,name:r,startedAt:e,finishedAt:o}){await t.rW_DataMigration.create({data:{version:n,name:r,startedAt:e,finishedAt:o}})}function w(t){t.run&&console.info(f.success(`${t.run} data migration(s) completed successfully.`)),t.error&&console.error(f.error(`${t.error} data migration(s) exited with errors.`)),t.skipped&&console.warn(f.warning(`${t.skipped} data migration(s) skipped due to previous error.`))}var W,j=I(()=>{"use strict";W="No pending data migrations run, already up-to-date."});import S from"path";import{config as G}from"dotenv-defaults";import{hideBin as J}from"yargs/helpers";import T from"yargs/yargs";import{getPaths as P}from"@cedarjs/project-config";import{terminalLink as $}from"termi-link";import{getPaths as R}from"@cedarjs/project-config";var h="Run any outstanding Data Migrations against the database";function M(t){return t.option("import-db-client-from-dist",{type:"boolean",alias:["db-from-dist"],description:"Import the db client from dist",default:!1}).option("dist-path",{type:"string",alias:"d",description:"Path to the api dist directory",default:R().api.dist}).epilogue(`Also see the ${$("CedarJS CLI Reference","https://cedarjs.com/docs/cli-commands#datamigrate-up")}`)}j();process.env.CEDAR_ENV_FILES_LOADED||(G({path:S.join(P().base,".env"),defaults:S.join(P().base,".env.defaults"),multiline:!0}),process.env.CEDAR_ENV_FILES_LOADED="true");T(J(process.argv)).scriptName("data-migrate").command("$0",h,M,x).parse();
@@ -1,45 +1,9 @@
1
- "use strict";
2
- var __create = Object.create;
3
- var __defProp = Object.defineProperty;
4
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
- var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getProtoOf = Object.getPrototypeOf;
7
- var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __export = (target, all) => {
9
- for (var name in all)
10
- __defProp(target, name, { get: all[name], enumerable: true });
11
- };
12
- var __copyProps = (to, from, except, desc) => {
13
- if (from && typeof from === "object" || typeof from === "function") {
14
- for (let key of __getOwnPropNames(from))
15
- if (!__hasOwnProp.call(to, key) && key !== except)
16
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
- }
18
- return to;
19
- };
20
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
- // If the importer is in node compatibility mode or this is not an ESM
22
- // file that has been converted to a CommonJS file using a Babel-
23
- // compatible transform (i.e. "__esModule" has not been set), then set
24
- // "default" to the CommonJS "module.exports" for node compatibility.
25
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
- mod
27
- ));
28
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
- var install_exports = {};
30
- __export(install_exports, {
31
- builder: () => builder,
32
- command: () => command,
33
- description: () => description,
34
- handler: () => handler
35
- });
36
- module.exports = __toCommonJS(install_exports);
37
- var import_termi_link = require("termi-link");
1
+ import { terminalLink } from "termi-link";
38
2
  const command = "install";
39
3
  const description = "Add the RW_DataMigration model to your schema";
40
4
  function builder(yargs) {
41
5
  return yargs.epilogue(
42
- `Also see the ${(0, import_termi_link.terminalLink)(
6
+ `Also see the ${terminalLink(
43
7
  "CedarJS CLI Reference",
44
8
  "https://cedarjs.com/docs/cli-commands#datamigrate-install"
45
9
  )}`
@@ -49,10 +13,9 @@ async function handler() {
49
13
  const { handler: dataMigrateInstallHandler } = await import("./installHandler.js");
50
14
  await dataMigrateInstallHandler();
51
15
  }
52
- // Annotate the CommonJS export names for ESM import in node:
53
- 0 && (module.exports = {
16
+ export {
54
17
  builder,
55
18
  command,
56
19
  description,
57
20
  handler
58
- });
21
+ };
@@ -1 +1 @@
1
- {"version":3,"file":"installHandler.d.ts","sourceRoot":"","sources":["../../src/commands/installHandler.ts"],"names":[],"mappings":"AAcA,wBAAsB,OAAO,kBAmD5B;AAED,eAAO,MAAM,uBAAuB,8HAMlC,CAAA;AAEF,eAAO,MAAM,8BAA8B,8EACkC,CAAA;AAE7E,eAAO,MAAM,KAAK,QAMN,CAAA"}
1
+ {"version":3,"file":"installHandler.d.ts","sourceRoot":"","sources":["../../src/commands/installHandler.ts"],"names":[],"mappings":"AAaA,wBAAsB,OAAO,kBAmD5B;AAED,eAAO,MAAM,uBAAuB,8HAMlC,CAAA;AAEF,eAAO,MAAM,8BAA8B,8EACkC,CAAA;AAE7E,eAAO,MAAM,KAAK,QAMN,CAAA"}
@@ -1,64 +1,32 @@
1
- "use strict";
2
- var __create = Object.create;
3
- var __defProp = Object.defineProperty;
4
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
- var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getProtoOf = Object.getPrototypeOf;
7
- var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __export = (target, all) => {
9
- for (var name in all)
10
- __defProp(target, name, { get: all[name], enumerable: true });
11
- };
12
- var __copyProps = (to, from, except, desc) => {
13
- if (from && typeof from === "object" || typeof from === "function") {
14
- for (let key of __getOwnPropNames(from))
15
- if (!__hasOwnProp.call(to, key) && key !== except)
16
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
- }
18
- return to;
19
- };
20
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
- // If the importer is in node compatibility mode or this is not an ESM
22
- // file that has been converted to a CommonJS file using a Babel-
23
- // compatible transform (i.e. "__esModule" has not been set), then set
24
- // "default" to the CommonJS "module.exports" for node compatibility.
25
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
- mod
27
- ));
28
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
- var installHandler_exports = {};
30
- __export(installHandler_exports, {
31
- RW_DATA_MIGRATION_MODEL: () => RW_DATA_MIGRATION_MODEL,
32
- createDatabaseMigrationCommand: () => createDatabaseMigrationCommand,
33
- handler: () => handler,
34
- notes: () => notes
35
- });
36
- module.exports = __toCommonJS(installHandler_exports);
37
- var import_node_fs = __toESM(require("node:fs"));
38
- var import_node_path = __toESM(require("node:path"));
39
- var import_execa = __toESM(require("execa"));
40
- var import_listr2 = require("listr2");
41
- var import_project_config = require("@cedarjs/project-config");
42
- var import_colors = __toESM(require("../lib/colors"));
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import execa from "execa";
4
+ import { Listr } from "listr2";
5
+ import { colors as c } from "@cedarjs/cli-helpers/colors";
6
+ import {
7
+ getPaths,
8
+ getSchemaPath,
9
+ getDataMigrationsPath
10
+ } from "@cedarjs/project-config";
43
11
  async function handler() {
44
- const cedarProjectPaths = (0, import_project_config.getPaths)();
12
+ const cedarProjectPaths = getPaths();
45
13
  const prismaConfigPath = cedarProjectPaths.api.prismaConfig;
46
- const dataMigrationsPath = await (0, import_project_config.getDataMigrationsPath)(prismaConfigPath);
47
- const tasks = new import_listr2.Listr(
14
+ const dataMigrationsPath = await getDataMigrationsPath(prismaConfigPath);
15
+ const tasks = new Listr(
48
16
  [
49
17
  {
50
18
  title: "Creating the dataMigrations directory...",
51
19
  task() {
52
- import_node_fs.default.mkdirSync(dataMigrationsPath, { recursive: true });
53
- import_node_fs.default.writeFileSync(import_node_path.default.join(dataMigrationsPath, ".keep"), "");
20
+ fs.mkdirSync(dataMigrationsPath, { recursive: true });
21
+ fs.writeFileSync(path.join(dataMigrationsPath, ".keep"), "");
54
22
  }
55
23
  },
56
24
  {
57
25
  title: "Adding the RW_DataMigration model to schema.prisma...",
58
26
  async task() {
59
- const dbSchemaFilePath = await (0, import_project_config.getSchemaPath)(prismaConfigPath);
60
- const dbSchemaFileContent = import_node_fs.default.readFileSync(dbSchemaFilePath, "utf-8");
61
- import_node_fs.default.writeFileSync(
27
+ const dbSchemaFilePath = await getSchemaPath(prismaConfigPath);
28
+ const dbSchemaFileContent = fs.readFileSync(dbSchemaFilePath, "utf-8");
29
+ fs.writeFileSync(
62
30
  dbSchemaFilePath,
63
31
  [dbSchemaFileContent.trim(), "", RW_DATA_MIGRATION_MODEL, ""].join(
64
32
  "\n"
@@ -69,7 +37,7 @@ async function handler() {
69
37
  {
70
38
  title: "Creating the database migration...",
71
39
  task() {
72
- return import_execa.default.command(createDatabaseMigrationCommand, {
40
+ return execa.command(createDatabaseMigrationCommand, {
73
41
  cwd: cedarProjectPaths.base
74
42
  }).stdout;
75
43
  }
@@ -86,7 +54,7 @@ async function handler() {
86
54
  console.log(notes);
87
55
  } catch (e) {
88
56
  process.exitCode = 1;
89
- console.error(import_colors.default.error(e.message));
57
+ console.error(c.error(e.message));
90
58
  }
91
59
  }
92
60
  const RW_DATA_MIGRATION_MODEL = `model RW_DataMigration {
@@ -98,15 +66,14 @@ const RW_DATA_MIGRATION_MODEL = `model RW_DataMigration {
98
66
  const createDatabaseMigrationCommand = "yarn cedar prisma migrate dev --name create_data_migrations --create-only";
99
67
  const notes = [
100
68
  "",
101
- import_colors.default.warning("Don't forget to apply the migration when you're ready:"),
69
+ c.warning("Don't forget to apply the migration when you're ready:"),
102
70
  "",
103
- ` ${import_colors.default.bold("yarn cedar prisma migrate dev")}`,
71
+ ` ${c.bold("yarn cedar prisma migrate dev")}`,
104
72
  ""
105
73
  ].join("\n");
106
- // Annotate the CommonJS export names for ESM import in node:
107
- 0 && (module.exports = {
74
+ export {
108
75
  RW_DATA_MIGRATION_MODEL,
109
76
  createDatabaseMigrationCommand,
110
77
  handler,
111
78
  notes
112
- });
79
+ };
@@ -1,5 +1,5 @@
1
1
  import type { Argv } from 'yargs';
2
- import type { DataMigrateUpOptions } from '../types';
2
+ import type { DataMigrateUpOptions } from '../types.js';
3
3
  export declare const command = "up";
4
4
  export declare const description = "Run any outstanding Data Migrations against the database";
5
5
  export declare function builder(yargs: Argv): Argv;
@@ -1 +1 @@
1
- {"version":3,"file":"up.d.ts","sourceRoot":"","sources":["../../src/commands/up.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,OAAO,CAAA;AAIjC,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,UAAU,CAAA;AAEpD,eAAO,MAAM,OAAO,OAAO,CAAA;AAC3B,eAAO,MAAM,WAAW,6DACoC,CAAA;AAE5D,wBAAgB,OAAO,CAAC,KAAK,EAAE,IAAI,GAAG,IAAI,CAoBzC;AAED,wBAAsB,OAAO,CAAC,OAAO,EAAE,oBAAoB,GAAG,OAAO,CAAC,IAAI,CAAC,CAQ1E"}
1
+ {"version":3,"file":"up.d.ts","sourceRoot":"","sources":["../../src/commands/up.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,OAAO,CAAA;AAIjC,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,aAAa,CAAA;AAEvD,eAAO,MAAM,OAAO,OAAO,CAAA;AAC3B,eAAO,MAAM,WAAW,6DACoC,CAAA;AAE5D,wBAAgB,OAAO,CAAC,KAAK,EAAE,IAAI,GAAG,IAAI,CAoBzC;AAED,wBAAsB,OAAO,CAAC,OAAO,EAAE,oBAAoB,GAAG,OAAO,CAAC,IAAI,CAAC,CAG1E"}
@@ -1,41 +1,5 @@
1
- "use strict";
2
- var __create = Object.create;
3
- var __defProp = Object.defineProperty;
4
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
- var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getProtoOf = Object.getPrototypeOf;
7
- var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __export = (target, all) => {
9
- for (var name in all)
10
- __defProp(target, name, { get: all[name], enumerable: true });
11
- };
12
- var __copyProps = (to, from, except, desc) => {
13
- if (from && typeof from === "object" || typeof from === "function") {
14
- for (let key of __getOwnPropNames(from))
15
- if (!__hasOwnProp.call(to, key) && key !== except)
16
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
- }
18
- return to;
19
- };
20
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
- // If the importer is in node compatibility mode or this is not an ESM
22
- // file that has been converted to a CommonJS file using a Babel-
23
- // compatible transform (i.e. "__esModule" has not been set), then set
24
- // "default" to the CommonJS "module.exports" for node compatibility.
25
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
- mod
27
- ));
28
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
- var up_exports = {};
30
- __export(up_exports, {
31
- builder: () => builder,
32
- command: () => command,
33
- description: () => description,
34
- handler: () => handler
35
- });
36
- module.exports = __toCommonJS(up_exports);
37
- var import_termi_link = require("termi-link");
38
- var import_project_config = require("@cedarjs/project-config");
1
+ import { terminalLink } from "termi-link";
2
+ import { getPaths } from "@cedarjs/project-config";
39
3
  const command = "up";
40
4
  const description = "Run any outstanding Data Migrations against the database";
41
5
  function builder(yargs) {
@@ -48,27 +12,21 @@ function builder(yargs) {
48
12
  type: "string",
49
13
  alias: "d",
50
14
  description: "Path to the api dist directory",
51
- default: (0, import_project_config.getPaths)().api.dist
15
+ default: getPaths().api.dist
52
16
  }).epilogue(
53
- `Also see the ${(0, import_termi_link.terminalLink)(
17
+ `Also see the ${terminalLink(
54
18
  "CedarJS CLI Reference",
55
19
  "https://cedarjs.com/docs/cli-commands#datamigrate-up"
56
20
  )}`
57
21
  );
58
22
  }
59
23
  async function handler(options) {
60
- if ((0, import_project_config.projectIsEsm)()) {
61
- const { handler: dataMigrateUpHandler } = await import("./upHandlerEsm.js");
62
- await dataMigrateUpHandler(options);
63
- } else {
64
- const { handler: dataMigrateUpHandler } = await import("./upHandler.js");
65
- await dataMigrateUpHandler(options);
66
- }
24
+ const { handler: dataMigrateUpHandler } = await import("./upHandler.js");
25
+ await dataMigrateUpHandler(options);
67
26
  }
68
- // Annotate the CommonJS export names for ESM import in node:
69
- 0 && (module.exports = {
27
+ export {
70
28
  builder,
71
29
  command,
72
30
  description,
73
31
  handler
74
- });
32
+ };
@@ -1,4 +1,4 @@
1
- import type { DataMigrateUpOptions } from '../types';
1
+ import type { DataMigrateUpOptions } from '../types.js';
2
2
  export declare function handler({ importDbClientFromDist, distPath, }: DataMigrateUpOptions): Promise<void>;
3
3
  export declare const NO_PENDING_MIGRATIONS_MESSAGE = "No pending data migrations run, already up-to-date.";
4
4
  //# sourceMappingURL=upHandler.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"upHandler.d.ts","sourceRoot":"","sources":["../../src/commands/upHandler.ts"],"names":[],"mappings":"AAUA,OAAO,KAAK,EAAE,oBAAoB,EAAiB,MAAM,UAAU,CAAA;AAEnE,wBAAsB,OAAO,CAAC,EAC5B,sBAAsB,EACtB,QAAQ,GACT,EAAE,oBAAoB,iBA2GtB;AA8ED,eAAO,MAAM,6BAA6B,wDACa,CAAA"}
1
+ {"version":3,"file":"upHandler.d.ts","sourceRoot":"","sources":["../../src/commands/upHandler.ts"],"names":[],"mappings":"AAcA,OAAO,KAAK,EAAE,oBAAoB,EAAiB,MAAM,aAAa,CAAA;AAsCtE,wBAAsB,OAAO,CAAC,EAC5B,sBAAsB,EACtB,QAAQ,GACT,EAAE,oBAAoB,iBAoMtB;AA6DD,eAAO,MAAM,6BAA6B,wDACa,CAAA"}
@@ -1,60 +1,108 @@
1
- "use strict";
2
- var __create = Object.create;
3
- var __defProp = Object.defineProperty;
4
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
- var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getProtoOf = Object.getPrototypeOf;
7
- var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __export = (target, all) => {
9
- for (var name in all)
10
- __defProp(target, name, { get: all[name], enumerable: true });
11
- };
12
- var __copyProps = (to, from, except, desc) => {
13
- if (from && typeof from === "object" || typeof from === "function") {
14
- for (let key of __getOwnPropNames(from))
15
- if (!__hasOwnProp.call(to, key) && key !== except)
16
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { Listr } from "listr2";
4
+ import { createServer, isRunnableDevEnvironment } from "vite";
5
+ import { colors as c } from "@cedarjs/cli-helpers/colors";
6
+ import {
7
+ getPaths,
8
+ getDataMigrationsPath,
9
+ resolveFile,
10
+ importStatementPath
11
+ } from "@cedarjs/project-config";
12
+ function resolveId(id) {
13
+ if (fs.existsSync(id) && fs.statSync(id).isFile()) {
14
+ return id;
17
15
  }
18
- return to;
19
- };
20
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
- // If the importer is in node compatibility mode or this is not an ESM
22
- // file that has been converted to a CommonJS file using a Babel-
23
- // compatible transform (i.e. "__esModule" has not been set), then set
24
- // "default" to the CommonJS "module.exports" for node compatibility.
25
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
- mod
27
- ));
28
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
- var upHandler_exports = {};
30
- __export(upHandler_exports, {
31
- NO_PENDING_MIGRATIONS_MESSAGE: () => NO_PENDING_MIGRATIONS_MESSAGE,
32
- handler: () => handler
33
- });
34
- module.exports = __toCommonJS(upHandler_exports);
35
- var import_node_fs = __toESM(require("node:fs"));
36
- var import_node_path = __toESM(require("node:path"));
37
- var import_listr2 = require("listr2");
38
- var import_babel_config = require("@cedarjs/babel-config");
39
- var import_project_config = require("@cedarjs/project-config");
40
- var import_colors = __toESM(require("../lib/colors"));
16
+ const withoutExt = /\.jsx?$/.test(id) ? id.replace(/\.jsx?$/, "") : id;
17
+ for (const ext of [".ts", ".tsx", ".js", ".jsx"]) {
18
+ if (fs.existsSync(withoutExt + ext)) {
19
+ return withoutExt + ext;
20
+ }
21
+ }
22
+ if (fs.existsSync(id) && fs.statSync(id).isDirectory()) {
23
+ for (const base of ["index", path.basename(id)]) {
24
+ for (const ext of [".ts", ".tsx", ".js", ".jsx"]) {
25
+ const candidate = path.join(id, base + ext);
26
+ if (fs.existsSync(candidate)) {
27
+ return candidate;
28
+ }
29
+ }
30
+ }
31
+ }
32
+ return id;
33
+ }
41
34
  async function handler({
42
35
  importDbClientFromDist,
43
36
  distPath
44
37
  }) {
45
38
  let db;
46
- let requireHookRegistered = false;
39
+ let server = null;
40
+ let cedarPlugins;
41
+ async function getRunner() {
42
+ if (!server) {
43
+ if (!cedarPlugins) {
44
+ const mod = await import("@cedarjs/vite");
45
+ cedarPlugins = mod;
46
+ }
47
+ server = await createServer({
48
+ mode: "production",
49
+ optimizeDeps: {
50
+ noDiscovery: true,
51
+ include: void 0
52
+ },
53
+ server: {
54
+ hmr: false,
55
+ watch: null
56
+ },
57
+ environments: {
58
+ nodeRunnerEnv: {}
59
+ },
60
+ resolve: {
61
+ alias: [
62
+ {
63
+ find: /^api\//,
64
+ replacement: getPaths().api.base + "/"
65
+ },
66
+ {
67
+ find: /^src\//,
68
+ replacement: "src/",
69
+ customResolver: (id, importer, _options) => {
70
+ const apiImportBase = importStatementPath(getPaths().api.base);
71
+ if (importer?.startsWith(apiImportBase)) {
72
+ const apiImportSrc = importStatementPath(getPaths().api.src);
73
+ const apiId = id.replace("src", apiImportSrc);
74
+ return { id: resolveId(apiId) };
75
+ }
76
+ return null;
77
+ }
78
+ }
79
+ ]
80
+ },
81
+ plugins: [
82
+ cedarPlugins.cedarCjsCompatPlugin(),
83
+ cedarPlugins.cedarjsResolveCedarStyleImportsPlugin(),
84
+ cedarPlugins.cedarImportDirPlugin(),
85
+ cedarPlugins.cedarAutoImportsPlugin()
86
+ ]
87
+ });
88
+ }
89
+ const env = server.environments.nodeRunnerEnv;
90
+ if (!env || !isRunnableDevEnvironment(env)) {
91
+ throw new Error("Vite environment is not runnable.");
92
+ }
93
+ return env.runner;
94
+ }
47
95
  if (importDbClientFromDist) {
48
- if (!import_node_fs.default.existsSync(distPath)) {
96
+ if (!fs.existsSync(distPath)) {
49
97
  console.warn(
50
98
  `Can't find api dist at ${distPath}. You may need to build first: yarn cedar build api`
51
99
  );
52
100
  process.exitCode = 1;
53
101
  return;
54
102
  }
55
- const distLibPath = import_node_path.default.join(distPath, "lib");
56
- const distLibDbPath = import_node_path.default.join(distLibPath, "db.js");
57
- if (!import_node_fs.default.existsSync(distLibDbPath)) {
103
+ const distLibPath = path.join(distPath, "lib");
104
+ const distLibDbPath = path.join(distLibPath, "db.js");
105
+ if (!fs.existsSync(distLibDbPath)) {
58
106
  console.error(
59
107
  `Can't find db.js at ${distLibDbPath}. CedarJS expects the db.js file to be in the ${distLibPath} directory`
60
108
  );
@@ -63,21 +111,33 @@ async function handler({
63
111
  }
64
112
  db = (await import(distLibDbPath)).db;
65
113
  } else {
66
- (0, import_babel_config.registerApiSideBabelHook)();
67
- requireHookRegistered = true;
68
- db = require(import_node_path.default.join((0, import_project_config.getPaths)().api.lib, "db")).db;
114
+ const dbPath = resolveFile(path.join(getPaths().api.lib, "db"));
115
+ if (!dbPath) {
116
+ console.error(`Can't find your db file in ${getPaths().api.lib}`);
117
+ process.exitCode = 1;
118
+ return;
119
+ }
120
+ try {
121
+ const runner = await getRunner();
122
+ const dbModule = await runner.import(dbPath);
123
+ db = dbModule.db;
124
+ } catch (e) {
125
+ await server?.close();
126
+ throw e;
127
+ }
69
128
  }
70
129
  const pendingDataMigrations = await getPendingDataMigrations(db);
71
130
  if (!pendingDataMigrations.length) {
72
- console.info(import_colors.default.success(`
131
+ console.info(c.success(`
73
132
  ${NO_PENDING_MIGRATIONS_MESSAGE}
74
133
  `));
75
134
  process.exitCode = 0;
135
+ await server?.close();
76
136
  return;
77
137
  }
78
138
  const counters = { run: 0, skipped: 0, error: 0 };
79
139
  const dataMigrationTasks = pendingDataMigrations.map((dataMigration) => {
80
- const dataMigrationName = import_node_path.default.basename(dataMigration.path, ".js");
140
+ const dataMigrationName = path.basename(dataMigration.path, ".js");
81
141
  return {
82
142
  title: dataMigrationName,
83
143
  skip() {
@@ -89,9 +149,6 @@ ${NO_PENDING_MIGRATIONS_MESSAGE}
89
149
  }
90
150
  },
91
151
  async task() {
92
- if (!requireHookRegistered) {
93
- (0, import_babel_config.registerApiSideBabelHook)();
94
- }
95
152
  try {
96
153
  const { startedAt, finishedAt } = await runDataMigration(
97
154
  db,
@@ -106,14 +163,13 @@ ${NO_PENDING_MIGRATIONS_MESSAGE}
106
163
  });
107
164
  } catch (e) {
108
165
  counters.error++;
109
- console.error(
110
- import_colors.default.error(`Error in data migration: ${e.message}`)
111
- );
166
+ const message = e instanceof Error ? e.message : String(e);
167
+ console.error(c.error(`Error in data migration: ${message}`));
112
168
  }
113
169
  }
114
170
  };
115
171
  });
116
- const tasks = new import_listr2.Listr(dataMigrationTasks, {
172
+ const tasks = new Listr(dataMigrationTasks, {
117
173
  renderer: "verbose"
118
174
  });
119
175
  try {
@@ -131,16 +187,29 @@ ${NO_PENDING_MIGRATIONS_MESSAGE}
131
187
  console.log();
132
188
  reportDataMigrations(counters);
133
189
  console.log();
190
+ } finally {
191
+ if (server) {
192
+ await server.close();
193
+ }
194
+ }
195
+ async function runDataMigration(db2, dataMigrationPath) {
196
+ const runner = await getRunner();
197
+ const dataMigrationModule = await runner.import(dataMigrationPath);
198
+ const dataMigration = dataMigrationModule.default;
199
+ const startedAt = /* @__PURE__ */ new Date();
200
+ await dataMigration({ db: db2 });
201
+ const finishedAt = /* @__PURE__ */ new Date();
202
+ return { startedAt, finishedAt };
134
203
  }
135
204
  }
136
205
  async function getPendingDataMigrations(db) {
137
- const dataMigrationsPath = await (0, import_project_config.getDataMigrationsPath)(
138
- (0, import_project_config.getPaths)().api.prismaConfig
206
+ const dataMigrationsPath = await getDataMigrationsPath(
207
+ getPaths().api.prismaConfig
139
208
  );
140
- if (!import_node_fs.default.existsSync(dataMigrationsPath)) {
209
+ if (!fs.existsSync(dataMigrationsPath)) {
141
210
  return [];
142
211
  }
143
- const dataMigrations = import_node_fs.default.readdirSync(dataMigrationsPath).filter(
212
+ const dataMigrations = fs.readdirSync(dataMigrationsPath).filter(
144
213
  (dataMigrationFileName) => ["js", ".ts"].some(
145
214
  (extension) => dataMigrationFileName.endsWith(extension)
146
215
  )
@@ -148,7 +217,7 @@ async function getPendingDataMigrations(db) {
148
217
  const [version] = dataMigrationFileName.split("-");
149
218
  return {
150
219
  version,
151
- path: import_node_path.default.join(dataMigrationsPath, dataMigrationFileName)
220
+ path: path.join(dataMigrationsPath, dataMigrationFileName)
152
221
  };
153
222
  });
154
223
  const ranDataMigrations = await db.rW_DataMigration.findMany(
@@ -175,13 +244,6 @@ function sortDataMigrationsByVersion(dataMigrationA, dataMigrationB) {
175
244
  }
176
245
  return 0;
177
246
  }
178
- async function runDataMigration(db, dataMigrationPath) {
179
- const dataMigration = require(dataMigrationPath);
180
- const startedAt = /* @__PURE__ */ new Date();
181
- await dataMigration.default({ db });
182
- const finishedAt = /* @__PURE__ */ new Date();
183
- return { startedAt, finishedAt };
184
- }
185
247
  const NO_PENDING_MIGRATIONS_MESSAGE = "No pending data migrations run, already up-to-date.";
186
248
  async function recordDataMigration(db, { version, name, startedAt, finishedAt }) {
187
249
  await db.rW_DataMigration.create({
@@ -191,24 +253,23 @@ async function recordDataMigration(db, { version, name, startedAt, finishedAt })
191
253
  function reportDataMigrations(counters) {
192
254
  if (counters.run) {
193
255
  console.info(
194
- import_colors.default.success(`${counters.run} data migration(s) completed successfully.`)
256
+ c.success(`${counters.run} data migration(s) completed successfully.`)
195
257
  );
196
258
  }
197
259
  if (counters.error) {
198
260
  console.error(
199
- import_colors.default.error(`${counters.error} data migration(s) exited with errors.`)
261
+ c.error(`${counters.error} data migration(s) exited with errors.`)
200
262
  );
201
263
  }
202
264
  if (counters.skipped) {
203
265
  console.warn(
204
- import_colors.default.warning(
266
+ c.warning(
205
267
  `${counters.skipped} data migration(s) skipped due to previous error.`
206
268
  )
207
269
  );
208
270
  }
209
271
  }
210
- // Annotate the CommonJS export names for ESM import in node:
211
- 0 && (module.exports = {
272
+ export {
212
273
  NO_PENDING_MIGRATIONS_MESSAGE,
213
274
  handler
214
- });
275
+ };
package/dist/index.js CHANGED
@@ -1,35 +1,22 @@
1
- "use strict";
2
- var __defProp = Object.defineProperty;
3
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
- var __getOwnPropNames = Object.getOwnPropertyNames;
5
- var __hasOwnProp = Object.prototype.hasOwnProperty;
6
- var __export = (target, all) => {
7
- for (var name in all)
8
- __defProp(target, name, { get: all[name], enumerable: true });
9
- };
10
- var __copyProps = (to, from, except, desc) => {
11
- if (from && typeof from === "object" || typeof from === "function") {
12
- for (let key of __getOwnPropNames(from))
13
- if (!__hasOwnProp.call(to, key) && key !== except)
14
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
- }
16
- return to;
17
- };
18
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
- var src_exports = {};
20
- __export(src_exports, {
21
- commands: () => commands
22
- });
23
- module.exports = __toCommonJS(src_exports);
24
- var import_termi_link = require("termi-link");
25
- var import_install = require("./commands/install");
26
- var import_up = require("./commands/up");
1
+ import { terminalLink } from "termi-link";
2
+ import {
3
+ command as installCommand,
4
+ description as installDescription,
5
+ builder as installBuilder,
6
+ handler as installHandler
7
+ } from "./commands/install.js";
8
+ import {
9
+ command as upCommand,
10
+ description as upDescription,
11
+ builder as upBuilder,
12
+ handler as upHandler
13
+ } from "./commands/up.js";
27
14
  const command = "data-migrate <command>";
28
15
  const aliases = ["dataMigrate", "dm"];
29
16
  const description = "Migrate the data in your database";
30
17
  function builder(yargs) {
31
- yargs.command(import_install.command, import_install.description, import_install.builder, import_install.handler).command(import_up.command, import_up.description, import_up.builder, import_up.handler).epilogue(
32
- `Also see the ${(0, import_termi_link.terminalLink)(
18
+ yargs.command(installCommand, installDescription, installBuilder, installHandler).command(upCommand, upDescription, upBuilder, upHandler).epilogue(
19
+ `Also see the ${terminalLink(
33
20
  "CedarJS CLI Reference",
34
21
  "https://cedarjs.com/docs/cli-commands#datamigrate"
35
22
  )}`
@@ -43,7 +30,6 @@ const commands = [
43
30
  builder
44
31
  }
45
32
  ];
46
- // Annotate the CommonJS export names for ESM import in node:
47
- 0 && (module.exports = {
33
+ export {
48
34
  commands
49
- });
35
+ };
package/package.json CHANGED
@@ -1,12 +1,13 @@
1
1
  {
2
2
  "name": "@cedarjs/cli-data-migrate",
3
- "version": "9.0.0-canary.1784+baa47810a",
3
+ "version": "9.0.0-canary.3124",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "git+https://github.com/cedarjs/cedar.git",
7
7
  "directory": "packages/cli-packages/dataMigrate"
8
8
  },
9
9
  "license": "MIT",
10
+ "type": "module",
10
11
  "exports": "./dist/index.js",
11
12
  "types": "./dist/index.d.ts",
12
13
  "bin": {
@@ -16,36 +17,38 @@
16
17
  "dist"
17
18
  ],
18
19
  "scripts": {
19
- "build": "tsx ./build.mts && yarn build:types",
20
+ "build": "node ./build.mts",
20
21
  "build:pack": "yarn pack -o cedarjs-cli-data-migrate.tgz",
21
- "build:types": "tsc --build --verbose",
22
+ "build:types": "tsc --build --verbose ./tsconfig.build.json",
22
23
  "prepublishOnly": "NODE_ENV=production yarn build",
23
24
  "test": "yarn test:unit && yarn test:dist",
24
25
  "test:dist": "vitest run ./dist.test.ts",
25
26
  "test:unit": "vitest run src"
26
27
  },
27
28
  "dependencies": {
28
- "@cedarjs/babel-config": "9.0.0-canary.1784",
29
- "@cedarjs/project-config": "9.0.0-canary.1784",
30
- "ansis": "4.2.0",
31
- "bundle-require": "^5.1.0",
29
+ "@cedarjs/cli-helpers": "9.0.0-canary.3124",
30
+ "@cedarjs/project-config": "9.0.0-canary.3124",
31
+ "@cedarjs/vite": "9.0.0-canary.3124",
32
32
  "dotenv-defaults": "5.0.2",
33
33
  "execa": "5.1.1",
34
- "listr2": "7.0.2",
34
+ "listr2": "10.2.2",
35
35
  "termi-link": "1.1.0",
36
- "yargs": "17.7.2"
36
+ "vite": "7.3.6",
37
+ "yargs": "17.7.3"
37
38
  },
38
39
  "devDependencies": {
39
- "@cedarjs/framework-tools": "9.0.0-canary.1784",
40
- "@prisma/client": "6.19.2",
40
+ "@cedarjs/framework-tools": "9.0.0-canary.3124",
41
+ "@prisma/client": "7.10.0",
41
42
  "@types/yargs": "17.0.35",
42
- "memfs": "4.56.10",
43
- "tsx": "4.21.0",
43
+ "memfs": "4.68.2",
44
44
  "typescript": "5.9.3",
45
- "vitest": "3.2.4"
45
+ "vitest": "4.1.11"
46
+ },
47
+ "engines": {
48
+ "node": ">=24"
46
49
  },
47
50
  "publishConfig": {
48
51
  "access": "public"
49
52
  },
50
- "gitHead": "baa47810a7defb73de27fdf513b815d679509b5e"
53
+ "gitHead": "3905ed045508b861b495f8d5630d76c7a157d8f1"
51
54
  }
package/LICENSE DELETED
@@ -1,21 +0,0 @@
1
- MIT License
2
-
3
- Copyright (c) 2025 Cedar
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
- SOFTWARE.
@@ -1,4 +0,0 @@
1
- import type { DataMigrateUpOptions } from '../types';
2
- export declare function handler({ importDbClientFromDist, distPath, }: DataMigrateUpOptions): Promise<void>;
3
- export declare const NO_PENDING_MIGRATIONS_MESSAGE = "No pending data migrations run, already up-to-date.";
4
- //# sourceMappingURL=upHandlerEsm.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"upHandlerEsm.d.ts","sourceRoot":"","sources":["../../src/commands/upHandlerEsm.ts"],"names":[],"mappings":"AAcA,OAAO,KAAK,EAAE,oBAAoB,EAAiB,MAAM,UAAU,CAAA;AAEnE,wBAAsB,OAAO,CAAC,EAC5B,sBAAsB,EACtB,QAAQ,GACT,EAAE,oBAAoB,iBAuHtB;AAiFD,eAAO,MAAM,6BAA6B,wDACa,CAAA"}
@@ -1,222 +0,0 @@
1
- "use strict";
2
- var __create = Object.create;
3
- var __defProp = Object.defineProperty;
4
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
- var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getProtoOf = Object.getPrototypeOf;
7
- var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __export = (target, all) => {
9
- for (var name in all)
10
- __defProp(target, name, { get: all[name], enumerable: true });
11
- };
12
- var __copyProps = (to, from, except, desc) => {
13
- if (from && typeof from === "object" || typeof from === "function") {
14
- for (let key of __getOwnPropNames(from))
15
- if (!__hasOwnProp.call(to, key) && key !== except)
16
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
- }
18
- return to;
19
- };
20
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
- // If the importer is in node compatibility mode or this is not an ESM
22
- // file that has been converted to a CommonJS file using a Babel-
23
- // compatible transform (i.e. "__esModule" has not been set), then set
24
- // "default" to the CommonJS "module.exports" for node compatibility.
25
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
- mod
27
- ));
28
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
- var upHandlerEsm_exports = {};
30
- __export(upHandlerEsm_exports, {
31
- NO_PENDING_MIGRATIONS_MESSAGE: () => NO_PENDING_MIGRATIONS_MESSAGE,
32
- handler: () => handler
33
- });
34
- module.exports = __toCommonJS(upHandlerEsm_exports);
35
- var import_node_fs = __toESM(require("node:fs"));
36
- var import_node_path = __toESM(require("node:path"));
37
- var import_bundle_require = require("bundle-require");
38
- var import_listr2 = require("listr2");
39
- var import_project_config = require("@cedarjs/project-config");
40
- var import_colors = __toESM(require("../lib/colors"));
41
- async function handler({
42
- importDbClientFromDist,
43
- distPath
44
- }) {
45
- let db;
46
- if (importDbClientFromDist) {
47
- if (!import_node_fs.default.existsSync(distPath)) {
48
- console.warn(
49
- `Can't find api dist at ${distPath}. You may need to build first: yarn cedar build api`
50
- );
51
- process.exitCode = 1;
52
- return;
53
- }
54
- const distLibPath = import_node_path.default.join(distPath, "lib");
55
- const distLibDbPath = import_node_path.default.join(distLibPath, "db.js");
56
- if (!import_node_fs.default.existsSync(distLibDbPath)) {
57
- console.error(
58
- `Can't find db.js at ${distLibDbPath}. CedarJS expects the db.js file to be in the ${distLibPath} directory`
59
- );
60
- process.exitCode = 1;
61
- return;
62
- }
63
- db = (await import(distLibDbPath)).db;
64
- } else {
65
- const dbPath = (0, import_project_config.resolveFile)(import_node_path.default.join((0, import_project_config.getPaths)().api.lib, "db"));
66
- if (!dbPath) {
67
- console.error(`Can't find your db file in ${(0, import_project_config.getPaths)().api.lib}`);
68
- process.exitCode = 1;
69
- return;
70
- }
71
- const { mod } = await (0, import_bundle_require.bundleRequire)({
72
- filepath: dbPath
73
- // TODO: Add plugins
74
- });
75
- db = mod.db;
76
- }
77
- const pendingDataMigrations = await getPendingDataMigrations(db);
78
- if (!pendingDataMigrations.length) {
79
- console.info(import_colors.default.success(`
80
- ${NO_PENDING_MIGRATIONS_MESSAGE}
81
- `));
82
- process.exitCode = 0;
83
- return;
84
- }
85
- const counters = { run: 0, skipped: 0, error: 0 };
86
- const dataMigrationTasks = pendingDataMigrations.map((dataMigration) => {
87
- const dataMigrationName = import_node_path.default.basename(dataMigration.path, ".js");
88
- return {
89
- title: dataMigrationName,
90
- skip() {
91
- if (counters.error > 0) {
92
- counters.skipped++;
93
- return true;
94
- } else {
95
- return false;
96
- }
97
- },
98
- async task() {
99
- try {
100
- const { startedAt, finishedAt } = await runDataMigration(
101
- db,
102
- dataMigration.path
103
- );
104
- counters.run++;
105
- await recordDataMigration(db, {
106
- version: dataMigration.version,
107
- name: dataMigrationName,
108
- startedAt,
109
- finishedAt
110
- });
111
- } catch (e) {
112
- counters.error++;
113
- console.error(
114
- import_colors.default.error(`Error in data migration: ${e.message}`)
115
- );
116
- }
117
- }
118
- };
119
- });
120
- const tasks = new import_listr2.Listr(dataMigrationTasks, {
121
- renderer: "verbose"
122
- });
123
- try {
124
- await tasks.run();
125
- await db.$disconnect();
126
- console.log();
127
- reportDataMigrations(counters);
128
- console.log();
129
- if (counters.error) {
130
- process.exitCode = 1;
131
- }
132
- } catch {
133
- process.exitCode = 1;
134
- await db.$disconnect();
135
- console.log();
136
- reportDataMigrations(counters);
137
- console.log();
138
- }
139
- }
140
- async function getPendingDataMigrations(db) {
141
- const dataMigrationsPath = await (0, import_project_config.getDataMigrationsPath)(
142
- (0, import_project_config.getPaths)().api.prismaConfig
143
- );
144
- if (!import_node_fs.default.existsSync(dataMigrationsPath)) {
145
- return [];
146
- }
147
- const dataMigrations = import_node_fs.default.readdirSync(dataMigrationsPath).filter(
148
- (dataMigrationFileName) => ["js", ".ts"].some(
149
- (extension) => dataMigrationFileName.endsWith(extension)
150
- )
151
- ).map((dataMigrationFileName) => {
152
- const [version] = dataMigrationFileName.split("-");
153
- return {
154
- version,
155
- path: import_node_path.default.join(dataMigrationsPath, dataMigrationFileName)
156
- };
157
- });
158
- const ranDataMigrations = await db.rW_DataMigration.findMany(
159
- {
160
- orderBy: { version: "asc" }
161
- }
162
- );
163
- const ranDataMigrationVersions = ranDataMigrations.map(
164
- (dataMigration) => dataMigration.version.toString()
165
- );
166
- const pendingDataMigrations = dataMigrations.filter(({ version }) => {
167
- return !ranDataMigrationVersions.includes(version);
168
- }).sort(sortDataMigrationsByVersion);
169
- return pendingDataMigrations;
170
- }
171
- function sortDataMigrationsByVersion(dataMigrationA, dataMigrationB) {
172
- const aVersion = parseInt(dataMigrationA.version);
173
- const bVersion = parseInt(dataMigrationB.version);
174
- if (aVersion > bVersion) {
175
- return 1;
176
- }
177
- if (aVersion < bVersion) {
178
- return -1;
179
- }
180
- return 0;
181
- }
182
- async function runDataMigration(db, dataMigrationPath) {
183
- const { mod } = await (0, import_bundle_require.bundleRequire)({
184
- filepath: dataMigrationPath
185
- // TODO: Add plugins
186
- });
187
- const dataMigration = mod.default;
188
- const startedAt = /* @__PURE__ */ new Date();
189
- await dataMigration({ db });
190
- const finishedAt = /* @__PURE__ */ new Date();
191
- return { startedAt, finishedAt };
192
- }
193
- const NO_PENDING_MIGRATIONS_MESSAGE = "No pending data migrations run, already up-to-date.";
194
- async function recordDataMigration(db, { version, name, startedAt, finishedAt }) {
195
- await db.rW_DataMigration.create({
196
- data: { version, name, startedAt, finishedAt }
197
- });
198
- }
199
- function reportDataMigrations(counters) {
200
- if (counters.run) {
201
- console.info(
202
- import_colors.default.success(`${counters.run} data migration(s) completed successfully.`)
203
- );
204
- }
205
- if (counters.error) {
206
- console.error(
207
- import_colors.default.error(`${counters.error} data migration(s) exited with errors.`)
208
- );
209
- }
210
- if (counters.skipped) {
211
- console.warn(
212
- import_colors.default.warning(
213
- `${counters.skipped} data migration(s) skipped due to previous error.`
214
- )
215
- );
216
- }
217
- }
218
- // Annotate the CommonJS export names for ESM import in node:
219
- 0 && (module.exports = {
220
- NO_PENDING_MIGRATIONS_MESSAGE,
221
- handler
222
- });
@@ -1,16 +0,0 @@
1
- declare const _default: {
2
- error: import("ansis").Ansis;
3
- warning: import("ansis").Ansis;
4
- highlight: import("ansis").Ansis;
5
- success: import("ansis").Ansis;
6
- info: import("ansis").Ansis;
7
- bold: import("ansis").Ansis;
8
- underline: import("ansis").Ansis;
9
- note: import("ansis").Ansis;
10
- tip: import("ansis").Ansis;
11
- important: import("ansis").Ansis;
12
- caution: import("ansis").Ansis;
13
- link: import("ansis").Ansis;
14
- };
15
- export default _default;
16
- //# sourceMappingURL=colors.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"colors.d.ts","sourceRoot":"","sources":["../../src/lib/colors.ts"],"names":[],"mappings":";;;;;;;;;;;;;;AAKA,wBAaC"}
@@ -1,48 +0,0 @@
1
- "use strict";
2
- var __create = Object.create;
3
- var __defProp = Object.defineProperty;
4
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
- var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getProtoOf = Object.getPrototypeOf;
7
- var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __export = (target, all) => {
9
- for (var name in all)
10
- __defProp(target, name, { get: all[name], enumerable: true });
11
- };
12
- var __copyProps = (to, from, except, desc) => {
13
- if (from && typeof from === "object" || typeof from === "function") {
14
- for (let key of __getOwnPropNames(from))
15
- if (!__hasOwnProp.call(to, key) && key !== except)
16
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
- }
18
- return to;
19
- };
20
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
- // If the importer is in node compatibility mode or this is not an ESM
22
- // file that has been converted to a CommonJS file using a Babel-
23
- // compatible transform (i.e. "__esModule" has not been set), then set
24
- // "default" to the CommonJS "module.exports" for node compatibility.
25
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
- mod
27
- ));
28
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
- var colors_exports = {};
30
- __export(colors_exports, {
31
- default: () => colors_default
32
- });
33
- module.exports = __toCommonJS(colors_exports);
34
- var import_ansis = __toESM(require("ansis"));
35
- var colors_default = {
36
- error: import_ansis.default.bold.red,
37
- warning: import_ansis.default.hex("#ffa500"),
38
- highlight: import_ansis.default.hex("#ffa500"),
39
- success: import_ansis.default.green,
40
- info: import_ansis.default.gray,
41
- bold: import_ansis.default.bold,
42
- underline: import_ansis.default.underline,
43
- note: import_ansis.default.blue,
44
- tip: import_ansis.default.green,
45
- important: import_ansis.default.magenta,
46
- caution: import_ansis.default.red,
47
- link: import_ansis.default.hex("#e8e8e8")
48
- };