@zenstackhq/cli 3.9.0-beta.1 → 3.9.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.cjs CHANGED
@@ -67,11 +67,10 @@ let _zenstackhq_orm_dialects_postgres = require("@zenstackhq/orm/dialects/postgr
67
67
  let _zenstackhq_orm_dialects_sqlite = require("@zenstackhq/orm/dialects/sqlite");
68
68
  let _zenstackhq_plugin_policy = require("@zenstackhq/plugin-policy");
69
69
  let _zenstackhq_server_api = require("@zenstackhq/server/api");
70
- let _zenstackhq_server_express = require("@zenstackhq/server/express");
71
- let cors = require("cors");
72
- cors = __toESM(cors, 1);
73
- let express = require("express");
74
- express = __toESM(express, 1);
70
+ let _zenstackhq_server_hono = require("@zenstackhq/server/hono");
71
+ let _hono_node_server = require("@hono/node-server");
72
+ let hono = require("hono");
73
+ let hono_cors = require("hono/cors");
75
74
  require("mixpanel");
76
75
  let os = require("os");
77
76
  os = __toESM(os, 1);
@@ -300,6 +299,32 @@ function startUsageTipsFetch() {
300
299
  }
301
300
  };
302
301
  }
302
+ function isPackageInstalled(pkgName) {
303
+ try {
304
+ (0, node_module.createRequire)(node_path.default.resolve(process.cwd(), "package.json")).resolve(pkgName);
305
+ return true;
306
+ } catch {
307
+ return false;
308
+ }
309
+ }
310
+ async function loadPackage(pkgName) {
311
+ try {
312
+ return await import(pkgName);
313
+ } catch (importErr) {
314
+ let projectRequire;
315
+ try {
316
+ projectRequire = (0, node_module.createRequire)(node_path.default.resolve(process.cwd(), "package.json"));
317
+ return await import((0, node_url.pathToFileURL)(projectRequire.resolve(pkgName)).href);
318
+ } catch (resolvedImportErr) {
319
+ try {
320
+ return projectRequire(pkgName);
321
+ } catch (requireErr) {
322
+ if (process.env["DEBUG"]) console.error(importErr, resolvedImportErr, requireErr);
323
+ return null;
324
+ }
325
+ }
326
+ }
327
+ }
303
328
  //#endregion
304
329
  //#region src/actions/check.ts
