@prisma/cli-init 0.4.0 → 0.5.0

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/index.js CHANGED
@@ -21,14 +21,14 @@ import {
21
21
  url,
22
22
  withResolvers,
23
23
  y
24
- } from "./chunk-ASMCGOOW.js";
24
+ } from "./chunk-7C5I22R2.js";
25
25
  import {
26
26
  credentialsFile,
27
27
  poll,
28
28
  printPpgInitOutput,
29
29
  requestOrThrow,
30
30
  successMessage
31
- } from "./chunk-SORRSNB3.js";
31
+ } from "./chunk-OCHZ4DEX.js";
32
32
  import {
33
33
  __commonJS,
34
34
  __require,
@@ -1485,13 +1485,13 @@ var require_lockfile = __commonJS({
1485
1485
  if (lock3.released) {
1486
1486
  return releasedCallback && releasedCallback(Object.assign(new Error("Lock is already released"), { code: "ERELEASED" }));
1487
1487
  }
1488
- unlock(file2, { ...options, realpath: false }, releasedCallback);
1488
+ unlock2(file2, { ...options, realpath: false }, releasedCallback);
1489
1489
  });
1490
1490
  });
1491
1491
  });
1492
1492
  });
1493
1493
  }
1494
- function unlock(file, options, callback) {
1494
+ function unlock2(file, options, callback) {
1495
1495
  options = {
1496
1496
  fs: fs3,
1497
1497
  realpath: true,
@@ -1544,7 +1544,7 @@ var require_lockfile = __commonJS({
1544
1544
  }
1545
1545
  });
1546
1546
  module.exports.lock = lock2;
1547
- module.exports.unlock = unlock;
1547
+ module.exports.unlock = unlock2;
1548
1548
  module.exports.check = check2;
1549
1549
  module.exports.getLocks = getLocks;
1550
1550
  }
@@ -1629,7 +1629,7 @@ var require_proper_lockfile = __commonJS({
1629
1629
  const release = toSync(lockfile.lock)(file, toSyncOptions(options));
1630
1630
  return toSync(release);
1631
1631
  }
1632
- function unlock(file, options) {
1632
+ function unlock2(file, options) {
1633
1633
  return toPromise(lockfile.unlock)(file, options);
1634
1634
  }
1635
1635
  function unlockSync(file, options) {
@@ -1643,7 +1643,7 @@ var require_proper_lockfile = __commonJS({
1643
1643
  }
1644
1644
  module.exports = lock2;
1645
1645
  module.exports.lock = lock2;
1646
- module.exports.unlock = unlock;
1646
+ module.exports.unlock = unlock2;
1647
1647
  module.exports.lockSync = lockSync;
1648
1648
  module.exports.unlockSync = unlockSync;
1649
1649
  module.exports.check = check2;
@@ -2645,7 +2645,7 @@ async function getApp(port, dbServer, serverState) {
2645
2645
  const { debug } = serverState;
2646
2646
  const [{ Hono }, { accelerateRoute }, { utilityRoute }] = await Promise.all([
2647
2647
  import("hono/tiny"),
2648
- import("./accelerate-GABM6I4V.js"),
2648
+ import("./accelerate-YEFEYVGD.js"),
2649
2649
  import("./utility-W6LOZZIT.js")
2650
2650
  ]);
2651
2651
  const app = new Hono();
@@ -2787,12 +2787,12 @@ ${JSON.stringify(issues, null, 2)}`);
2787
2787
  });
2788
2788
  }
2789
2789
  static async scan(options) {
2790
- const { debug } = options ?? {};
2790
+ const { debug, globs } = options ?? {};
2791
2791
  const dataDirsPath = join(getDataDirPath(DEFAULT_NAME), "..");
2792
2792
  if (debug) {
2793
2793
  console.debug(`[State] scanning for server states in: ${dataDirsPath}`);
2794
2794
  }
2795
- const names = await readDirectoryNames(dataDirsPath);
2795
+ const names = await readDirectoryNames(dataDirsPath, globs);
2796
2796
  if (debug) {
2797
2797
  console.debug(`[State] found server names: ${JSON.stringify(names)}`);
2798
2798
  }
@@ -2834,14 +2834,17 @@ var StatelessServerState = class extends ServerState {
2834
2834
  var StatefulServerState = class _StatefulServerState extends ServerState {
2835
2835
  #databaseDumpPath;
2836
2836
  #dataDirPath;
2837
+ #lockfilePath;
2837
2838
  #pglitePath;
2838
2839
  #serverDumpPath;
2840
+ #closed;
2839
2841
  #serverDump;
2840
- #unlock = null;
2841
2842
  constructor(options) {
2842
2843
  super({ ...options, persistenceMode: "stateful" });
2844
+ this.#closed = false;
2843
2845
  this.#dataDirPath = getDataDirPath(this.name);
2844
2846
  this.#databaseDumpPath = join(this.#dataDirPath, "db_dump.bak");
2847
+ this.#lockfilePath = join(this.#dataDirPath, ".lock");
2845
2848
  this.#pglitePath = join(this.#dataDirPath, ".pglite");
2846
2849
  this.#serverDump = options?.serverDump ?? null;
2847
2850
  this.#serverDumpPath = _StatefulServerState.getServerDumpPath(this.#dataDirPath);
@@ -2864,7 +2867,7 @@ var StatefulServerState = class _StatefulServerState extends ServerState {
2864
2867
  console.debug(`[State] using data directory: ${this.#dataDirPath}`);
2865
2868
  }
2866
2869
  try {
2867
- this.#unlock = await (0, import_proper_lockfile.lock)(this.#dataDirPath, { lockfilePath: join(this.#dataDirPath, ".lock") });
2870
+ await (0, import_proper_lockfile.lock)(this.#dataDirPath, { lockfilePath: this.#lockfilePath });
2868
2871
  if (this.debug) {
2869
2872
  console.debug(`[State] obtained lock on: ${this.#dataDirPath}`);
2870
2873
  }
@@ -2891,17 +2894,19 @@ var StatefulServerState = class _StatefulServerState extends ServerState {
2891
2894
  }
2892
2895
  }
2893
2896
  async close() {
2894
- if (this.#unlock == null) {
2897
+ if (this.#closed) {
2895
2898
  return;
2896
2899
  }
2897
2900
  try {
2898
- await this.#unlock();
2899
- this.#unlock = null;
2901
+ await (0, import_proper_lockfile.unlock)(this.#dataDirPath, { lockfilePath: this.#lockfilePath });
2902
+ this.#closed = true;
2900
2903
  if (this.debug) {
2901
2904
  console.debug(`[State] released lock on: ${this.#dataDirPath}`);
2902
2905
  }
2903
2906
  } catch (error) {
2904
- console.error(`[State] failed to release lock on: ${this.#dataDirPath}`);
2907
+ if (this.debug) {
2908
+ console.error(`[State] failed to release lock on: ${this.#dataDirPath}`, error);
2909
+ }
2905
2910
  throw error;
2906
2911
  }
2907
2912
  }
@@ -2919,19 +2924,21 @@ var StatefulServerState = class _StatefulServerState extends ServerState {
2919
2924
  `, { encoding: "utf-8" });
2920
2925
  }
2921
2926
  };
2922
- async function getServerStatus(name, options) {
2927
+ async function getServerStatus(nameOrState, options) {
2923
2928
  const { debug, onlyMetadata } = options || {};
2929
+ const name = typeof nameOrState === "string" ? nameOrState : nameOrState.name;
2930
+ const givenState = typeof nameOrState !== "string" ? nameOrState : void 0;
2924
2931
  const baseResult = {
2925
- databasePort: -1,
2926
- exports: void 0,
2932
+ databasePort: givenState?.databasePort ?? -1,
2933
+ exports: givenState?.exports,
2927
2934
  name,
2928
- pid: void 0,
2929
- port: -1,
2930
- shadowDatabasePort: -1,
2935
+ pid: givenState?.pid,
2936
+ port: givenState?.port ?? -1,
2937
+ shadowDatabasePort: givenState?.shadowDatabasePort ?? -1,
2931
2938
  version: "1"
2932
2939
  };
2933
2940
  try {
2934
- const serverState = await ServerState.fromServerDump({ debug, name });
2941
+ const serverState = givenState || await ServerState.fromServerDump({ debug, name });
2935
2942
  if (!serverState) {
2936
2943
  if (debug) {
2937
2944
  console.debug(`[State] no server state found for name: ${name}`);
@@ -2979,14 +2986,14 @@ async function getServerStatus(name, options) {
2979
2986
  return { ...baseResult, status: "not_running" };
2980
2987
  }
2981
2988
  const health = await healthResponse.json();
2982
- if (health.name !== name) {
2989
+ if (health.name !== nameOrState) {
2983
2990
  if (debug) {
2984
2991
  console.debug(`[State] server state for "${name}" has mismatched health response: ${JSON.stringify(health)}`);
2985
2992
  }
2986
2993
  return { ...baseResult, status: "unknown" };
2987
2994
  }
2988
2995
  if (debug) {
2989
- console.debug(`[State] server state for "${name}" is live: ${JSON.stringify(health)}`);
2996
+ console.debug(`[State] server state for "${nameOrState}" is live: ${JSON.stringify(health)}`);
2990
2997
  }
2991
2998
  return { ...baseResult, status: "running" };
2992
2999
  } catch (error) {
@@ -3145,6 +3152,10 @@ function printError(text) {
3145
3152
  }
3146
3153
 
3147
3154
  // src/Init.ts
3155
+ var isBun = (
3156
+ // @ts-ignore
3157
+ !!globalThis.Bun || !!globalThis.process?.versions?.bun
3158
+ );
3148
3159
  var defaultSchema = (props) => {
3149
3160
  const {
3150
3161
  datasourceProvider = "postgresql",
@@ -3169,7 +3180,6 @@ ${previewFeatures.length > 0 ? ` previewFeatures = [${previewFeatures.map((feat
3169
3180
 
3170
3181
  datasource db {
3171
3182
  provider = "${datasourceProvider}"
3172
- url = env("DATABASE_URL")
3173
3183
  }
3174
3184
  `;
3175
3185
  if (withModel) {
@@ -3203,10 +3213,10 @@ model User {
3203
3213
  }
3204
3214
  return schema;
3205
3215
  };
3206
- var defaultEnv = async (url2, comments = true) => {
3216
+ var defaultEnv = async (url2, debug = false, comments = true) => {
3207
3217
  if (url2 === void 0) {
3208
3218
  let created = false;
3209
- const state = await ServerState.fromServerDump() || (created = true, await ServerState.createExclusively({ persistenceMode: "stateful" }));
3219
+ const state = await ServerState.fromServerDump({ debug }) || (created = true, await ServerState.createExclusively({ persistenceMode: "stateful", debug }));
3210
3220
  if (created) {
3211
3221
  await state.close();
3212
3222
  }
@@ -3214,12 +3224,14 @@ var defaultEnv = async (url2, comments = true) => {
3214
3224
  databasePort: state.databasePort,
3215
3225
  dryRun: true,
3216
3226
  port: state.port,
3217
- shadowDatabasePort: state.shadowDatabasePort
3227
+ shadowDatabasePort: state.shadowDatabasePort,
3228
+ debug
3218
3229
  });
3219
3230
  url2 = server.ppg.url;
3220
3231
  }
3221
- let env = comments ? `# Environment variables declared in this file are automatically made available to Prisma.
3222
- # See the documentation for more detail: https://pris.ly/d/prisma-schema#accessing-environment-variables-from-the-schema
3232
+ let env = comments ? `# Environment variables declared in this file are NOT automatically loaded by Prisma.
3233
+ # Please add \`import "dotenv/config";\` to your \`prisma.config.ts\` file, or use the Prisma CLI with Bun
3234
+ # to load environment variables from .env files: https://pris.ly/prisma-config-env-vars.
3223
3235
 
3224
3236
  # Prisma supports the native connection string format for PostgreSQL, MySQL, SQLite, SQL Server, MongoDB and CockroachDB.
3225
3237
  # See the documentation for all the connection string options: https://pris.ly/d/connection-strings
@@ -3273,8 +3285,29 @@ var defaultGitIgnore = () => {
3273
3285
  .env
3274
3286
  `;
3275
3287
  };
3276
- var defaultGeneratorProvider = "prisma-client-js";
3288
+ var defaultGeneratorProvider = "prisma-client";
3277
3289
  var defaultPreviewFeatures = [];
3290
+ function normalizePath(configPath) {
3291
+ return JSON.stringify(configPath.replaceAll(path2.sep, "/"));
3292
+ }
3293
+ var defaultConfig = (props) => {
3294
+ const { prismaFolder } = props;
3295
+ const schemaPath = path2.relative(process.cwd(), path2.join(prismaFolder, "schema.prisma"));
3296
+ const migrationsPath = path2.relative(process.cwd(), path2.join(prismaFolder, "migrations"));
3297
+ return `import { defineConfig, env } from "prisma/config";
3298
+
3299
+ export default defineConfig({
3300
+ schema: ${normalizePath(schemaPath)},
3301
+ migrations: {
3302
+ path: ${normalizePath(migrationsPath)},
3303
+ },
3304
+ engine: "classic",
3305
+ datasource: {
3306
+ url: env("DATABASE_URL"),
3307
+ },
3308
+ });
3309
+ `;
3310
+ };
3278
3311
  var Init = class _Init {
3279
3312
  static new() {
3280
3313
  return new _Init();
@@ -3338,7 +3371,8 @@ var Init = class _Init {
3338
3371
  "--name": String,
3339
3372
  "--non-interactive": Boolean,
3340
3373
  "--prompt": String,
3341
- "--vibe": String
3374
+ "--vibe": String,
3375
+ "--debug": Boolean
3342
3376
  });
3343
3377
  if (internals.isError(args) || args["--help"]) {
3344
3378
  return this.help();
@@ -3399,7 +3433,7 @@ var Init = class _Init {
3399
3433
  let generatedSchema;
3400
3434
  let generatedName;
3401
3435
  if (isPpgCommand) {
3402
- const PlatformCommands = await import("./_-WIN5AVS3.js");
3436
+ const PlatformCommands = await import("./_-YBFA2SJO.js");
3403
3437
  const credentials = await credentialsFile.load();
3404
3438
  if (internals.isError(credentials))
3405
3439
  throw credentials;
@@ -3552,9 +3586,15 @@ var Init = class _Init {
3552
3586
  );
3553
3587
  const databaseUrl = prismaPostgresDatabaseUrl || url2;
3554
3588
  const warnings = [];
3589
+ fs2.writeFileSync(
3590
+ path2.join(outputDir, "prisma.config.ts"),
3591
+ defaultConfig({
3592
+ prismaFolder
3593
+ })
3594
+ );
3555
3595
  const envPath = path2.join(outputDir, ".env");
3556
3596
  if (!fs2.existsSync(envPath)) {
3557
- fs2.writeFileSync(envPath, await defaultEnv(databaseUrl));
3597
+ fs2.writeFileSync(envPath, await defaultEnv(databaseUrl, args["--debug"]));
3558
3598
  } else {
3559
3599
  const envFile = fs2.readFileSync(envPath, { encoding: "utf8" });
3560
3600
  const config = dotenv.parse(envFile);
@@ -3565,10 +3605,13 @@ var Init = class _Init {
3565
3605
  )}`
3566
3606
  );
3567
3607
  } else {
3568
- fs2.appendFileSync(envPath, `
3608
+ fs2.appendFileSync(
3609
+ envPath,
3610
+ `
3569
3611
 
3570
3612
  # This was inserted by \`prisma init\`:
3571
- ` + defaultEnv(databaseUrl));
3613
+ ` + await defaultEnv(databaseUrl, args["--debug"])
3614
+ );
3572
3615
  }
3573
3616
  }
3574
3617
  const gitignorePath = path2.join(outputDir, ".gitignore");
@@ -3594,6 +3637,9 @@ var Init = class _Init {
3594
3637
  console.error("Failed to append client path to .gitignore file, reason: ", e);
3595
3638
  }
3596
3639
  const steps = [];
3640
+ if (!isBun) {
3641
+ steps.push(`Install \`dotenv\`, and add \`import "dotenv/config";\` to your \`prisma.config.ts\` file to load environment variables from \`.env\`.`);
3642
+ }
3597
3643
  const isPrismaDev = !args["--url"] && (datasourceProvider === "postgres" || datasourceProvider === "postgresql");
3598
3644
  if (isPrismaDev) {
3599
3645
  steps.push(
@@ -3629,9 +3675,14 @@ var Init = class _Init {
3629
3675
  "ORM"
3630
3676
  )} with scalable connection pooling, global caching, and a managed serverless Postgres database. Read: https://pris.ly/cli/beyond-orm`
3631
3677
  );
3678
+ if (!isBun) {
3679
+ warnings.push(`Environment variables declared in the \`.env\` file are NOT automatically loaded by Prisma.
3680
+ See: https://pris.ly/prisma-config-env-vars.`);
3681
+ }
3632
3682
  const defaultOutput = `
3633
3683
  \u2714 Your Prisma schema was created at ${green("prisma/schema.prisma")}
3634
- You can now open it in your favorite editor.
3684
+ \u2714 Your Prisma config was created at ${green("prisma.config.ts")}
3685
+ You can now open them in your favorite editor.
3635
3686
  ${warnings.length > 0 && internals.logger.should.warn() ? `
3636
3687
  ${warnings.join("\n")}
3637
3688
  ` : ""}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@prisma/cli-init",
3
- "version": "0.4.0",
3
+ "version": "0.5.0",
4
4
  "description": "Init CLI for Prisma",
5
5
  "type": "module",
6
6
  "sideEffects": false,
@@ -36,7 +36,7 @@
36
36
  "tsup": "8.0.2",
37
37
  "typescript": "5.8.3",
38
38
  "vitest": "3.1.3",
39
- "@prisma/dev": "0.9.0"
39
+ "@prisma/dev": "0.11.1"
40
40
  },
41
41
  "dependencies": {
42
42
  "@inquirer/prompts": "7.3.3",
@@ -1,221 +0,0 @@
1
- import { createRequire } from 'node:module'; const require = createRequire(import.meta.url);
2
- import {
3
- Engine,
4
- apiKeyValidator,
5
- array,
6
- handleEngineError,
7
- integer,
8
- literal,
9
- looseObject,
10
- minLength,
11
- minValue,
12
- number,
13
- object,
14
- optional,
15
- pipe,
16
- safeParse,
17
- string,
18
- union
19
- } from "./chunk-ASMCGOOW.js";
20
- import "./chunk-YX4UTTNJ.js";
21
-
22
- // ../../dev/server/src/accelerate.ts
23
- import { Hono } from "hono/tiny";
24
- import { validator } from "hono/validator";
25
-
26
- // ../../dev/server/src/caching.ts
27
- var invalidateInputSchema = object({
28
- tags: union([pipe(array(string()), minLength(1)), literal("all")])
29
- });
30
- async function assertInvalidateInput(ctx) {
31
- const { output, success } = safeParse(invalidateInputSchema, await ctx.req.json(), { abortEarly: true });
32
- if (!success) {
33
- return ctx.text("Invalid input", 400);
34
- }
35
- return output;
36
- }
37
-
38
- // ../../dev/server/src/schema.ts
39
- import { Buffer } from "buffer";
40
- var SCHEMAS_BY_HASH = /* @__PURE__ */ new Map();
41
- async function hashSchema(base64Schema) {
42
- const encoder = new TextEncoder();
43
- const data = encoder.encode(base64Schema);
44
- const hashBuffer = await crypto.subtle.digest("SHA-256", data);
45
- const hashArray = Array.from(new Uint8Array(hashBuffer));
46
- const hashHex = hashArray.map((byte) => byte.toString(16).padStart(2, "0")).join("");
47
- return hashHex;
48
- }
49
- function assertSchema(ctx) {
50
- const schemaHash = ctx.req.param("schemaHash");
51
- const schemas = SCHEMAS_BY_HASH.get(schemaHash);
52
- if (schemas == null) {
53
- return ctx.json({ EngineNotStarted: { reason: "SchemaMissing" } }, 404);
54
- }
55
- return { schemaHash, schemas };
56
- }
57
- var datasourceBlockRegex = /datasource\s+db\s+\{\s*provider\s*=\s*"postgres(!?ql)?"\s+url\s*=\s*.+\s*\}/;
58
- async function overrideDatasource(base64Schema, connectionString) {
59
- const schema = Buffer.from(base64Schema, "base64").toString("utf8");
60
- const override = `datasource db {
61
- provider = "postgresql"
62
- url = "${connectionString.toString()}"
63
- }`;
64
- const schemaWithOverride = schema.replace(datasourceBlockRegex, override);
65
- const overrideHash = await hashSchema(schemaWithOverride);
66
- return {
67
- base64Override: Buffer.from(schemaWithOverride, "utf8").toString("base64"),
68
- overrideHash
69
- };
70
- }
71
-
72
- // ../../dev/server/src/tracing.ts
73
- function getTracingHeaders(ctx) {
74
- const { req } = ctx;
75
- return {
76
- traceparent: req.header("traceparent"),
77
- ["X-capture-telemetry"]: req.header("X-capture-telemetry")
78
- };
79
- }
80
-
81
- // ../../dev/server/src/transaction.ts
82
- var transactionOptionsSchema = object({
83
- isolation_level: optional(string()),
84
- max_wait: pipe(number(), integer(), minValue(0)),
85
- timeout: pipe(number(), integer(), minValue(0))
86
- });
87
- async function assertTransactionOptions(ctx) {
88
- const { issues, output, success } = safeParse(transactionOptionsSchema, await ctx.req.json(), { abortEarly: true });
89
- if (!success) {
90
- return ctx.json({ EngineNotStarted: { reason: "InvalidRequest", issues } }, 400);
91
- }
92
- return output;
93
- }
94
- var transactionSchema = looseObject({
95
- id: union([string(), number()])
96
- });
97
- function assertTransaction(thing, ctx) {
98
- const { output, success } = safeParse(transactionSchema, thing);
99
- if (!success) {
100
- return ctx.json({ EngineMalfunction: {} }, 500);
101
- }
102
- return output;
103
- }
104
-
105
- // ../../dev/server/src/accelerate.ts
106
- var accelerateRoute = new Hono();
107
- accelerateRoute.post("/invalidate", validator("header", apiKeyValidator), async (ctx) => {
108
- const invlidateInput = await assertInvalidateInput(ctx);
109
- if (invlidateInput instanceof Response) {
110
- return invlidateInput;
111
- }
112
- return ctx.body(null);
113
- });
114
- var SCHEMAFUL_BASE_PATH = "/:clientVersion/:schemaHash";
115
- var schemafulRoute = accelerateRoute.basePath(SCHEMAFUL_BASE_PATH);
116
- accelerateRoute.route("/", schemafulRoute);
117
- var GRAPHQL_PATHS = ["/graphql", "/itx/:transactionId/graphql"];
118
- schemafulRoute.on("POST", [...GRAPHQL_PATHS], validator("header", apiKeyValidator), async (ctx) => {
119
- const { req } = ctx;
120
- try {
121
- const engine = await getEngine(ctx);
122
- if (engine instanceof Response) {
123
- return engine;
124
- }
125
- const query = await req.text();
126
- const transactionId = req.param("transactionId");
127
- const results = await engine.request(query, {
128
- ...getTracingHeaders(ctx),
129
- ["X-transaction-id"]: transactionId
130
- });
131
- return ctx.text(results);
132
- } catch (error) {
133
- return handleEngineError(error, ctx);
134
- }
135
- });
136
- schemafulRoute.basePath("/itx/:transactionId").on("POST", ["/commit", "/rollback"], validator("header", apiKeyValidator), async (ctx) => {
137
- const { req } = ctx;
138
- try {
139
- const engine = await getEngine(ctx);
140
- if (engine instanceof Response) {
141
- return engine;
142
- }
143
- const action = req.routePath.split("/").filter(Boolean).at(-1);
144
- const method = `${action}Transaction`;
145
- const transactionId = req.param("transactionId");
146
- const response = await engine[method](transactionId, getTracingHeaders(ctx));
147
- return ctx.json(response);
148
- } catch (error) {
149
- return handleEngineError(error, ctx);
150
- }
151
- });
152
- schemafulRoute.put("/schema", validator("header", apiKeyValidator), async (ctx) => {
153
- const { req } = ctx;
154
- const base64Schema = await req.text();
155
- if (!base64Schema) {
156
- return ctx.text("Missing schema", 400);
157
- }
158
- const schemaHash = req.param("schemaHash");
159
- const schemas = SCHEMAS_BY_HASH.get(schemaHash);
160
- if (schemas == null) {
161
- if (schemaHash !== await hashSchema(base64Schema)) {
162
- return ctx.text("Schema hash mismatch", 400);
163
- }
164
- const override = await overrideDatasource(base64Schema, ctx.get("db").prismaORMConnectionString);
165
- SCHEMAS_BY_HASH.set(schemaHash, { base64Original: base64Schema, ...override });
166
- return ctx.text(schemaHash);
167
- }
168
- if (base64Schema !== schemas.base64Original) {
169
- return ctx.text("Schema mismatch", 400);
170
- }
171
- return ctx.text(schemaHash);
172
- });
173
- schemafulRoute.post("/transaction/start", validator("header", apiKeyValidator), async (ctx) => {
174
- const { req } = ctx;
175
- const transactionOptions = await assertTransactionOptions(ctx);
176
- if (transactionOptions instanceof Response) {
177
- return transactionOptions;
178
- }
179
- try {
180
- const engine = await getEngine(ctx);
181
- if (engine instanceof Response) {
182
- return engine;
183
- }
184
- const response = await engine.startTransaction(transactionOptions, getTracingHeaders(ctx));
185
- const transaction = assertTransaction(response, ctx);
186
- if (transaction instanceof Response) {
187
- return transaction;
188
- }
189
- const { id } = transaction;
190
- const clientVersion = req.param("clientVersion");
191
- const port = ctx.get("port");
192
- const protocol = ctx.get("protocol");
193
- const schemaHash = req.param("schemaHash");
194
- return ctx.json({
195
- ...response,
196
- "data-proxy": {
197
- endpoint: `${protocol}://localhost:${port}/${clientVersion}/${schemaHash}/itx/${id}`
198
- }
199
- });
200
- } catch (error) {
201
- return handleEngineError(error, ctx);
202
- }
203
- });
204
- async function getEngine(ctx) {
205
- const { req } = ctx;
206
- const schema = assertSchema(ctx);
207
- if (schema instanceof Response) {
208
- return schema;
209
- }
210
- const { base64Override, overrideHash } = schema.schemas;
211
- return await Engine.get({
212
- base64Schema: base64Override,
213
- clientVersion: process.env.PRISMA_DEV_FORCE_CLIENT_VERSION || req.param("clientVersion"),
214
- debug: ctx.get("debug"),
215
- platform: ctx.get("platform"),
216
- schemaHash: overrideHash
217
- });
218
- }
219
- export {
220
- accelerateRoute
221
- };