@orizm/cli 1.0.1 → 1.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/bin/index.js +1 -1
  2. package/dist/cli.js +575 -142
  3. package/package.json +6 -7
package/bin/index.js CHANGED
@@ -1,3 +1,3 @@
1
1
  #!/usr/bin/env node
2
2
 
3
- require("../dist/cli.js");
3
+ import "../dist/cli.js";
package/dist/cli.js CHANGED
@@ -1,39 +1,15 @@
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 __copyProps = (to, from, except, desc) => {
9
- if (from && typeof from === "object" || typeof from === "function") {
10
- for (let key of __getOwnPropNames(from))
11
- if (!__hasOwnProp.call(to, key) && key !== except)
12
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
13
- }
14
- return to;
15
- };
16
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
17
- // If the importer is in node compatibility mode or this is not an ESM
18
- // file that has been converted to a CommonJS file using a Babel-
19
- // compatible transform (i.e. "__esModule" has not been set), then set
20
- // "default" to the CommonJS "module.exports" for node compatibility.
21
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
22
- mod
23
- ));
24
-
25
1
  // src/cli.ts
26
- var import_commander6 = require("commander");
2
+ import { Command as Command6, program } from "commander";
27
3
 
28
4
  // src/cms/generate/command.ts
29
- var import_commander = require("commander");
5
+ import { Command } from "commander";
30
6
 
31
7
  // src/lib/load-config.ts