305
330
  /**
@@ -956,7 +981,9 @@ const mysql = {
956
981
  }
957
982
  },
958
983
  async introspect(connectionString, options) {
959
- const connection = await (await import("mysql2/promise")).createConnection(connectionString);
984
+ const mod = await loadPackage("mysql2/promise");
985
+ if (!mod) throw new CliError("Package \"mysql2\" is required for MySQL support. Please install it with: npm install mysql2");
986
+ const connection = await (mod.createConnection ? mod : mod.default ?? mod).createConnection(connectionString);
960
987
  try {
961
988
  const databaseName = new URL(connectionString).pathname.replace("/", "");
962
989
  if (!databaseName) throw new CliError("Database name not found in connection string");
@@ -1454,8 +1481,10 @@ const postgresql = {
1454
1481
  }
1455
1482
  },
1456
1483
  async introspect(connectionString, options) {
1457
- const { Client } = await import("pg");
1458
- const client = new Client({ connectionString });
1484
+ const pg = await loadPackage("pg");
1485
+ const ClientClass = pg?.Client || pg?.default?.Client;
1486
+ if (!ClientClass) throw new CliError("Package \"pg\" is required for PostgreSQL support. Please install it with: npm install pg");
1487
+ const client = new ClientClass({ connectionString });
1459
1488
  await client.connect();
1460
1489
  try {
1461
1490
  const { rows: tables } = await client.query(tableIntrospectionQuery);
@@ -1981,7 +2010,9 @@ const sqlite = {
1981
2010
  },
1982
2011
  getDefaultDatabaseType() {},
1983
2012
  async introspect(connectionString, _options) {
1984
- const SQLite = (await import("better-sqlite3")).default;
2013
+ const mod = await loadPackage("better-sqlite3");
2014
+ const SQLite = mod?.default || mod;
2015
+ if (!SQLite) throw new CliError("Package \"better-sqlite3\" is required for SQLite support. Please install it with: npm install better-sqlite3");
1985
2016
  const db = new SQLite(connectionString, { readonly: true });
1986
2017
  try {
1987
2018
  const all = (sql) => {
@@ -2243,9 +2274,21 @@ async function runPull(options) {
2243
2274
  returnServices: true,
2244
2275
  mergeImports: treatAsFile
2245
2276
  });
2246
- const SUPPORTED_PROVIDERS = Object.keys(providers);
2247
- const datasource = getDatasource(model);
2248
- if (!SUPPORTED_PROVIDERS.includes(datasource.provider)) throw new CliError(`Unsupported datasource provider: ${datasource.provider}`);
2277
+ let datasource;
2278
+ if (options.provider && options.databaseUrl) {
2279
+ let databaseUrl = options.databaseUrl;
2280
+ if (options.provider === "sqlite" && databaseUrl.startsWith("file:")) {
2281
+ databaseUrl = new URL(databaseUrl, `file:${model.$document.uri.path}`).pathname;
2282
+ if (process.platform === "win32" && databaseUrl[0] === "/") databaseUrl = databaseUrl.slice(1);
2283
+ }
2284
+ datasource = {
2285
+ provider: options.provider,
2286
+ url: databaseUrl,
2287
+ defaultSchema: "public",
2288
+ allSchemas: ["public"]
2289
+ };
2290
+ } else datasource = getDatasource(model);
2291
+ if (!Object.keys(providers).includes(datasource.provider)) throw new CliError(`Unsupported datasource provider: ${datasource.provider}`);
2249
2292
  const provider = providers[datasource.provider];
2250
2293
  if (!provider) throw new CliError(`No introspection provider found for: ${datasource.provider}`);
2251
2294
  spinner.start("Introspecting database...");
@@ -2285,16 +2328,17 @@ async function runPull(options) {
2285
2328
  });
2286
2329
  resolvedRelations.push(...relations);
2287
2330
  }
2331
+ const schemasMatch = (a, b) => (a ?? "") === (b ?? "");
2288
2332
  for (const relation of resolvedRelations) {
2289
2333
  const similarRelations = resolvedRelations.filter((rr) => {
2290
- return rr !== relation && (rr.schema === relation.schema && rr.table === relation.table && rr.references.schema === relation.references.schema && rr.references.table === relation.references.table || rr.schema === relation.references.schema && rr.columns[0] === relation.references.columns[0] && rr.references.schema === relation.schema && rr.references.table === relation.table);
2334
+ return rr !== relation && (schemasMatch(rr.schema, relation.schema) && rr.table === relation.table && schemasMatch(rr.references.schema, relation.references.schema) && rr.references.table === relation.references.table || schemasMatch(rr.schema, relation.references.schema) && rr.table === relation.references.table && schemasMatch(rr.references.schema, relation.schema) && rr.references.table === relation.table);
2291
2335
  }).length;
2292
2336
  syncRelation({
2293
2337
  model: newModel,
2294
2338
  relation,
2295
2339
  services,
2296
2340
  options,
2297
- selfRelation: relation.references.schema === relation.schema && relation.references.table === relation.table,
2341
+ selfRelation: schemasMatch(relation.references.schema, relation.schema) && relation.references.table === relation.table,
2298
2342
  similarRelations
2299
2343
  });
2300
2344
  }
@@ -3064,10 +3108,17 @@ function getVersion() {
3064
3108
  async function checkNewVersion() {
3065
3109
  const currVersion = getVersion();
3066
3110
  let latestVersion;
3111
+ let timer;
3067
3112
  try {
3068
- latestVersion = await getLatestVersion();
3113
+ const fetchPromise = getLatestVersion();
3114
+ fetchPromise.catch(() => {});
3115
+ latestVersion = await Promise.race([fetchPromise, new Promise((_, reject) => {
3116
+ timer = setTimeout(() => reject(/* @__PURE__ */ new Error("version check timed out")), CHECK_VERSION_TIMEOUT + 1e3);
3117
+ })]);
3069
3118
  } catch {
3070
3119
  return;
3120
+ } finally {
3121
+ clearTimeout(timer);
3071
3122
  }
3072
3123
  if (latestVersion && currVersion && semver.default.gt(latestVersion, currVersion)) console.log(`A newer version ${colors.default.cyan(latestVersion)} is available.`);
3073
3124
  }
@@ -3089,24 +3140,16 @@ const ProxyAuthError = {
3089
3140
  INVALID_TIMESTAMP: "Request timestamp is expired or invalid",
3090
3141
  INVALID_SIGNATURE_FORMAT: "Invalid x-zenstack-signature format"
3091
3142
  };
3092
- function rejectAuth(res, code) {
3093
- return res.status(401).json({
3143
+ function rejectAuth(c, code) {
3144
+ return c.json({
3094
3145
  code,
3095
3146
  message: ProxyAuthError[code]
3096
- });
3147
+ }, 401);
3097
3148
  }
3098
- /**
3099
- * Represents the identity claim embedded in the Authorization header.
3100
- * The bearer token is a plain base64-encoded JSON string.
3101
- */
3102
3149
  const UserClaimSchema = zod.z.discriminatedUnion("type", [zod.z.object({ type: zod.z.literal("superUser") }), zod.z.object({
3103
3150
  type: zod.z.literal("user"),
3104
3151
  data: zod.z.record(zod.z.string(), zod.z.unknown())
3105
3152
  })]);
3106
- /**
3107
- * Accepts a public key in either PEM format or as a raw base64 / base64url DER string
3108
- * (without the `-----BEGIN PUBLIC KEY-----` markers) and always returns a PEM string.
3109
- */
3110
3153
  function normalizePublicKey(key) {
3111
3154
  key = key.trim();
3112
3155
  if (key.startsWith("-----BEGIN PUBLIC KEY-----")) return key;
@@ -3117,21 +3160,21 @@ async function run(options) {
3117
3160
  ...options,
3118
3161
  studioAuthKey: options.studioAuthKey ?? process.env["ZENSTACK_STUDIO_AUTH_KEY"]
3119
3162
  };
3120
- if (!options.studioAuthKey) console.warn(colors.default.yellow("Warning: This proxy has no authentication. Do not expose it to the public network.\nTo secure it, get an API key from ZenStack Studio and set it via the ZENSTACK_STUDIO_AUTH_KEY environment variable."));
3121
3163
  const allowedLogLevels = ["error", "query"];
3122
3164
  const log = options.logLevel?.filter((level) => allowedLogLevels.includes(level));
3123
- const schemaFile = getSchemaFile(options.schema);
3165
+ const schemaFile = await resolveSchema(options);
3124
3166
  console.log(colors.default.gray(`Loading ZModel schema from: ${schemaFile}`));
3125
3167
  let outputPath = getOutputPath(options, schemaFile);
3126
3168
  if (!node_path.default.isAbsolute(outputPath)) outputPath = node_path.default.resolve(process.cwd(), outputPath);
3127
- const dataSource = (await loadSchemaDocument(schemaFile)).declarations.find(_zenstackhq_language_ast.isDataSource);
3169
+ const model = await loadSchemaDocument(schemaFile);
3170
+ const dataSource = model.declarations.find(_zenstackhq_language_ast.isDataSource);
3128
3171
  let databaseUrl = options.databaseUrl;
3129
3172
  if (!databaseUrl) {
3130
3173
  const schemaUrl = dataSource?.fields.find((f) => f.name === "url")?.value;
3131
3174
  if (!schemaUrl) throw new CliError(`The schema's "datasource" does not have a "url" field, please provide it with -d option.`);
3132
3175
  databaseUrl = evaluateUrl(schemaUrl);
3133
3176
  }
3134
- const dialect = await createDialect((0, _zenstackhq_language_utils.getStringLiteral)(dataSource?.fields.find((f) => f.name === "provider")?.value), databaseUrl, outputPath);
3177
+ const dialect = await createDialect((0, _zenstackhq_language_utils.getStringLiteral)(dataSource?.fields.find((f) => f.name === "provider")?.value), databaseUrl, model.$document.uri.path);
3135
3178
  const schemaModule = await (0, jiti.createJiti)(typeof __filename !== "undefined" ? __filename : require("url").pathToFileURL(__filename).href).import(node_path.default.join(outputPath, "schema"));
3136
3179
  const schema = schemaModule.schema;
3137
3180
  const omit = {};
@@ -3154,6 +3197,7 @@ async function run(options) {
3154
3197
  const authDb = db.$use(new _zenstackhq_plugin_policy.PolicyPlugin());
3155
3198
  if (options.studioAuthKey) console.log(colors.default.gray("Access policy plugin enabled for authorization."));
3156
3199
  startServer(db, schemaModule.schema, options, authDb);
3200
+ if (!options.studioAuthKey) console.warn(colors.default.yellow("Warning: This proxy has no authentication. Do not expose it to the public network.\nTo secure it, get an API key from ZenStack Studio and set it via the ZENSTACK_STUDIO_AUTH_KEY environment variable."));
3157
3201
  }
3158
3202
  function evaluateUrl(schemaUrl) {
3159
3203
  if ((0, _zenstackhq_language_ast.isLiteralExpr)(schemaUrl)) return (0, _zenstackhq_language_utils.getStringLiteral)(schemaUrl);
@@ -3174,87 +3218,69 @@ function redactDatabaseUrl(url) {
3174
3218
  return url;
3175
3219
  }
3176
3220
  }
3177
- async function createDialect(provider, databaseUrl, outputPath) {
3221
+ async function createDialect(provider, databaseUrl, schemaFilePath) {
3178
3222
  switch (provider) {
3179
3223
  case "sqlite": {
3180
3224
  let SQLite;
3181
- try {
3182
- SQLite = (await import("better-sqlite3")).default;
3183
- } catch {
3184
- throw new CliError(`Package "better-sqlite3" is required for SQLite support. Please install it with: npm install better-sqlite3`);
3185
- }
3225
+ const mod = await loadPackage("better-sqlite3");
3226
+ if (mod) SQLite = mod.default || mod;
3227
+ else throw new CliError(`Package "better-sqlite3" is required for SQLite support. Please install it with: npm install better-sqlite3`);
3186
3228
  let resolvedUrl = databaseUrl.trim();
3187
3229
  if (resolvedUrl.startsWith("file:")) {
3188
- const filePath = resolvedUrl.substring(5);
3189
- if (!node_path.default.isAbsolute(filePath)) resolvedUrl = node_path.default.join(outputPath, filePath);
3230
+ resolvedUrl = new URL(resolvedUrl, `file:${schemaFilePath}`).pathname;
3231
+ if (process.platform === "win32" && resolvedUrl[0] === "/") resolvedUrl = resolvedUrl.slice(1);
3190
3232
  }
3191
3233
  console.log(colors.default.gray(`Connecting to SQLite database at: ${resolvedUrl}`));
3192
3234
  return new _zenstackhq_orm_dialects_sqlite.SqliteDialect({ database: new SQLite(resolvedUrl) });
3193
3235
  }
3194
3236
  case "postgresql": {
3195
3237
  let PgPool;
3196
- try {
3197
- PgPool = (await import("pg")).Pool;
3198
- } catch {
3199
- throw new CliError(`Package "pg" is required for PostgreSQL support. Please install it with: npm install pg`);
3200
- }
3238
+ const mod = await loadPackage("pg");
3239
+ if (mod) PgPool = mod.Pool || mod.default?.Pool;
3240
+ else throw new CliError(`Package "pg" is required for PostgreSQL support. Please install it with: npm install pg`);
3201
3241
  console.log(colors.default.gray(`Connecting to PostgreSQL database at: ${redactDatabaseUrl(databaseUrl)}`));
3202
3242
  return new _zenstackhq_orm_dialects_postgres.PostgresDialect({ pool: new PgPool({ connectionString: databaseUrl }) });
3203
3243
  }
3204
3244
  case "mysql": {
3205
3245
  let createMysqlPool;
3206
- try {
3207
- createMysqlPool = (await import("mysql2")).createPool;
3208
- } catch {
3209
- throw new CliError(`Package "mysql2" is required for MySQL support. Please install it with: npm install mysql2`);
3210
- }
3246
+ const mod = await loadPackage("mysql2");
3247
+ if (mod) createMysqlPool = mod.createPool || mod.default?.createPool;
3248
+ else throw new CliError(`Package "mysql2" is required for MySQL support. Please install it with: npm install mysql2`);
3211
3249
  console.log(colors.default.gray(`Connecting to MySQL database at: ${redactDatabaseUrl(databaseUrl)}`));
3212
3250
  return new _zenstackhq_orm_dialects_mysql.MysqlDialect({ pool: createMysqlPool(databaseUrl) });
3213
3251
  }
3214
3252
  default: throw new CliError(`Unsupported database provider: ${provider}`);
3215
3253
  }
3216
3254
  }
3217
- function createProxyApp(client, schema, authDb, auth) {
3218
- const app = (0, express.default)();
3219
- app.use((0, cors.default)());
3220
- app.use(express.default.json({
3221
- limit: "5mb",
3222
- verify: (req, _res, buf) => {
3223
- req.rawBody = buf.toString("utf8");
3224
- }
3225
- }));
3226
- app.use(express.default.urlencoded({
3227
- extended: true,
3228
- limit: "5mb"
3229
- }));
3230
- if (auth?.studioAuthKey) {
3231
- const toleranceSecs = auth.signatureToleranceSecs;
3232
- const normalizedKey = normalizePublicKey(auth.studioAuthKey);
3233
- app.use(["/api/model", "/api/schema"], createSignatureMiddleware(normalizedKey, toleranceSecs));
3234
- }
3235
- app.use("/api/model", (0, _zenstackhq_server_express.ZenStackMiddleware)({
3236
- apiHandler: new _zenstackhq_server_api.RPCApiHandler({ schema }),
3237
- getClient: (req) => resolveClient(client, authDb, req, !!auth?.studioAuthKey)
3255
+ function createProxyApp(optionsOrClient, schema, authDb, auth) {
3256
+ let options;
3257
+ if ("client" in optionsOrClient && "schema" in optionsOrClient) options = optionsOrClient;
3258
+ else options = {
3259
+ client: optionsOrClient,
3260
+ schema,
3261
+ authDb,
3262
+ auth
3263
+ };
3264
+ const app = new hono.Hono();
3265
+ app.use("*", (0, hono_cors.cors)(options.cors));
3266
+ if (options.auth?.studioAuthKey) {
3267
+ const toleranceSecs = options.auth.signatureToleranceSecs;
3268
+ const sigMiddleware = createSignatureMiddleware(normalizePublicKey(options.auth.studioAuthKey), toleranceSecs);
3269
+ app.use("/api/model/*", sigMiddleware);
3270
+ app.use("/api/schema", sigMiddleware);
3271
+ }
3272
+ app.use("/api/model/*", (0, _zenstackhq_server_hono.createHonoHandler)({
3273
+ apiHandler: new _zenstackhq_server_api.RPCApiHandler({ schema: options.schema }),
3274
+ getClient: (c) => resolveClient(options.client, options.authDb ?? options.client, c, !!options.auth?.studioAuthKey)
3238
3275
  }));
3239
- app.get("/api/schema", (_req, res) => {
3240
- res.json({
3241
- ...schema,
3276
+ app.get("/api/schema", (c) => {
3277
+ return c.json({
3278
+ ...options.schema,
3242
3279
  zenstackVersion: getVersion()
3243
3280
  });
3244
3281
  });
3245
3282
  return app;
3246
3283
  }
3247
- /**
3248
- * Creates an Express middleware that verifies the ed25519 signature on every request.
3249
- *
3250
- * The signature header format is: `t=<unix-timestamp>,v1=<base64url-signature>`
3251
- *
3252
- * The signed message is constructed as:
3253
- * - GET requests: `<raw-query-string><timestamp>[<authorizationToken>]`
3254
- * - Other methods: `<raw-body><timestamp>[<authorizationToken>]`
3255
- *
3256
- * `authorizationToken` is the bearer token value from the `Authorization` header (if present).
3257
- */
3258
3284
  function createSignatureMiddleware(publicKey, toleranceSeconds) {
3259
3285
  let lastInvalidSigWarnAt = 0;
3260
3286
  const WARN_THROTTLE_SECS = 60;
@@ -3265,48 +3291,41 @@ function createSignatureMiddleware(publicKey, toleranceSeconds) {
3265
3291
  console.warn(colors.default.yellow("Warning: Received a request with an invalid signature. Please double-check whether you have the correct public API key configured."));
3266
3292
  }
3267
3293
  }
3268
- return (req, res, next) => {
3269
- const signatureHeader = req.headers["x-zenstack-signature"];
3270
- if (!signatureHeader || typeof signatureHeader !== "string") return rejectAuth(res, "MISSING_SIGNATURE_HEADER");
3294
+ return async (c, next) => {
3295
+ const signatureHeader = c.req.header("x-zenstack-signature");
3296
+ if (!signatureHeader) return rejectAuth(c, "MISSING_SIGNATURE_HEADER");
3271
3297
  const parts = signatureHeader.split(",");
3272
3298
  const timestampPart = parts.find((p) => p.startsWith("t="));
3273
3299
  const sigPart = parts.find((p) => p.startsWith("v1="));
3274
- if (!timestampPart || !sigPart) return rejectAuth(res, "INVALID_SIGNATURE_FORMAT");
3300
+ if (!timestampPart || !sigPart) return rejectAuth(c, "INVALID_SIGNATURE_FORMAT");
3275
3301
  const timestamp = timestampPart.substring(2);
3276
3302
  const sig = sigPart.substring(3);
3277
3303
  const requestTime = parseInt(timestamp, 10);
3278
3304
  const now = Math.floor(Date.now() / 1e3);
3279
- if (isNaN(requestTime) || Math.abs(now - requestTime) > toleranceSeconds) return rejectAuth(res, "INVALID_TIMESTAMP");
3305
+ if (isNaN(requestTime) || Math.abs(now - requestTime) > toleranceSeconds) return rejectAuth(c, "INVALID_TIMESTAMP");
3280
3306
  let payload;
3281
- if (req.method === "GET" || req.method === "DELETE") {
3282
- const qMark = req.originalUrl.indexOf("?");
3283
- payload = qMark >= 0 ? req.originalUrl.substring(qMark + 1) : "";
3284
- } else payload = req.rawBody ?? "";
3285
- const authHeader = req.headers["authorization"];
3307
+ if (c.req.method === "GET" || c.req.method === "DELETE") {
3308
+ const rawUrl = c.req.url;
3309
+ const qMark = rawUrl.indexOf("?");
3310
+ payload = qMark >= 0 ? rawUrl.substring(qMark + 1) : "";
3311
+ } else payload = await c.req.text();
3312
+ const authHeader = c.req.header("authorization");
3286
3313
  const authorizationToken = authHeader && authHeader.startsWith("Bearer ") ? authHeader.substring(7) : void 0;
3287
3314
  const message = authorizationToken ? `${payload}${timestamp}${authorizationToken}` : `${payload}${timestamp}`;
3288
3315
  try {
3289
3316
  if (!(0, node_crypto.verify)(null, Buffer.from(message, "utf8"), publicKey, Buffer.from(sig, "base64url"))) {
3290
3317
  warnInvalidSignature();
3291
- return rejectAuth(res, "INVALID_SIGNATURE_FORMAT");
3318
+ return rejectAuth(c, "INVALID_SIGNATURE_FORMAT");
3292
3319
  }
3293
3320
  } catch {
3294
3321
  warnInvalidSignature();
3295
- return rejectAuth(res, "INVALID_SIGNATURE_FORMAT");
3322
+ return rejectAuth(c, "INVALID_SIGNATURE_FORMAT");
3296
3323
  }
3297
3324
  return next();
3298
3325
  };
3299
3326
  }
3300
- /**
3301
- * Resolves the appropriate client for a request based on the Authorization header.
3302
- *
3303
- * - No studioAuthKey configured (authDb is undefined): always return the base client.
3304
- * - SuperUser claim: return the base client (full access, no policy enforcement).
3305
- * - Regular user claim: return authDb with the user identity set via $setAuth.
3306
- * - No / invalid token: return the base client.
3307
- */
3308
- function resolveClient(client, authDb, req, isAuthKeyEnabled) {
3309
- const authHeader = req.headers["authorization"];
3327
+ function resolveClient(client, authDb, c, isAuthKeyEnabled) {
3328
+ const authHeader = c.req.header("authorization");
3310
3329
  if (!isAuthKeyEnabled && !authHeader) return client;
3311
3330
  if (!authHeader?.startsWith("Bearer ")) return authDb;
3312
3331
  const token = authHeader.substring(7);
@@ -3321,10 +3340,18 @@ function resolveClient(client, authDb, req, isAuthKeyEnabled) {
3321
3340
  else return authDb.$setAuth(claim.data);
3322
3341
  }
3323
3342
  function startServer(client, schema, options, authDb) {
3324
- const server = createProxyApp(client, schema, authDb, options.studioAuthKey ? {
3325
- studioAuthKey: options.studioAuthKey,
3326
- signatureToleranceSecs: options.signatureToleranceSecs
3327
- } : void 0).listen(options.port, () => {
3343
+ const server = (0, _hono_node_server.serve)({
3344
+ fetch: createProxyApp({
3345
+ client,
3346
+ schema,
3347
+ authDb,
3348
+ auth: options.studioAuthKey ? {
3349
+ studioAuthKey: options.studioAuthKey,
3350
+ signatureToleranceSecs: options.signatureToleranceSecs
3351
+ } : void 0
3352
+ }).fetch,
3353
+ port: options.port
3354
+ }, () => {
3328
3355
  console.log(`ZenStack proxy server is running on port: ${options.port}`);
3329
3356
  console.log(`You can visit ZenStack Studio at: ${colors.default.blue("https://studio.zenstack.dev")}`);
3330
3357
  });
@@ -3348,6 +3375,121 @@ function startServer(client, schema, options, authDb) {
3348
3375
  process.exit(0);
3349
3376
  });
3350
3377
  }
3378
+ async function resolveSchema(options) {
3379
+ if (!options.introspect) try {
3380
+ return getSchemaFile(options.schema);
3381
+ } catch (err) {
3382
+ if (!(err instanceof CliError)) throw err;
3383
+ const dbFlag = !!process.env["DATABASE_URL"] ? "" : "-d <databaseUrl>";
3384
+ throw new CliError(`No ZModel schema file found in default locations.
3385
+ • If you have an existing schema file, specify it explicitly:\n npx @zenstackhq/cli studio --schema <path> ${dbFlag}\n • Otherwise, auto-generate from the database:\n npx @zenstackhq/cli studio --introspect ${dbFlag}`);
3386
+ }
3387
+ else {
3388
+ const databaseUrl = options.databaseUrl ?? process.env["DATABASE_URL"];
3389
+ if (!databaseUrl) throw new CliError("--introspect requires a database connection — pass -d <url> or set DATABASE_URL.");
3390
+ const providerType = getProviderFromUrl(databaseUrl);
3391
+ await installDbDriverPackage(providerType);
3392
+ const schemaFile = await introspectAndGenerateSchema(databaseUrl, providerType, !options.databaseUrl);
3393
+ await run$5({
3394
+ schema: schemaFile,
3395
+ silent: false,
3396
+ watch: false
3397
+ });
3398
+ console.log(colors.default.yellow("\n⚠ The generated schema has no access policies.\n All data is accessible without restriction.\n Edit " + colors.default.cyan(schemaFile) + " to add access policies.\n"));
3399
+ return schemaFile;
3400
+ }
3401
+ }
3402
+ function getProviderFromUrl(url) {
3403
+ if (url.startsWith("postgres://") || url.startsWith("postgresql://")) return "postgresql";
3404
+ if (url.startsWith("mysql://")) return "mysql";
3405
+ if (url.startsWith("file:") || url.startsWith("sqlite:")) return "sqlite";
3406
+ throw new CliError(`Unable to determine database type from URL: ${url}`);
3407
+ }
3408
+ async function installDbDriverPackage(providerType) {
3409
+ const driverPackage = (() => {
3410
+ switch (providerType) {
3411
+ case "postgresql": return {
3412
+ name: "pg",
3413
+ dev: false
3414
+ };
3415
+ case "mysql": return {
3416
+ name: "mysql2",
3417
+ dev: false
3418
+ };
3419
+ case "sqlite": return {
3420
+ name: "better-sqlite3",
3421
+ dev: false
3422
+ };
3423
+ }
3424
+ })();
3425
+ if (isPackageInstalled(driverPackage.name)) return;
3426
+ let pm = await (0, package_manager_detector.detect)();
3427
+ if (!pm) pm = {
3428
+ agent: "npm",
3429
+ name: "npm"
3430
+ };
3431
+ console.log(colors.default.gray(`Using package manager: ${pm.agent}`));
3432
+ const resolved = (0, package_manager_detector.resolveCommand)(pm.agent, "add", [driverPackage.name, ...driverPackage.dev ? [pm.agent.startsWith("yarn") || pm.agent === "bun" ? "--dev" : "--save-dev"] : []]);
3433
+ if (!resolved) throw new CliError(`Unable to determine how to install package "${driverPackage.name}". Please install it manually.`);
3434
+ const spinner = (0, ora.default)(`Installing "${driverPackage.name}"`).start();
3435
+ try {
3436
+ execSync$1(`${resolved.command} ${resolved.args.join(" ")}`, { cwd: process.cwd() });
3437
+ spinner.succeed();
3438
+ } catch (e) {
3439
+ spinner.fail();
3440
+ throw e;
3441
+ }
3442
+ }
3443
+ function adjustSqliteUrlForSchema(url) {
3444
+ let prefix = "";
3445
+ let filePath = url;
3446
+ if (url.startsWith("file:")) {
3447
+ prefix = "file:";
3448
+ filePath = url.substring(5);
3449
+ } else if (url.startsWith("sqlite:")) {
3450
+ prefix = "sqlite:";
3451
+ filePath = url.substring(7);
3452
+ }
3453
+ if (!node_path.default.isAbsolute(filePath)) {
3454
+ const adjustedPath = node_path.default.join("..", filePath).replace(/\\/g, "/");
3455
+ return {
3456
+ isRelative: true,
3457
+ adjustedUrl: `${prefix}${adjustedPath}`
3458
+ };
3459
+ }
3460
+ return {
3461
+ isRelative: false,
3462
+ adjustedUrl: url
3463
+ };
3464
+ }
3465
+ async function introspectAndGenerateSchema(databaseUrl, providerType, urlFromEnv) {
3466
+ let urlExpr;
3467
+ if (providerType === "sqlite") {
3468
+ const { isRelative, adjustedUrl } = adjustSqliteUrlForSchema(databaseUrl);
3469
+ if (isRelative) {
3470
+ urlExpr = `'${adjustedUrl}'`;
3471
+ databaseUrl = adjustedUrl;
3472
+ } else urlExpr = urlFromEnv ? "env(\"DATABASE_URL\")" : `'${databaseUrl}'`;
3473
+ } else urlExpr = urlFromEnv ? "env(\"DATABASE_URL\")" : `'${databaseUrl}'`;
3474
+ const minimalSchema = `datasource db {\n provider = '${providerType}'\n url = ${urlExpr}\n}\n`;
3475
+ const schemaDir = node_path.default.resolve("zenstack");
3476
+ const schemaFile = node_path.default.join(schemaDir, "schema.zmodel");
3477
+ node_fs.default.mkdirSync(schemaDir, { recursive: true });
3478
+ node_fs.default.writeFileSync(schemaFile, minimalSchema, "utf-8");
3479
+ await runPull({
3480
+ schema: schemaFile,
3481
+ output: schemaFile,
3482
+ databaseUrl,
3483
+ provider: providerType,
3484
+ modelCasing: "pascal",
3485
+ fieldCasing: "none",
3486
+ alwaysMap: false,
3487
+ quote: "single",
3488
+ indent: 4
3489
+ });
3490
+ console.log(colors.default.green(`\n✅ Schema generated: ${colors.default.cyan(schemaFile)}`));
3491
+ return schemaFile;
3492
+ }
3351
3493
  //#endregion
3352
3494
  //#region src/utils/is-ci.ts
3353
3495
  const isInCi = node_process.env["CI"] !== "0" && node_process.env["CI"] !== "false" && ("CI" in node_process.env || "CONTINUOUS_INTEGRATION" in node_process.env || Object.keys(node_process.env).some((key) => key.startsWith("CI_")));
@@ -3603,7 +3745,7 @@ Arguments following -- are passed to the seed script. E.g.: "zen db seed -- --us
3603
3745
  const parsed = parseInt(v, 10);
3604
3746
  if (isNaN(parsed) || parsed < 0) throw new CliError(`--signatureToleranceSecs must be a positive integer, got: ${v}`);
3605
3747
  return parsed;
3606
- })).addOption(noVersionCheckOption).action(proxyAction);
3748
+ })).addOption(new commander.Option("--introspect", "Introspect the database to generate a schema when no schema file is found")).addOption(noVersionCheckOption).action(proxyAction);
3607
3749
  program.addHelpCommand("help [command]", "Display help for a command");
3608
3750
  program.hook("preAction", async (_thisCommand, actionCommand) => {
3609
3751
  if (actionCommand.getOptionValue("versionCheck") !== false) await checkNewVersion();