32
- var import_esbuild = __toESM(require("esbuild"));
33
- var import_config_validator = require("@orizm/common/config-validator");
34
- var v = __toESM(require("valibot"));
8
+ import esbuild from "esbuild";
9
+ import { OrizmConfigDef } from "@orizm/common/config-validator";
10
+ import * as v from "valibot";
35
11
  async function loadConfig(configFile) {
36
- const buildResult = await import_esbuild.default.build({
12
+ const buildResult = await esbuild.build({
37
13
  entryPoints: [configFile],
38
14
  bundle: true,
39
15
  write: false,
@@ -45,16 +21,16 @@ async function loadConfig(configFile) {
45
21
  buildResult.outputFiles[0].text
46
22
  )}`;
47
23
  const { default: orizmConfigRaw } = await import(moduleURL);
48
- return v.parse(import_config_validator.OrizmConfigDef, orizmConfigRaw);
24
+ return v.parse(OrizmConfigDef, orizmConfigRaw);
49
25
  }
50
26
 
51
27
  // src/lib/cli-spinner.ts
52
- var import_readline = __toESM(require("readline"));
28
+ import readline from "readline";
53
29
 
54
30
  // src/lib/cli-symbol.ts
55
- var import_cli_color = require("cli-color");
56
- var success = (0, import_cli_color.green)("\u2713");
57
- var error = (0, import_cli_color.red)("\u2717");
31
+ import cliColor from "cli-color";
32
+ var success = cliColor.green("\u2713");
33
+ var error = cliColor.red("\u2717");
58
34
 
59
35
  // src/lib/cli-cursor.ts
60
36
  function hide() {
@@ -97,8 +73,8 @@ var Spinner = class {
97
73
  clearInterval(this.timer);
98
74
  this.timer = null;
99
75
  }
100
- import_readline.default.clearLine(process.stdout, 0);
101
- import_readline.default.cursorTo(process.stdout, 0);
76
+ readline.clearLine(process.stdout, 0);
77
+ readline.cursorTo(process.stdout, 0);
102
78
  show();
103
79
  return this;
104
80
  }
@@ -110,8 +86,8 @@ var Spinner = class {
110
86
  render() {
111
87
  const frame = FRAMES[this.currentFrame];
112
88
  this.currentFrame = (this.currentFrame + 1) % FRAMES.length;
113
- import_readline.default.clearLine(process.stdout, 0);
114
- import_readline.default.cursorTo(process.stdout, 0);
89
+ readline.clearLine(process.stdout, 0);
90
+ readline.cursorTo(process.stdout, 0);
115
91
  process.stdout.write(`${frame} ${this.text}`);
116
92
  }
117
93
  };
@@ -120,8 +96,8 @@ function createSpinner() {
120
96
  }
121
97
 
122
98
  // src/lib/handle-error.ts
123
- var v2 = __toESM(require("valibot"));
124
- var cliColor = __toESM(require("cli-color"));
99
+ import * as v2 from "valibot";
100
+ import cliColor2 from "cli-color";
125
101
  function handleError(error2) {
126
102
  show();
127
103
  if (v2.isValiError(error2)) {
@@ -133,7 +109,7 @@ function handleError(error2) {
133
109
  }
134
110
  console.error();
135
111
  console.error(
136
- cliColor.red(
112
+ cliColor2.red(
137
113
  "Something went wrong. Please check the error below for more details."
138
114
  )
139
115
  );
@@ -144,31 +120,31 @@ function handleError(error2) {
144
120
  }
145
121
  function buildValiErrorMessage(e) {
146
122
  return e.issues.map((issue) => {
147
- return ` ${cliColor.red(issue.message)} (at ${cliColor.yellow(v2.getDotPath(issue))})`;
123
+ return ` ${cliColor2.red(issue.message)} (at ${cliColor2.yellow(v2.getDotPath(issue))})`;
148
124
  }).join("\n");
149
125
  }
150
126
 
151
127
  // src/cms/generate/generator.ts
152
- var import_promises = require("fs/promises");
153
- var import_path = __toESM(require("path"));
154
- var import_handlebars = __toESM(require("handlebars"));
128
+ import { mkdir, writeFile } from "fs/promises";
129
+ import path from "path";
130
+ import Handlebars from "handlebars";
155
131
 
156
132
  // src/cms/templates/types.ts.hbr
157
- var types_ts_default = '// This file was automatically generated and should not be edited.\n\nimport { FormValidationRules, StorageItemType } from "@orizm/common";\n\n// Utilities\ntype _ModuleRef<T> = T & _ModuleDescriptor;\ntype _ModuleDescriptor = {\n isModule: true;\n};\ntype _ArrayModuleRef<T> = T & _ArrayModuleDescriptor;\ntype _ArrayModuleDescriptor = {\n isModuleArray: true;\n};\n\n// Tables\n{{#each tables}}\nexport type {{toCodeTypeName this.name}} = {\n id: string;\n createdAt: string;\n updatedAt: string;\n {{#unless this.isSubmissions}}\n group?: string;\n publishedAt?: string;\n _draft?: boolean;\n _published?: boolean;\n scheduledPublishAt?: string | null;\n scheduledUnpublishAt?: string | null;\n {{else}}\n _formId: string;\n _content: unknown;\n _formSchema: unknown;\n _attachments: StorageItemType[];\n {{/unless}}\n {{#each this.columns}}\n {{this.name}}{{#unless this.required}}?{{/unless}}: {{typeName this}};\n {{/each}}\n {{#if this.enableForm}}\n formSchema: FormValidationRules;\n {{/if}}\n};\n\nexport type {{toCodeTypeName this.name}}CreateInput = {\n {{#unless this.isSubmissions}}\n group?: string;\n publishedAt?: string;\n scheduledPublishAt?: string | null;\n scheduledUnpublishAt?: string | null;\n createdAt?: string;\n {{/unless}}\n {{#each this.columns}}\n {{this.name}}{{#unless this.required}}?{{/unless}}: {{typeName this}};\n {{/each}}\n {{#if this.enableForm}}\n formSchema: FormValidationRules;\n {{/if}}\n};\n\nexport type {{toCodeTypeName this.name}}UpdateInput = {\n {{#each this.columns}}\n {{#unless this.readOnly}}{{this.name}}?: {{typeName this}}{{#unless this.required}} | null{{/unless}};{{/unless}}\n {{/each}}\n {{#unless this.isSubmissions}}\n publishedAt?: string;\n scheduledPublishAt?: string | null;\n scheduledUnpublishAt?: string | null;\n createdAt?: string;\n {{/unless}}\n {{#if this.enableForm}}\n formSchema: FormValidationRules;\n {{/if}}\n};\n{{/each}}\n\n// Module types\n{{#each tableModules}}\nexport type {{toCodeTypeName this.name}} = {\n id?: string;\n {{#each this.columns}}\n {{this.name}}{{#unless this.required}}?{{/unless}}: {{typeName this}};\n {{/each}}\n};\n{{/each}}\n\n\n// Descriptor types\n{{#each tables}}\nexport type {{toCodeTypeName this.name}}__Descriptor = {\n row: {{toCodeTypeName this.name}};\n create: {{toCodeTypeName this.name}}CreateInput;\n update: {{toCodeTypeName this.name}}UpdateInput;\n {{#if (filterRefColumn this.columns)}}\n refs: {\n {{#each (filterRefColumn this.columns)}}\n {{includeName this}}: {{{includeType this}}};\n {{/each}}\n }\n {{/if}}\n {{#unless (filterRefColumn this.columns)}}\n refs: object;\n {{/unless}}\n {{#if (filterUniqueIndexes this.indexes)}}\n unique: [\n {{#each (filterUniqueIndexes this.indexes)}}\n { {{#each (getIndexColumns ../this this)}}{{this.name}}:{{typeName this}},{{/each}} },\n {{/each}}\n ]\n {{/if}}\n {{#unless (filterUniqueIndexes this.indexes)}}\n unique: [];\n {{/unless}}\n {{#if this.enableDrafts}}\n enableDrafts: true;\n {{/if}}\n {{#if this.enableForm}}\n submissionDescriptor: {{toCodeTypeName this.name}}_Submission__Descriptor;\n {{else}}\n submissionDescriptor: never;\n {{/if}}\n};\n{{/each}}\n\n\n{{#each tableModules}}\nexport type {{toCodeTypeName this.name}}__Descriptor = {\n row: {{toCodeTypeName this.name}};\n {{#if (filterRefColumn this.columns)}}\n refs: {\n {{#each (filterRefColumn this.columns)}}\n {{includeName this}}: {{{includeType this}}};\n {{/each}}\n }\n {{/if}}\n {{#unless (filterRefColumn this.columns)}}\n refs: object;\n {{/unless}}\n unique:[]\n};\n{{/each}}\n\n\n// Webhook types\nexport type WebhookEvent = "content.create" | "content.update" | "content.delete";\nexport type WebhookPayload = {\n event: WebhookEvent;\n timestamp: string;\n project: string;\n} & (\n {{#each tables}}\n | {\n table: "{{this.name}}";\n content: {{toCodeTypeName this.name}};\n old?: {{toCodeTypeName this.name}};\n }\n {{/each}}\n)\n';
133
+ var types_ts_default = '// This file was automatically generated and should not be edited.\n\nimport { FormValidationRules, StorageItemType } from "@orizm/common";\n\n// Utilities\ntype _ModuleRef<T> = T & _ModuleDescriptor;\ntype _ModuleDescriptor = {\n isModule: true;\n};\ntype _ArrayModuleRef<T> = T & _ArrayModuleDescriptor;\ntype _ArrayModuleDescriptor = {\n isModuleArray: true;\n};\n\n// Tables\n{{#each tables}}\nexport type {{toCodeTypeName this.name}} = {\n id: string;\n createdAt: string;\n updatedAt: string;\n {{#unless this.isSubmissions}}\n group?: string;\n publishedAt?: string;\n _draft?: boolean;\n _published?: boolean;\n scheduledPublishAt?: string | null;\n scheduledUnpublishAt?: string | null;\n {{else}}\n _formId: string;\n _content: unknown;\n _formSchema: unknown;\n _attachments: StorageItemType[];\n {{/unless}}\n {{#each this.columns}}\n {{this.name}}{{#unless this.required}}?{{/unless}}: {{typeName this}};\n {{/each}}\n {{#if this.enableForm}}\n formSchema: FormValidationRules;\n {{/if}}\n};\n\nexport type {{toCodeTypeName this.name}}CreateInput = {\n {{#unless this.isSubmissions}}\n group?: string;\n publishedAt?: string;\n scheduledPublishAt?: string | null;\n scheduledUnpublishAt?: string | null;\n createdAt?: string;\n {{/unless}}\n {{#each this.columns}}\n {{this.name}}{{#unless this.required}}?{{/unless}}: {{typeName this}};\n {{/each}}\n {{#if this.enableForm}}\n formSchema: FormValidationRules;\n {{/if}}\n};\n\nexport type {{toCodeTypeName this.name}}UpdateInput = {\n {{#each this.columns}}\n {{#unless this.readOnly}}{{this.name}}?: {{typeName this}}{{#unless this.required}} | null{{/unless}};{{/unless}}\n {{/each}}\n {{#unless this.isSubmissions}}\n publishedAt?: string;\n scheduledPublishAt?: string | null;\n scheduledUnpublishAt?: string | null;\n createdAt?: string;\n {{/unless}}\n {{#if this.enableForm}}\n formSchema: FormValidationRules;\n {{/if}}\n};\n{{/each}}\n\n// Module types\n{{#each tableModules}}\nexport type {{toCodeTypeName this.name}} = {\n id?: string;\n {{#each this.columns}}\n {{this.name}}{{#unless this.required}}?{{/unless}}: {{typeName this}};\n {{/each}}\n};\n{{/each}}\n\n\n// Descriptor types\n{{#each tables}}\nexport type {{toCodeTypeName this.name}}__Descriptor = {\n row: {{toCodeTypeName this.name}};\n create: {{toCodeTypeName this.name}}CreateInput;\n update: {{toCodeTypeName this.name}}UpdateInput;\n {{#if (filterRefColumn this.columns)}}\n refs: {\n {{#each (filterRefColumn this.columns)}}\n {{includeName this}}: {{{includeType this}}};\n {{/each}}\n }\n {{/if}}\n {{#unless (filterRefColumn this.columns)}}\n refs: object;\n {{/unless}}\n {{#if (filterUniqueIndexes this.indexes)}}\n unique: [\n {{#each (filterUniqueIndexes this.indexes)}}\n { {{#each (getIndexColumns ../this this)}}{{this.name}}:{{typeName this}},{{/each}} },\n {{/each}}\n ]\n {{/if}}\n {{#unless (filterUniqueIndexes this.indexes)}}\n unique: [];\n {{/unless}}\n {{#if this.enableDrafts}}\n enableDrafts: true;\n {{/if}}\n {{#if this.enableForm}}\n submissionDescriptor: {{toCodeTypeName this.name}}_Submission__Descriptor;\n {{else}}\n submissionDescriptor: never;\n {{/if}}\n};\n{{/each}}\n\n\n{{#each tableModules}}\nexport type {{toCodeTypeName this.name}}__Descriptor = {\n row: {{toCodeTypeName this.name}};\n {{#if (filterRefColumn this.columns)}}\n refs: {\n {{#each (filterRefColumn this.columns)}}\n {{includeName this}}: {{{includeType this}}};\n {{/each}}\n }\n {{/if}}\n {{#unless (filterRefColumn this.columns)}}\n refs: object;\n {{/unless}}\n unique:[]\n};\n{{/each}}\n\n\n// Webhook types\nexport type WebhookEvent = "content.create" | "content.update" | "content.delete";\ntype WebhookPayloadBase = {\n event: WebhookEvent;\n timestamp: string;\n project: string;\n};\n{{#if tables}}\nexport type WebhookPayload = WebhookPayloadBase & (\n {{#each tables}}\n | {\n table: "{{this.name}}";\n content: {{toCodeTypeName this.name}};\n old?: {{toCodeTypeName this.name}};\n }\n {{/each}}\n);\n{{else}}\nexport type WebhookPayload = WebhookPayloadBase;\n{{/if}}\n';
158
134
 
159
135
  // src/cms/templates/client.ts.hbr
160
136
  var client_ts_default = '// This file was automatically generated and should not be edited.\n\nimport { OrizmCMSClient } from "@orizm/cms-sdk";\n\nimport * as Models from "./types";\n\nexport class CMSClient {\n constructor(protected client: OrizmCMSClient) {\n this.tables = {\n {{#each tables}}\n {{toEndpointName this.name}}: this.client.getTableClient<Models.{{toCodeTypeName this.name}}__Descriptor>("{{toEndpointName this.name}}"),\n {{/each}}\n };\n\n this.buckets = {\n {{#each buckets}}\n {{toEndpointName this.name}}: this.client.getBucketClient("{{toEndpointName this.name}}"),\n {{/each}}\n };\n\n this.userManagement = this.client.userManagement;\n \n this.userinfo = this.client.userinfo;\n \n this.auth = this.client.auth;\n }\n\n readonly tables;\n readonly buckets;\n readonly userManagement;\n readonly userinfo;\n readonly auth;\n}\n';
161
137
 
162
138
  // src/cms/generate/generator.ts
163
- import_handlebars.default.registerHelper("toEndpointName", (str) => {
139
+ Handlebars.registerHelper("toEndpointName", (str) => {
164
140
  return str;
165
141
  });
166
142
  function toCodeTypeName(str) {
167
143
  str = str.charAt(0).toUpperCase() + str.slice(1);
168
144
  return str.replace(/_([a-z])/g, (g) => g[1].toUpperCase());
169
145
  }
170
- import_handlebars.default.registerHelper("toCodeTypeName", toCodeTypeName);
171
- import_handlebars.default.registerHelper(
146
+ Handlebars.registerHelper("toCodeTypeName", toCodeTypeName);
147
+ Handlebars.registerHelper(
172
148
  "typeName",
173
149
  (column) => {
174
150
  if (column.type === "reference") {
@@ -186,7 +162,7 @@ import_handlebars.default.registerHelper(
186
162
  }
187
163
  }
188
164
  );
189
- import_handlebars.default.registerHelper(
165
+ Handlebars.registerHelper(
190
166
  "filterRefColumn",
191
167
  (columns) => {
192
168
  return (columns || []).filter(
@@ -194,13 +170,13 @@ import_handlebars.default.registerHelper(
194
170
  );
195
171
  }
196
172
  );
197
- import_handlebars.default.registerHelper(
173
+ Handlebars.registerHelper(
198
174
  "includeName",
199
175
  (column) => {
200
176
  return column.type === "reference" ? column.includeName : column.name;
201
177
  }
202
178
  );
203
- import_handlebars.default.registerHelper(
179
+ Handlebars.registerHelper(
204
180
  "includeType",
205
181
  (column) => {
206
182
  if (column.type === "reference")
@@ -213,13 +189,13 @@ import_handlebars.default.registerHelper(
213
189
  )}__Descriptor>`;
214
190
  }
215
191
  );
216
- import_handlebars.default.registerHelper(
192
+ Handlebars.registerHelper(
217
193
  "filterUniqueIndexes",
218
194
  (indexes) => {
219
195
  return (indexes || []).filter((i) => i.unique);
220
196
  }
221
197
  );
222
- import_handlebars.default.registerHelper(
198
+ Handlebars.registerHelper(
223
199
  "getIndexColumns",
224
200
  (table, index) => {
225
201
  return index.columns.map((i) => {
@@ -232,8 +208,8 @@ import_handlebars.default.registerHelper(
232
208
  }
233
209
  );
234
210
  async function generate(options) {
235
- const config = options.projectDef;
236
- await (0, import_promises.mkdir)(options.output, { recursive: true });
211
+ const config = options.config;
212
+ await mkdir(options.output, { recursive: true });
237
213
  await renderTypes(config, options.output);
238
214
  await renderClient(config, options.output);
239
215
  }
@@ -247,26 +223,26 @@ async function renderTypes(config, output) {
247
223
  ...config,
248
224
  tables: [...config.tables, ...submissionTables]
249
225
  };
250
- const rendered = import_handlebars.default.compile(types_ts_default)(renderParams);
251
- const targetPath = import_path.default.join(output, "types.ts");
252
- await (0, import_promises.writeFile)(targetPath, rendered, "utf-8");
226
+ const rendered = Handlebars.compile(types_ts_default)(renderParams);
227
+ const targetPath = path.join(output, "types.ts");
228
+ await writeFile(targetPath, rendered, "utf-8");
253
229
  }
254
230
  async function renderClient(config, output) {
255
- const rendered = import_handlebars.default.compile(client_ts_default)(config);
256
- const targetPath = import_path.default.join(output, "client.ts");
257
- await (0, import_promises.writeFile)(targetPath, rendered, "utf-8");
231
+ const rendered = Handlebars.compile(client_ts_default)(config);
232
+ const targetPath = path.join(output, "client.ts");
233
+ await writeFile(targetPath, rendered, "utf-8");
258
234
  }
259
235
 
260
236
  // src/cms/generate/command.ts
261
237
  var spinner = createSpinner();
262
- var cmsGenerateCommand = new import_commander.Command("generate").description("generate orizm client and types.").option("-c, --config <path>", "orizm config file path.", "orizm.config.ts").option("-o, --output <path>", "output directory.", "./src/orizm").action(async (options) => {
238
+ var cmsGenerateCommand = new Command("generate").description("generate orizm client and types.").option("-c, --config <path>", "orizm config file path.", "orizm.config.ts").option("-o, --output <path>", "output directory.", "./src/orizm").action(async (options) => {
263
239
  try {
264
240
  spinner.start("Loading project schema...");
265
- const projectDef = await loadConfig(options.config);
241
+ const config = await loadConfig(options.config);
266
242
  spinner.succeed("Loaded project schema.");
267
243
  spinner.start("Generating code...");
268
244
  await generate({
269
- projectDef,
245
+ config,
270
246
  output: options.output
271
247
  });
272
248
  spinner.succeed(`Generated code to '${options.output}'`);
@@ -276,38 +252,493 @@ var cmsGenerateCommand = new import_commander.Command("generate").description("g
276
252
  });
277
253
 
278
254
  // src/cms/pull/command.ts
279
- var import_commander2 = require("commander");
255
+ import { Command as Command2 } from "commander";
280
256
 
281
- // src/api/developer-api-client.ts
282
- var import_openapi_fetch = __toESM(require("openapi-fetch"));
283
- function createDeveloperAPIClient(baseUrl, apiKey) {
284
- const url = new URL(baseUrl);
285
- url.pathname = `/api/dev/v1`;
286
- return (0, import_openapi_fetch.default)({
287
- baseUrl: url.toString(),
288
- headers: {
289
- "x-api-key": apiKey
257
+ // ../../node_modules/.pnpm/openapi-fetch@0.13.5/node_modules/openapi-fetch/dist/index.js
258
+ var PATH_PARAM_RE = /\{[^{}]+\}/g;
259
+ var supportsRequestInitExt = () => {
260
+ return typeof process === "object" && Number.parseInt(process?.versions?.node?.substring(0, 2)) >= 18 && process.versions.undici;
261
+ };
262
+ function randomID() {
263
+ return Math.random().toString(36).slice(2, 11);
264
+ }
265
+ function createClient(clientOptions) {
266
+ let {
267
+ baseUrl = "",
268
+ Request: CustomRequest = globalThis.Request,
269
+ fetch: baseFetch = globalThis.fetch,
270
+ querySerializer: globalQuerySerializer,
271
+ bodySerializer: globalBodySerializer,
272
+ headers: baseHeaders,
273
+ requestInitExt = void 0,
274
+ ...baseOptions
275
+ } = { ...clientOptions };
276
+ requestInitExt = supportsRequestInitExt() ? requestInitExt : void 0;
277
+ baseUrl = removeTrailingSlash(baseUrl);
278
+ const middlewares = [];
279
+ async function coreFetch(schemaPath, fetchOptions) {
280
+ const {
281
+ baseUrl: localBaseUrl,
282
+ fetch = baseFetch,
283
+ Request = CustomRequest,
284
+ headers,
285
+ params = {},
286
+ parseAs = "json",
287
+ querySerializer: requestQuerySerializer,
288
+ bodySerializer = globalBodySerializer ?? defaultBodySerializer,
289
+ body,
290
+ ...init
291
+ } = fetchOptions || {};
292
+ if (localBaseUrl) {
293
+ baseUrl = removeTrailingSlash(localBaseUrl);
294
+ }
295
+ let querySerializer = typeof globalQuerySerializer === "function" ? globalQuerySerializer : createQuerySerializer(globalQuerySerializer);
296
+ if (requestQuerySerializer) {
297
+ querySerializer = typeof requestQuerySerializer === "function" ? requestQuerySerializer : createQuerySerializer({
298
+ ...typeof globalQuerySerializer === "object" ? globalQuerySerializer : {},
299
+ ...requestQuerySerializer
300
+ });
301
+ }
302
+ const serializedBody = body === void 0 ? void 0 : bodySerializer(body);
303
+ const defaultHeaders = (
304
+ // with no body, we should not to set Content-Type
305
+ serializedBody === void 0 || // if serialized body is FormData; browser will correctly set Content-Type & boundary expression
306
+ serializedBody instanceof FormData ? {} : {
307
+ "Content-Type": "application/json"
308
+ }
309
+ );
310
+ const requestInit = {
311
+ redirect: "follow",
312
+ ...baseOptions,
313
+ ...init,
314
+ body: serializedBody,
315
+ headers: mergeHeaders(defaultHeaders, baseHeaders, headers, params.header)
316
+ };
317
+ let id;
318
+ let options;
319
+ let request = new CustomRequest(createFinalURL(schemaPath, { baseUrl, params, querySerializer }), requestInit);
320
+ let response;
321
+ for (const key in init) {
322
+ if (!(key in request)) {
323
+ request[key] = init[key];
324
+ }
325
+ }
326
+ if (middlewares.length) {
327
+ id = randomID();
328
+ options = Object.freeze({
329
+ baseUrl,
330
+ fetch,
331
+ parseAs,
332
+ querySerializer,
333
+ bodySerializer
334
+ });
335
+ for (const m of middlewares) {
336
+ if (m && typeof m === "object" && typeof m.onRequest === "function") {
337
+ const result = await m.onRequest({
338
+ request,
339
+ schemaPath,
340
+ params,
341
+ options,
342
+ id
343
+ });
344
+ if (result) {
345
+ if (result instanceof CustomRequest) {
346
+ request = result;
347
+ } else if (result instanceof Response) {
348
+ response = result;
349
+ break;
350
+ } else {
351
+ throw new Error("onRequest: must return new Request() or Response() when modifying the request");
352
+ }
353
+ }
354
+ }
355
+ }
356
+ }
357
+ if (!response) {
358
+ try {
359
+ response = await fetch(request, requestInitExt);
360
+ } catch (error3) {
361
+ let errorAfterMiddleware = error3;
362
+ if (middlewares.length) {
363
+ for (let i = middlewares.length - 1; i >= 0; i--) {
364
+ const m = middlewares[i];
365
+ if (m && typeof m === "object" && typeof m.onError === "function") {
366
+ const result = await m.onError({
367
+ request,
368
+ error: errorAfterMiddleware,
369
+ schemaPath,
370
+ params,
371
+ options,
372
+ id
373
+ });
374
+ if (result) {
375
+ if (result instanceof Response) {
376
+ errorAfterMiddleware = void 0;
377
+ response = result;
378
+ break;
379
+ }
380
+ if (result instanceof Error) {
381
+ errorAfterMiddleware = result;
382
+ continue;
383
+ }
384
+ throw new Error("onError: must return new Response() or instance of Error");
385
+ }
386
+ }
387
+ }
388
+ }
389
+ if (errorAfterMiddleware) {
390
+ throw errorAfterMiddleware;
391
+ }
392
+ }
393
+ if (middlewares.length) {
394
+ for (let i = middlewares.length - 1; i >= 0; i--) {
395
+ const m = middlewares[i];
396
+ if (m && typeof m === "object" && typeof m.onResponse === "function") {
397
+ const result = await m.onResponse({
398
+ request,
399
+ response,
400
+ schemaPath,
401
+ params,
402
+ options,
403
+ id
404
+ });
405
+ if (result) {
406
+ if (!(result instanceof Response)) {
407
+ throw new Error("onResponse: must return new Response() when modifying the response");
408
+ }
409
+ response = result;
410
+ }
411
+ }
412
+ }
413
+ }
414
+ }
415
+ if (response.status === 204 || response.headers.get("Content-Length") === "0") {
416
+ return response.ok ? { data: void 0, response } : { error: void 0, response };
417
+ }
418
+ if (response.ok) {
419
+ if (parseAs === "stream") {
420
+ return { data: response.body, response };
421
+ }
422
+ return { data: await response[parseAs](), response };
290
423
  }
424
+ let error2 = await response.text();
425
+ try {
426
+ error2 = JSON.parse(error2);
427
+ } catch {
428
+ }
429
+ return { error: error2, response };
430
+ }
431
+ return {
432
+ request(method, url, init) {
433
+ return coreFetch(url, { ...init, method: method.toUpperCase() });
434
+ },
435
+ /** Call a GET endpoint */
436
+ GET(url, init) {
437
+ return coreFetch(url, { ...init, method: "GET" });
438
+ },
439
+ /** Call a PUT endpoint */
440
+ PUT(url, init) {
441
+ return coreFetch(url, { ...init, method: "PUT" });
442
+ },
443
+ /** Call a POST endpoint */
444
+ POST(url, init) {
445
+ return coreFetch(url, { ...init, method: "POST" });
446
+ },
447
+ /** Call a DELETE endpoint */
448
+ DELETE(url, init) {
449
+ return coreFetch(url, { ...init, method: "DELETE" });
450
+ },
451
+ /** Call a OPTIONS endpoint */
452
+ OPTIONS(url, init) {
453
+ return coreFetch(url, { ...init, method: "OPTIONS" });
454
+ },
455
+ /** Call a HEAD endpoint */
456
+ HEAD(url, init) {
457
+ return coreFetch(url, { ...init, method: "HEAD" });
458
+ },
459
+ /** Call a PATCH endpoint */
460
+ PATCH(url, init) {
461
+ return coreFetch(url, { ...init, method: "PATCH" });
462
+ },
463
+ /** Call a TRACE endpoint */
464
+ TRACE(url, init) {
465
+ return coreFetch(url, { ...init, method: "TRACE" });
466
+ },
467
+ /** Register middleware */
468
+ use(...middleware) {
469
+ for (const m of middleware) {
470
+ if (!m) {
471
+ continue;
472
+ }
473
+ if (typeof m !== "object" || !("onRequest" in m || "onResponse" in m || "onError" in m)) {
474
+ throw new Error("Middleware must be an object with one of `onRequest()`, `onResponse() or `onError()`");
475
+ }
476
+ middlewares.push(m);
477
+ }
478
+ },
479
+ /** Unregister middleware */
480
+ eject(...middleware) {
481
+ for (const m of middleware) {
482
+ const i = middlewares.indexOf(m);
483
+ if (i !== -1) {
484
+ middlewares.splice(i, 1);
485
+ }
486
+ }
487
+ }
488
+ };
489
+ }
490
+ function serializePrimitiveParam(name, value, options) {
491
+ if (value === void 0 || value === null) {
492
+ return "";
493
+ }
494
+ if (typeof value === "object") {
495
+ throw new Error(
496
+ "Deeply-nested arrays/objects aren\u2019t supported. Provide your own `querySerializer()` to handle these."
497
+ );
498
+ }
499
+ return `${name}=${options?.allowReserved === true ? value : encodeURIComponent(value)}`;
500
+ }
501
+ function serializeObjectParam(name, value, options) {
502
+ if (!value || typeof value !== "object") {
503
+ return "";
504
+ }
505
+ const values = [];
506
+ const joiner = {
507
+ simple: ",",
508
+ label: ".",
509
+ matrix: ";"
510
+ }[options.style] || "&";
511
+ if (options.style !== "deepObject" && options.explode === false) {
512
+ for (const k in value) {
513
+ values.push(k, options.allowReserved === true ? value[k] : encodeURIComponent(value[k]));
514
+ }
515
+ const final2 = values.join(",");
516
+ switch (options.style) {
517
+ case "form": {
518
+ return `${name}=${final2}`;
519
+ }
520
+ case "label": {
521
+ return `.${final2}`;
522
+ }
523
+ case "matrix": {
524
+ return `;${name}=${final2}`;
525
+ }
526
+ default: {
527
+ return final2;
528
+ }
529
+ }
530
+ }
531
+ for (const k in value) {
532
+ const finalName = options.style === "deepObject" ? `${name}[${k}]` : k;
533
+ values.push(serializePrimitiveParam(finalName, value[k], options));
534
+ }
535
+ const final = values.join(joiner);
536
+ return options.style === "label" || options.style === "matrix" ? `${joiner}${final}` : final;
537
+ }
538
+ function serializeArrayParam(name, value, options) {
539
+ if (!Array.isArray(value)) {
540
+ return "";
541
+ }
542
+ if (options.explode === false) {
543
+ const joiner2 = { form: ",", spaceDelimited: "%20", pipeDelimited: "|" }[options.style] || ",";
544
+ const final = (options.allowReserved === true ? value : value.map((v4) => encodeURIComponent(v4))).join(joiner2);
545
+ switch (options.style) {
546
+ case "simple": {
547
+ return final;
548
+ }
549
+ case "label": {
550
+ return `.${final}`;
551
+ }
552
+ case "matrix": {
553
+ return `;${name}=${final}`;
554
+ }
555
+ // case "spaceDelimited":
556
+ // case "pipeDelimited":
557
+ default: {
558
+ return `${name}=${final}`;
559
+ }
560
+ }
561
+ }
562
+ const joiner = { simple: ",", label: ".", matrix: ";" }[options.style] || "&";
563
+ const values = [];
564
+ for (const v4 of value) {
565
+ if (options.style === "simple" || options.style === "label") {
566
+ values.push(options.allowReserved === true ? v4 : encodeURIComponent(v4));
567
+ } else {
568
+ values.push(serializePrimitiveParam(name, v4, options));
569
+ }
570
+ }
571
+ return options.style === "label" || options.style === "matrix" ? `${joiner}${values.join(joiner)}` : values.join(joiner);
572
+ }
573
+ function createQuerySerializer(options) {
574
+ return function querySerializer(queryParams) {
575
+ const search = [];
576
+ if (queryParams && typeof queryParams === "object") {
577
+ for (const name in queryParams) {
578
+ const value = queryParams[name];
579
+ if (value === void 0 || value === null) {
580
+ continue;
581
+ }
582
+ if (Array.isArray(value)) {
583
+ if (value.length === 0) {
584
+ continue;
585
+ }
586
+ search.push(
587
+ serializeArrayParam(name, value, {
588
+ style: "form",
589
+ explode: true,
590
+ ...options?.array,
591
+ allowReserved: options?.allowReserved || false
592
+ })
593
+ );
594
+ continue;
595
+ }
596
+ if (typeof value === "object") {
597
+ search.push(
598
+ serializeObjectParam(name, value, {
599
+ style: "deepObject",
600
+ explode: true,
601
+ ...options?.object,
602
+ allowReserved: options?.allowReserved || false
603
+ })
604
+ );
605
+ continue;
606
+ }
607
+ search.push(serializePrimitiveParam(name, value, options));
608
+ }
609
+ }
610
+ return search.join("&");
611
+ };
612
+ }
613
+ function defaultPathSerializer(pathname, pathParams) {
614
+ let nextURL = pathname;
615
+ for (const match of pathname.match(PATH_PARAM_RE) ?? []) {
616
+ let name = match.substring(1, match.length - 1);
617
+ let explode = false;
618
+ let style = "simple";
619
+ if (name.endsWith("*")) {
620
+ explode = true;
621
+ name = name.substring(0, name.length - 1);
622
+ }
623
+ if (name.startsWith(".")) {
624
+ style = "label";
625
+ name = name.substring(1);
626
+ } else if (name.startsWith(";")) {
627
+ style = "matrix";
628
+ name = name.substring(1);
629
+ }
630
+ if (!pathParams || pathParams[name] === void 0 || pathParams[name] === null) {
631
+ continue;
632
+ }
633
+ const value = pathParams[name];
634
+ if (Array.isArray(value)) {
635
+ nextURL = nextURL.replace(match, serializeArrayParam(name, value, { style, explode }));
636
+ continue;
637
+ }
638
+ if (typeof value === "object") {
639
+ nextURL = nextURL.replace(match, serializeObjectParam(name, value, { style, explode }));
640
+ continue;
641
+ }
642
+ if (style === "matrix") {
643
+ nextURL = nextURL.replace(match, `;${serializePrimitiveParam(name, value)}`);
644
+ continue;
645
+ }
646
+ nextURL = nextURL.replace(match, style === "label" ? `.${encodeURIComponent(value)}` : encodeURIComponent(value));
647
+ }
648
+ return nextURL;
649
+ }
650
+ function defaultBodySerializer(body) {
651
+ if (body instanceof FormData) {
652
+ return body;
653
+ }
654
+ return JSON.stringify(body);
655
+ }
656
+ function createFinalURL(pathname, options) {
657
+ let finalURL = `${options.baseUrl}${pathname}`;
658
+ if (options.params?.path) {
659
+ finalURL = defaultPathSerializer(finalURL, options.params.path);
660
+ }
661
+ let search = options.querySerializer(options.params.query ?? {});
662
+ if (search.startsWith("?")) {
663
+ search = search.substring(1);
664
+ }
665
+ if (search) {
666
+ finalURL += `?${search}`;
667
+ }
668
+ return finalURL;
669
+ }
670
+ function mergeHeaders(...allHeaders) {
671
+ const finalHeaders = new Headers();
672
+ for (const h of allHeaders) {
673
+ if (!h || typeof h !== "object") {
674
+ continue;
675
+ }
676
+ const iterator = h instanceof Headers ? h.entries() : Object.entries(h);
677
+ for (const [k, v4] of iterator) {
678
+ if (v4 === null) {
679
+ finalHeaders.delete(k);
680
+ } else if (Array.isArray(v4)) {
681
+ for (const v22 of v4) {
682
+ finalHeaders.append(k, v22);
683
+ }
684
+ } else if (v4 !== void 0) {
685
+ finalHeaders.set(k, v4);
686
+ }
687
+ }
688
+ }
689
+ return finalHeaders;
690
+ }
691
+ function removeTrailingSlash(url) {
692
+ if (url.endsWith("/")) {
693
+ return url.substring(0, url.length - 1);
694
+ }
695
+ return url;
696
+ }
697
+
698
+ // ../private-api-clients/src/assert-valid-url-origin.ts
699
+ function assertValidUrlOrigin(origin) {
700
+ const url = new URL(origin);
701
+ if (url.origin !== origin) {
702
+ throw new Error(`${origin} is not a valid URL origin`);
703
+ }
704
+ }
705
+
706
+ // ../private-api-clients/src/dev-v2-api-client.ts
707
+ function createDeveloperAPIv2Client({
708
+ serverOrigin = "",
709
+ fetch,
710
+ headers
711
+ }) {
712
+ if (serverOrigin) assertValidUrlOrigin(serverOrigin);
713
+ return createClient({
714
+ baseUrl: `${serverOrigin}/api/dev/v2`,
715
+ fetch,
716
+ headers
291
717
  });
292
718
  }
293
719
 
294
- // src/lib/fetch-definition-reference.ts
295
- async function fetchDefinitionReference(options) {
296
- const client = createDeveloperAPIClient(options.baseUrl, options.apiKey);
720
+ // src/lib/fetch-current-definition.ts
721
+ async function fetchCurrentDefinition(options) {
722
+ const client = createDeveloperAPIv2Client({
723
+ serverOrigin: options.baseUrl,
724
+ headers: {
725
+ "x-api-key": options.apiKey
726
+ }
727
+ });
297
728
  const abortController = new AbortController();
298
729
  const timeout = setTimeout(() => {
299
730
  abortController.abort();
300
731
  }, 1e4);
301
732
  try {
302
733
  const response = await client.GET(
303
- "/projects/{projectName}/definitions/current/reference",
734
+ "/projects/{projectName}/definitions/current",
304
735
  {
305
736
  params: { path: { projectName: options.projectName } },
306
737
  signal: abortController.signal
307
738
  }
308
739
  );
309
740
  if (response.data) {
310
- return response.data.content;
741
+ return response.data;
311
742
  }
312
743
  if (response.response.status === 404) {
313
744
  throw new Error(`Project ${options.projectName} not found.`);
@@ -329,9 +760,9 @@ async function fetchDefinitionReference(options) {
329
760
  }
330
761
 
331
762
  // src/lib/load-env.ts
332
- var import_promises2 = __toESM(require("fs/promises"));
333
- var v3 = __toESM(require("valibot"));
334
- var import_dotenv = __toESM(require("dotenv"));
763
+ import fs from "fs/promises";
764
+ import * as v3 from "valibot";
765
+ import dotenv from "dotenv";
335
766
  var DEFAULT_ENV_FILE_PATH = ".env";
336
767
  var EnvSchema = v3.object({
337
768
  ORIZM_PROJECT: v3.pipe(
@@ -355,15 +786,15 @@ var EnvSchema = v3.object({
355
786
  async function loadEnv(envPath) {
356
787
  let envFileContent;
357
788
  if (envPath) {
358
- envFileContent = await import_promises2.default.readFile(envPath, "utf-8").catch(() => null);
789
+ envFileContent = await fs.readFile(envPath, "utf-8").catch(() => null);
359
790
  if (!envFileContent) {
360
791
  throw new Error(`Environment variables file: '${envPath}' is not found.`);
361
792
  }
362
793
  } else {
363
- envFileContent = await import_promises2.default.readFile(DEFAULT_ENV_FILE_PATH, "utf-8").catch(() => null);
794
+ envFileContent = await fs.readFile(DEFAULT_ENV_FILE_PATH, "utf-8").catch(() => null);
364
795
  }
365
796
  if (envFileContent !== null) {
366
- const dotenvParsed = import_dotenv.default.parse(envFileContent);
797
+ const dotenvParsed = dotenv.parse(envFileContent);
367
798
  const envParseResult = v3.safeParse(EnvSchema, dotenvParsed);
368
799
  if (!envParseResult.success) {
369
800
  throw new Error(
@@ -389,7 +820,7 @@ async function pullAction(options) {
389
820
  const env = await loadEnv(options.envPath);
390
821
  spinner2.succeed("Loaded environment variables.");
391
822
  spinner2.start("Loading project schema...");
392
- const definitionReference = await fetchDefinitionReference({
823
+ const definitionReference = await fetchCurrentDefinition({
393
824
  baseUrl: env.ORIZM_BASE_URL,
394
825
  apiKey: env.ORIZM_API_KEY,
395
826
  projectName: env.ORIZM_PROJECT
@@ -398,13 +829,13 @@ async function pullAction(options) {
398
829
  spinner2.start("Generating code...");
399
830
  await generate({
400
831
  output: options.destination,
401
- projectDef: definitionReference
832
+ config: definitionReference.parsed
402
833
  });
403
834
  spinner2.succeed(`Generated code to '${options.destination}'`);
404
835
  }
405
836
 
406
837
  // src/cms/pull/command.ts
407
- var cmsPullCommand = new import_commander2.Command("pull").description("pull orizm schema and generate client and types.").option("-e, --env [path]", "env file path.").option("-o, --output <path>", "output directory.", "./src/orizm").action(async (options) => {
838
+ var cmsPullCommand = new Command2("pull").description("pull orizm schema and generate client and types.").option("-e, --env [path]", "env file path.").option("-o, --output <path>", "output directory.", "./src/orizm").action(async (options) => {
408
839
  try {
409
840
  await pullAction({
410
841
  destination: options.output,
@@ -416,34 +847,34 @@ var cmsPullCommand = new import_commander2.Command("pull").description("pull ori
416
847
  });
417
848
 
418
849
  // src/consumer/generate/command.ts
419
- var import_commander3 = require("commander");
850
+ import { Command as Command3 } from "commander";
420
851
 
421
852
  // src/consumer/pull/generate.ts
422
- var import_promises3 = require("fs/promises");
423
- var import_path2 = __toESM(require("path"));
424
- var import_handlebars2 = __toESM(require("handlebars"));
853
+ import { mkdir as mkdir2, writeFile as writeFile2 } from "fs/promises";
854
+ import path2 from "path";
855
+ import Handlebars2 from "handlebars";
425
856
 
426
857
  // src/consumer/templates/client.ts.hbr
427
858
  var client_ts_default2 = '// This file was automatically generated and should not be edited.\n\nimport { ConsumerClientOptions, OrizmConsumerClientBase } from "@orizm/consumer-sdk";\nimport * as Models from "./types";\n\nexport class OrizmClient extends OrizmConsumerClientBase {\n constructor(options: ConsumerClientOptions) {\n super(options);\n }\n\n readonly tables = {\n {{#each tables}}\n {{toEndpointName this.name}}: this.getTableClient<Models.{{toCodeTypeName this.name}}__Descriptor>("{{toEndpointName this.name}}"),\n {{/each}}\n };\n}\n';
428
859
 
429
860
  // src/consumer/templates/types.ts.hbr
430
- var types_ts_default2 = '// This file was automatically generated and should not be edited.\n\nimport { FormValidationRules, StorageItemType } from "@orizm/common";\n\n// Utilities\ntype _ModuleRef<T> = T & _ModuleDescriptor;\ntype _ModuleDescriptor = {\n isModule: true;\n};\ntype _ArrayModuleRef<T> = T & _ArrayModuleDescriptor;\ntype _ArrayModuleDescriptor = {\n isModuleArray: true;\n};\n\n\n// Tables\n{{#each tables}}\nexport type {{toCodeTypeName this.name}} = {\n id: string;\n createdAt: string;\n updatedAt: string;\n group?: string;\n publishedAt?: string;\n _draft?: boolean;\n _published?: boolean;\n {{#each this.columns}}\n {{this.name}}{{#unless this.required}}?{{/unless}}: {{typeName this}};\n {{/each}}\n {{#if this.enableForm}}\n formSchema: FormValidationRules;\n {{/if}}\n}\n\n{{/each}}\n\n{{#each tableModules}}\nexport type {{toCodeTypeName this.name}} = {\n {{#each this.columns}}\n {{this.name}}{{#unless this.required}}?{{/unless}}: {{typeName this}};\n {{/each}}\n};\n{{/each}}\n\n// Descriptor types\n{{#each tables}}\nexport type {{toCodeTypeName this.name}}__Descriptor = {\n row: {{toCodeTypeName this.name}};\n {{#if (filterRefColumn this.columns)}}\n refs: {\n {{#each (filterRefColumn this.columns)}}\n {{includeName this}}: {{{includeType this}}};\n {{/each}}\n }\n {{/if}}\n {{#unless (filterRefColumn this.columns)}}\n refs: object;\n {{/unless}}\n {{#if (filterUniqueIndexes this.indexes)}}\n unique: [\n {{#each (filterUniqueIndexes this.indexes)}}\n { {{#each (getIndexColumns ../this this)}}{{this.name}}:{{typeName this}},{{/each}} },\n {{/each}}\n ]\n {{/if}}\n {{#unless (filterUniqueIndexes this.indexes)}}\n unique: [];\n {{/unless}}\n {{#if this.enableDrafts}}\n enableDrafts: true;\n {{/if}}\n};\n{{/each}}\n\n\n{{#each tableModules}}\nexport type {{toCodeTypeName this.name}}__Descriptor = {\n row: {{toCodeTypeName this.name}};\n {{#if (filterRefColumn this.columns)}}\n refs: {\n {{#each (filterRefColumn this.columns)}}\n {{includeName this}}: {{{includeType this}}};\n {{/each}}\n }\n {{/if}}\n {{#unless (filterRefColumn this.columns)}}\n refs: object;\n {{/unless}}\n unique:[]\n};\n{{/each}}\n\n\n// Webhook types\nexport type WebhookEvent = "content.create" | "content.update" | "content.delete";\nexport type WebhookPayload = {\n event: WebhookEvent;\n timestamp: string;\n project: string;\n} & (\n {{#each tables}}\n | {\n table: "{{this.name}}";\n content: {{toCodeTypeName this.name}};\n old?: {{toCodeTypeName this.name}};\n }\n {{/each}}\n)\n';
861
+ var types_ts_default2 = '// This file was automatically generated and should not be edited.\n\nimport { FormValidationRules, StorageItemType } from "@orizm/common";\n\n// Utilities\ntype _ModuleRef<T> = T & _ModuleDescriptor;\ntype _ModuleDescriptor = {\n isModule: true;\n};\ntype _ArrayModuleRef<T> = T & _ArrayModuleDescriptor;\ntype _ArrayModuleDescriptor = {\n isModuleArray: true;\n};\n\n\n// Tables\n{{#each tables}}\nexport type {{toCodeTypeName this.name}} = {\n id: string;\n createdAt: string;\n updatedAt: string;\n group?: string;\n publishedAt?: string;\n _draft?: boolean;\n _published?: boolean;\n {{#each this.columns}}\n {{this.name}}{{#unless this.required}}?{{/unless}}: {{typeName this}};\n {{/each}}\n {{#if this.enableForm}}\n formSchema: FormValidationRules;\n {{/if}}\n}\n\n{{/each}}\n\n{{#each tableModules}}\nexport type {{toCodeTypeName this.name}} = {\n {{#each this.columns}}\n {{this.name}}{{#unless this.required}}?{{/unless}}: {{typeName this}};\n {{/each}}\n};\n{{/each}}\n\n// Descriptor types\n{{#each tables}}\nexport type {{toCodeTypeName this.name}}__Descriptor = {\n row: {{toCodeTypeName this.name}};\n {{#if (filterRefColumn this.columns)}}\n refs: {\n {{#each (filterRefColumn this.columns)}}\n {{includeName this}}: {{{includeType this}}};\n {{/each}}\n }\n {{/if}}\n {{#unless (filterRefColumn this.columns)}}\n refs: object;\n {{/unless}}\n {{#if (filterUniqueIndexes this.indexes)}}\n unique: [\n {{#each (filterUniqueIndexes this.indexes)}}\n { {{#each (getIndexColumns ../this this)}}{{this.name}}:{{typeName this}},{{/each}} },\n {{/each}}\n ]\n {{/if}}\n {{#unless (filterUniqueIndexes this.indexes)}}\n unique: [];\n {{/unless}}\n {{#if this.enableDrafts}}\n enableDrafts: true;\n {{/if}}\n};\n{{/each}}\n\n\n{{#each tableModules}}\nexport type {{toCodeTypeName this.name}}__Descriptor = {\n row: {{toCodeTypeName this.name}};\n {{#if (filterRefColumn this.columns)}}\n refs: {\n {{#each (filterRefColumn this.columns)}}\n {{includeName this}}: {{{includeType this}}};\n {{/each}}\n }\n {{/if}}\n {{#unless (filterRefColumn this.columns)}}\n refs: object;\n {{/unless}}\n unique:[]\n};\n{{/each}}\n\n\n// Webhook types\nexport type WebhookEvent = "content.create" | "content.update" | "content.delete";\ntype WebhookPayloadBase = {\n event: WebhookEvent;\n timestamp: string;\n project: string;\n};\n{{#if tables}}\nexport type WebhookPayload = WebhookPayloadBase & (\n {{#each tables}}\n | {\n table: "{{this.name}}";\n content: {{toCodeTypeName this.name}};\n old?: {{toCodeTypeName this.name}};\n }\n {{/each}}\n);\n{{else}}\nexport type WebhookPayload = WebhookPayloadBase;\n{{/if}}\n';
431
862
 
432
863
  // src/consumer/pull/generate.ts
433
864
  async function generate2(options) {
434
- await (0, import_promises3.mkdir)(options.output, { recursive: true });
865
+ await mkdir2(options.output, { recursive: true });
435
866
  await renderTypes2(options.definition, options.output);
436
867
  await renderClient2(options.definition, options.output);
437
868
  }
438
- import_handlebars2.default.registerHelper("toEndpointName", (str) => {
869
+ Handlebars2.registerHelper("toEndpointName", (str) => {
439
870
  return str;
440
871
  });
441
872
  function toCodeTypeName2(str) {
442
873
  str = str.charAt(0).toUpperCase() + str.slice(1);
443
874
  return str.replace(/_([a-z])/g, (g) => g[1].toUpperCase());
444
875
  }
445
- import_handlebars2.default.registerHelper("toCodeTypeName", toCodeTypeName2);
446
- import_handlebars2.default.registerHelper("typeName", (column) => {
876
+ Handlebars2.registerHelper("toCodeTypeName", toCodeTypeName2);
877
+ Handlebars2.registerHelper("typeName", (column) => {
447
878
  if (column.type === "reference") {
448
879
  return "string";
449
880
  } else if (column.type == "json") {
@@ -464,15 +895,15 @@ import_handlebars2.default.registerHelper("typeName", (column) => {
464
895
  return column.type;
465
896
  }
466
897
  });
467
- import_handlebars2.default.registerHelper("filterRefColumn", (columns) => {
898
+ Handlebars2.registerHelper("filterRefColumn", (columns) => {
468
899
  return (columns || []).filter(
469
900
  (c) => c.type === "reference" && c.tableName && c.includeName || c.type === "module" && c.moduleName || c.type === "module-array" && c.moduleName
470
901
  );
471
902
  });
472
- import_handlebars2.default.registerHelper("includeName", (column) => {
903
+ Handlebars2.registerHelper("includeName", (column) => {
473
904
  return column.type === "reference" ? column.includeName : column.name;
474
905
  });
475
- import_handlebars2.default.registerHelper("includeType", (column) => {
906
+ Handlebars2.registerHelper("includeType", (column) => {
476
907
  if (column.type === "reference" && column.tableName)
477
908
  return toCodeTypeName2(column.tableName) + "__Descriptor";
478
909
  if (column.type === "module" && column.moduleName)
@@ -480,13 +911,13 @@ import_handlebars2.default.registerHelper("includeType", (column) => {
480
911
  if (column.type === "module-array" && column.moduleName)
481
912
  return `_ArrayModuleRef<${toCodeTypeName2(column.moduleName)}__Descriptor>`;
482
913
  });
483
- import_handlebars2.default.registerHelper(
914
+ Handlebars2.registerHelper(
484
915
  "filterUniqueIndexes",
485
916
  (indexes) => {
486
917
  return (indexes || []).filter((i) => i.unique);
487
918
  }
488
919
  );
489
- import_handlebars2.default.registerHelper(
920
+ Handlebars2.registerHelper(
490
921
  "getIndexColumns",
491
922
  (table, index) => {
492
923
  return index.columns.map((i) => {
@@ -499,14 +930,14 @@ import_handlebars2.default.registerHelper(
499
930
  }
500
931
  );
501
932
  async function renderTypes2(config, output) {
502
- const rendered = import_handlebars2.default.compile(types_ts_default2)(config);
503
- const targetPath = import_path2.default.join(output, "types.ts");
504
- await (0, import_promises3.writeFile)(targetPath, rendered, "utf-8");
933
+ const rendered = Handlebars2.compile(types_ts_default2)(config);
934
+ const targetPath = path2.join(output, "types.ts");
935
+ await writeFile2(targetPath, rendered, "utf-8");
505
936
  }
506
937
  async function renderClient2(config, output) {
507
- const rendered = import_handlebars2.default.compile(client_ts_default2)(config);
508
- const targetPath = import_path2.default.join(output, "client.ts");
509
- await (0, import_promises3.writeFile)(targetPath, rendered, "utf-8");
938
+ const rendered = Handlebars2.compile(client_ts_default2)(config);
939
+ const targetPath = path2.join(output, "client.ts");
940
+ await writeFile2(targetPath, rendered, "utf-8");
510
941
  }
511
942
 
512
943
  // src/consumer/generate/action.ts
@@ -524,7 +955,7 @@ async function generateAction(orizmConfigTs, destination) {
524
955
  }
525
956
 
526
957
  // src/consumer/generate/command.ts
527
- var consumerGenerateCommand = new import_commander3.Command("generate").description("generate orizm client and types.").option("-c, --config <path>", "orizm config file path.", "orizm.config.ts").option("-o, --output <path>", "output directory.", "./src/orizm").action(async (options) => {
958
+ var consumerGenerateCommand = new Command3("generate").description("generate orizm client and types.").option("-c, --config <path>", "orizm config file path.", "orizm.config.ts").option("-o, --output <path>", "output directory.", "./src/orizm").action(async (options) => {
528
959
  try {
529
960
  await generateAction(options.config, options.output);
530
961
  } catch (error2) {
@@ -533,7 +964,7 @@ var consumerGenerateCommand = new import_commander3.Command("generate").descript
533
964
  });
534
965
 
535
966
  // src/consumer/pull/command.ts
536
- var import_commander4 = require("commander");
967
+ import { Command as Command4 } from "commander";
537
968
 
538
969
  // src/consumer/pull/action.ts
539
970
  var spinner4 = createSpinner();
@@ -542,7 +973,7 @@ async function pullAction2(options) {
542
973
  const config = await loadEnv(options.envPath);
543
974
  spinner4.succeed("Loaded environment variables.");
544
975
  spinner4.start("Loading project schema...");
545
- const definition = await fetchDefinitionReference({
976
+ const definition = await fetchCurrentDefinition({
546
977
  baseUrl: config.ORIZM_BASE_URL,
547
978
  apiKey: config.ORIZM_API_KEY,
548
979
  projectName: config.ORIZM_PROJECT
@@ -550,14 +981,14 @@ async function pullAction2(options) {
550
981
  spinner4.succeed("Loaded project schema.");
551
982
  spinner4.start("Generating code...");
552
983
  await generate2({
553
- definition,
984
+ definition: definition.parsed,
554
985
  output: options.destination
555
986
  });
556
987
  spinner4.succeed(`Generated code to '${options.destination}'`);
557
988
  }
558
989
 
559
990
  // src/consumer/pull/command.ts
560
- var consumerPullCommand = new import_commander4.Command("pull").description("pull orizm schema and generate client and types.").option("-e, --env [path]", "env file path.").option("-o, --output <path>", "output directory.", "./src/orizm").action(async (options) => {
991
+ var consumerPullCommand = new Command4("pull").description("pull orizm schema and generate client and types.").option("-e, --env [path]", "env file path.").option("-o, --output <path>", "output directory.", "./src/orizm").action(async (options) => {
561
992
  try {
562
993
  await pullAction2({
563
994
  destination: options.output,
@@ -569,19 +1000,20 @@ var consumerPullCommand = new import_commander4.Command("pull").description("pul
569
1000
  });
570
1001
 
571
1002
  // src/push/command.ts
572
- var import_commander5 = require("commander");
573
- var import_cli_color3 = require("cli-color");
1003
+ import { Command as Command5 } from "commander";
1004
+ import cliColor4 from "cli-color";
574
1005
 
575
1006
  // src/lib/developer-api.ts
576
1007
  async function applyDefinition(env, projectDef) {
577
- const client = createDeveloperAPIClient(
578
- env.ORIZM_BASE_URL,
579
- env.ORIZM_API_KEY
580
- );
1008
+ const client = createDeveloperAPIv2Client({
1009
+ serverOrigin: env.ORIZM_BASE_URL,
1010
+ headers: {
1011
+ "x-api-key": env.ORIZM_API_KEY
1012
+ }
1013
+ });
581
1014
  const response = await client.POST("/projects/{projectName}/definitions", {
582
1015
  params: { path: { projectName: env.ORIZM_PROJECT } },
583
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
584
- body: { apply: true, project: projectDef }
1016
+ body: { definition: projectDef }
585
1017
  });
586
1018
  if (!response.data) {
587
1019
  const status = response.response.status;
@@ -596,16 +1028,17 @@ async function applyDefinition(env, projectDef) {
596
1028
  }
597
1029
  }
598
1030
  var getChangeEvents = async (env, projectDef) => {
599
- const client = createDeveloperAPIClient(
600
- env.ORIZM_BASE_URL,
601
- env.ORIZM_API_KEY
602
- );
1031
+ const client = createDeveloperAPIv2Client({
1032
+ serverOrigin: env.ORIZM_BASE_URL,
1033
+ headers: {
1034
+ "x-api-key": env.ORIZM_API_KEY
1035
+ }
1036
+ });
603
1037
  const response = await client.POST(
604
1038
  "/projects/{projectName}/definitions/dry-run",
605
1039
  {
606
1040
  params: { path: { projectName: env.ORIZM_PROJECT } },
607
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
608
- body: { project: projectDef }
1041
+ body: { definition: projectDef }
609
1042
  }
610
1043
  );
611
1044
  if (!response.data) {
@@ -623,7 +1056,7 @@ var getChangeEvents = async (env, projectDef) => {
623
1056
  };
624
1057
 
625
1058
  // src/lib/display-change-events.ts
626
- var import_cli_color2 = require("cli-color");
1059
+ import cliColor3 from "cli-color";
627
1060
 
628
1061
  // src/lib/cli-table.ts
629
1062
  var COLORS = {
@@ -732,7 +1165,7 @@ async function displayChangeEvents(changeEvents) {
732
1165
  } = changeEvents;
733
1166
  if (tableChangeEvents.length === 0 && bucketChangeEvents.length === 0 && authorityChangeEvents.length === 0) {
734
1167
  console.log();
735
- console.log((0, import_cli_color2.green)("No changes."));
1168
+ console.log(cliColor3.green("No changes."));
736
1169
  return;
737
1170
  }
738
1171
  displayTableChangeEvents(tableChangeEvents);
@@ -970,9 +1403,9 @@ function displayAuthorityChangeEvents(authorityChangeEvents) {
970
1403
  }
971
1404
 
972
1405
  // src/lib/cli-input.ts
973
- var import_promises4 = require("readline/promises");
1406
+ import { createInterface } from "node:readline/promises";
974
1407
  async function input(prompt) {
975
- const rl = (0, import_promises4.createInterface)({
1408
+ const rl = createInterface({
976
1409
  input: process.stdin,
977
1410
  output: process.stdout
978
1411
  });
@@ -984,7 +1417,7 @@ async function input(prompt) {
984
1417
 
985
1418
  // src/push/command.ts
986
1419
  var spinner5 = createSpinner();
987
- var pushCommand = new import_commander5.Command("push").description("apply schema to project.").option("-e, --env <path>", "env file path.").option("-c, --config <path>", "orizm config file path.", "orizm.config.ts").option("--dry-run", "display change-events without applying schema.", false).option("-y, --yes", "apply schema without confirmation.", false).action(async (options) => {
1420
+ var pushCommand = new Command5("push").description("apply schema to project.").option("-e, --env <path>", "env file path.").option("-c, --config <path>", "orizm config file path.", "orizm.config.ts").option("--dry-run", "display change-events without applying schema.", false).option("-y, --yes", "apply schema without confirmation.", false).action(async (options) => {
988
1421
  try {
989
1422
  spinner5.start("Loading environment variables...");
990
1423
  const env = await loadEnv(options.env);
@@ -1005,7 +1438,7 @@ var pushCommand = new import_commander5.Command("push").description("apply schem
1005
1438
  if (!options.yes) {
1006
1439
  const confirm = await input("Do you want to apply schema? (y/N): ");
1007
1440
  if (confirm !== "y") {
1008
- console.log((0, import_cli_color3.red)("Canceled."));
1441
+ console.log(cliColor4.red("Canceled."));
1009
1442
  return;
1010
1443
  }
1011
1444
  }
@@ -1018,16 +1451,16 @@ var pushCommand = new import_commander5.Command("push").description("apply schem
1018
1451
  });
1019
1452
 
1020
1453
  // src/cli.ts
1021
- import_commander6.program.name("orizm CLI");
1022
- import_commander6.program.addCommand(pushCommand);
1023
- var cmsCommands = new import_commander6.Command("cms").description("cms commands.");
1454
+ program.name("orizm CLI");
1455
+ program.addCommand(pushCommand);
1456
+ var cmsCommands = new Command6("cms").description("cms commands.");
1024
1457
  cmsCommands.addCommand(cmsGenerateCommand);
1025
1458
  cmsCommands.addCommand(cmsPullCommand);
1026
- import_commander6.program.addCommand(cmsCommands);
1027
- var consumerCommands = new import_commander6.Command("consumer").description(
1459
+ program.addCommand(cmsCommands);
1460
+ var consumerCommands = new Command6("consumer").description(
1028
1461
  "consumer commands."
1029
1462
  );
1030
1463
  consumerCommands.addCommand(consumerGenerateCommand);
1031
1464
  consumerCommands.addCommand(consumerPullCommand);
1032
- import_commander6.program.addCommand(consumerCommands);
1033
- import_commander6.program.parse();
1465
+ program.addCommand(consumerCommands);
1466
+ program.parse();
package/package.json CHANGED
@@ -1,7 +1,8 @@
1
1
  {
2
2
  "name": "@orizm/cli",
3
- "version": "1.0.1",
3
+ "version": "1.0.3",
4
4
  "description": "Orizm CLI",
5
+ "type": "module",
5
6
  "repository": {
6
7
  "type": "git",
7
8
  "url": "https://github.com/chot-Inc/superx.git",
@@ -17,23 +18,21 @@
17
18
  "dotenv": "^16.3.1",
18
19
  "esbuild": "^0.17.19",
19
20
  "handlebars": "^4.7.7",
20
- "openapi-fetch": "^0.12.2",
21
21
  "valibot": "^1.0.0",
22
- "@orizm/common": "1.13.0"
22
+ "@orizm/common": "1.13.1"
23
23
  },
24
24
  "bin": {
25
25
  "orizm": "bin/index.js"
26
26
  },
27
27
  "devDependencies": {
28
28
  "@types/cli-color": "^2.0.2",
29
- "openapi-typescript": "^7.6.1",
30
- "@orizm/package-configs": "0.0.0"
29
+ "@orizm/package-configs": "0.0.0",
30
+ "@orizm/private-api-clients": "0.0.0"
31
31
  },
32
32
  "license": "Apache-2.0",
33
33
  "scripts": {
34
34
  "dev": "tsup --watch",
35
35
  "build": "tsup",
36
- "typecheck": "tsc --noEmit",
37
- "generate": "openapi-typescript ../../apps/server/openapi/developerAPI.yaml --output src/api/developer-api.d.ts"
36
+ "typecheck": "tsc --noEmit"
38
37
  }
39
38
  }