@hygraph/cli 0.0.1 → 0.0.2

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/bin/hygraph.js CHANGED
@@ -1,4 +1,11 @@
1
1
  #!/usr/bin/env node
2
2
  import { run } from "../dist/cli.js";
3
3
 
4
- run();
4
+ try {
5
+ await run();
6
+ } catch (error) {
7
+ // Commander has already exited for its own errors. Anything reaching here
8
+ // is a failure the command did not translate for the user.
9
+ console.error(error instanceof Error ? error.message : String(error));
10
+ process.exitCode = 1;
11
+ }
package/dist/cli.d.ts CHANGED
@@ -6,9 +6,11 @@ export interface RunResult {
6
6
  }
7
7
  /**
8
8
  * Parses arguments and captures what would have been written, instead of
9
- * touching the process. Pure, so it is testable.
9
+ * touching the process. Pure, so it is testable. Async because commands
10
+ * talk to the management API; parseAsync awaits an action that returns a
11
+ * promise, where parse would let it run unobserved.
10
12
  */
11
- export declare function handle(argv: readonly string[]): RunResult;
13
+ export declare function handle(argv: readonly string[]): Promise<RunResult>;
12
14
  /** Entry point for the bin. Commander reads process.argv and slices it itself. */
13
- export declare function run(): void;
15
+ export declare function run(): Promise<void>;
14
16
  //#endregion
package/dist/cli.js CHANGED
@@ -1,10 +1,12 @@
1
1
  import { t as VERSION } from "./version.js";
2
+ import { t as isEmpty } from "./is-empty.js";
2
3
  import { EventEmitter } from "node:events";
3
4
  import childProcess from "node:child_process";
4
- import path from "node:path";
5
- import fs from "node:fs";
5
+ import path, { resolve } from "node:path";
6
+ import fs, { existsSync } from "node:fs";
6
7
  import process$1 from "node:process";
7
8
  import { stripVTControlCharacters } from "node:util";
9
+ import { createJiti } from "jiti";
8
10
  //#region node_modules/.pnpm/commander@15.0.0/node_modules/commander/lib/error.js
9
11
  /**
10
12
  * CommanderError class
@@ -3047,17 +3049,210 @@ function validate(command) {
3047
3049
  });
3048
3050
  }
3049
3051
  //#endregion
3052
+ //#region src/utils/has-typename.ts
3053
+ /**
3054
+ * Every resource a builder returns carries a `__typename`, so telling one
3055
+ * apart from another — or from whatever a config actually exported — is a
3056
+ * single comparison rather than a guess at its shape.
3057
+ */
3058
+ function hasTypename(value, typename) {
3059
+ return typeof value === "object" && value !== null && "__typename" in value && value.__typename === typename;
3060
+ }
3061
+ //#endregion
3062
+ //#region src/config/import-module.ts
3063
+ /**
3064
+ * The only place that knows how a TypeScript config becomes a module.
3065
+ * Replacing jiti is a rewrite of this function and one dependency; nothing
3066
+ * upstream of it knows what transpiled the file.
3067
+ *
3068
+ * The default export is read here rather than by the caller because jiti's
3069
+ * `{ default: true }` shortcut resolves to `mod?.default ?? mod`, which hands
3070
+ * back the whole namespace when there is no default export. Testing for the
3071
+ * key keeps a config missing `export default` reportable as that, instead of
3072
+ * as a config of the wrong shape.
3073
+ */
3074
+ async function importConfigModule(path) {
3075
+ const absolute = resolve(process.cwd(), path);
3076
+ const module = await createJiti(import.meta.url).import(absolute);
3077
+ if (typeof module !== "object" || module === null || !("default" in module)) throw new Error(`${path} has no default export`);
3078
+ return module.default;
3079
+ }
3080
+ //#endregion
3081
+ //#region src/config/load.ts
3082
+ /**
3083
+ * Reads `hygraph.config.ts` and hands back the target it exports.
3084
+ * We support only a single target for now.
3085
+ */
3086
+ async function loadConfig(path) {
3087
+ const absolute = resolve(process.cwd(), path);
3088
+ if (!existsSync(absolute)) throw new Error(`no config file at ${path}`);
3089
+ const exported = await importConfigModule(path);
3090
+ if (Array.isArray(exported)) throw new Error(`${path} exports a list of targets, which is not supported yet (export a single target)`);
3091
+ if (!isTarget(exported)) throw new Error(`the default export of ${path} is not a target`);
3092
+ return exported;
3093
+ }
3094
+ function isTarget(value) {
3095
+ return hasTypename(value, "Target");
3096
+ }
3097
+ //#endregion
3098
+ //#region src/management/client.ts
3099
+ /** The server answered, but not with data: a non-2xx status, `errors`, or both. */
3100
+ var ManagementApiError = class extends Error {
3101
+ status;
3102
+ errors;
3103
+ constructor(status, errors) {
3104
+ super(errors.length > 0 ? errors.map((error) => error.message).join("; ") : `status ${status}`);
3105
+ this.status = status;
3106
+ this.errors = errors;
3107
+ this.name = "ManagementApiError";
3108
+ }
3109
+ };
3110
+ /**
3111
+ * A client for one target's management API. Commands hand it the generated
3112
+ * document of their operation and get the typed result back.
3113
+ */
3114
+ function createManagementClient({ endpoint, token, fetch = globalThis.fetch }) {
3115
+ return { async request(document, ...[variables]) {
3116
+ const response = await fetch(endpoint, {
3117
+ method: "POST",
3118
+ headers: {
3119
+ "Content-Type": "application/json",
3120
+ Authorization: `Bearer ${token}`,
3121
+ "x-hyg-client": "cli",
3122
+ "User-Agent": `@hygraph/cli/${VERSION}`
3123
+ },
3124
+ body: JSON.stringify({
3125
+ query: document.toString(),
3126
+ variables
3127
+ })
3128
+ });
3129
+ const body = await response.json().catch(() => ({}));
3130
+ if (!response.ok || body.errors?.length || body.data == null) throw new ManagementApiError(response.status, body.errors ?? []);
3131
+ return body.data;
3132
+ } };
3133
+ }
3134
+ //#endregion
3135
+ //#region src/management/errors.ts
3136
+ const AUTH_CODES = /* @__PURE__ */ new Set(["AuthenticationError", "AuthorizationError"]);
3137
+ /**
3138
+ * One sentence for the user about why a management API call failed.
3139
+ *
3140
+ * Covers what the management client and fetch throw: the server answering
3141
+ * with errors, and the server not being reachable at all. Anything else is
3142
+ * not a management API failure and is rethrown, so a bug keeps its stack.
3143
+ */
3144
+ function describeManagementError(error, endpoint) {
3145
+ if (error instanceof ManagementApiError) {
3146
+ const { status, errors } = error;
3147
+ const codes = errors.map((graphqlError) => graphqlError.extensions?.code);
3148
+ if (status === 401 || status === 403 || codes.some((code) => typeof code === "string" && AUTH_CODES.has(code))) return `the token was rejected by ${endpoint}`;
3149
+ const messages = errors.map((graphqlError) => graphqlError.message);
3150
+ return messages.length > 0 ? `${endpoint} answered: ${messages.join("; ")}` : `${endpoint} answered with status ${status}`;
3151
+ }
3152
+ if (error instanceof TypeError && error.message === "fetch failed") return `could not reach ${endpoint}: ${error.cause instanceof Error ? error.cause.message : "unknown cause"}`;
3153
+ throw error;
3154
+ }
3155
+ //#endregion
3156
+ //#region src/management/graphql.ts
3157
+ var TypedDocumentString = class extends String {
3158
+ __apiType;
3159
+ value;
3160
+ __meta__;
3161
+ constructor(value, __meta__) {
3162
+ super(value);
3163
+ this.value = value;
3164
+ this.__meta__ = __meta__;
3165
+ }
3166
+ toString() {
3167
+ return this.value;
3168
+ }
3169
+ };
3170
+ const WhoamiDocument = new TypedDocumentString(`
3171
+ query Whoami {
3172
+ viewer {
3173
+ id
3174
+ ... on TokenViewer {
3175
+ project {
3176
+ id
3177
+ name
3178
+ region {
3179
+ id
3180
+ __typename
3181
+ }
3182
+ environments {
3183
+ name
3184
+ __typename
3185
+ }
3186
+ __typename
3187
+ }
3188
+ __typename
3189
+ }
3190
+ __typename
3191
+ }
3192
+ }
3193
+ `);
3194
+ //#endregion
3050
3195
  //#region src/commands/whoami.ts
3196
+ /** A failure the user can act on. The command prints it and exits 1. */
3197
+ var WhoamiFailure = class extends Error {};
3051
3198
  function registerWhoami(program) {
3052
- program.command("whoami").description("show what the current token is and can do").action(function() {
3053
- whoami(this);
3054
- });
3199
+ program.command("whoami").description("show what the current token is and can do").option("--config <file>", "the config to read the target from", "hygraph.config.ts").action(async function(options) {
3200
+ try {
3201
+ const target = await loadTarget(options.config);
3202
+ this.configureOutput().writeOut?.(await whoami(target));
3203
+ } catch (error) {
3204
+ if (error instanceof WhoamiFailure) this.error(`error: ${error.message}`, {
3205
+ exitCode: 1,
3206
+ code: "hygraph.whoami"
3207
+ });
3208
+ throw error;
3209
+ }
3210
+ }).addHelpText("after", examples([["hygraph whoami", "the target in hygraph.config.ts"], ["hygraph whoami --config brands/kaffa/hygraph.config.ts"]]));
3055
3211
  }
3056
- function whoami(command) {
3057
- command.error("error: whoami is not implemented yet", {
3058
- exitCode: 1,
3059
- code: "hygraph.notImplemented"
3212
+ /** Resolves the target's token against its management API and describes it. */
3213
+ async function whoami(target, fetch) {
3214
+ if (isEmpty(target.token)) throw new WhoamiFailure(`target "${target.name}" has no token`);
3215
+ const client = createManagementClient({
3216
+ endpoint: target.endpoint,
3217
+ token: target.token,
3218
+ fetch
3060
3219
  });
3220
+ let result;
3221
+ try {
3222
+ result = await client.request(WhoamiDocument);
3223
+ } catch (error) {
3224
+ throw new WhoamiFailure(describeManagementError(error, target.endpoint));
3225
+ }
3226
+ return renderWhoami(result.viewer, target);
3227
+ }
3228
+ async function loadTarget(config) {
3229
+ try {
3230
+ return await loadConfig(config);
3231
+ } catch (error) {
3232
+ throw new WhoamiFailure(error instanceof Error ? error.message : String(error));
3233
+ }
3234
+ }
3235
+ /**
3236
+ * The token as the management API sees it, checked against what the target
3237
+ * claims. Reads only what the viewer already exposes: no permissions yet.
3238
+ */
3239
+ function renderWhoami(viewer, target) {
3240
+ if (viewer.__typename !== "TokenViewer") throw new WhoamiFailure(`the token is a ${viewer.__typename}, not a permanent auth token`);
3241
+ const { project } = viewer;
3242
+ if (!project) throw new WhoamiFailure("the token's project could not be read");
3243
+ if (project.id !== target.project) throw new WhoamiFailure(`the token belongs to project ${project.id} (${project.name}), the target says ${target.project}`);
3244
+ const environments = project.environments.map((environment) => environment.name);
3245
+ if (!environments.includes(target.environment)) throw new WhoamiFailure(`project "${project.name}" has no environment "${target.environment}" (has ${environments.join(", ")})`);
3246
+ return rows([
3247
+ ["token", "permanent, project-scoped"],
3248
+ ["project", `${project.id} (${project.name})`],
3249
+ ["region", project.region.id],
3250
+ ["env", target.environment]
3251
+ ]);
3252
+ }
3253
+ function rows(entries) {
3254
+ const width = Math.max(...entries.map(([label]) => label.length));
3255
+ return entries.map(([label, value]) => `${label.padEnd(width)} ${value}`).join("\n") + "\n";
3061
3256
  }
3062
3257
  //#endregion
3063
3258
  //#region src/commands/index.ts
@@ -3098,9 +3293,11 @@ function capture(command, writeOut, writeErr) {
3098
3293
  }
3099
3294
  /**
3100
3295
  * Parses arguments and captures what would have been written, instead of
3101
- * touching the process. Pure, so it is testable.
3296
+ * touching the process. Pure, so it is testable. Async because commands
3297
+ * talk to the management API; parseAsync awaits an action that returns a
3298
+ * promise, where parse would let it run unobserved.
3102
3299
  */
3103
- function handle(argv) {
3300
+ async function handle(argv) {
3104
3301
  let stdout = "";
3105
3302
  let stderr = "";
3106
3303
  const program = createProgram();
@@ -3118,7 +3315,7 @@ function handle(argv) {
3118
3315
  };
3119
3316
  }
3120
3317
  try {
3121
- program.parse(argv, { from: "user" });
3318
+ await program.parseAsync(argv, { from: "user" });
3122
3319
  return {
3123
3320
  stdout,
3124
3321
  stderr,
@@ -3134,13 +3331,13 @@ function handle(argv) {
3134
3331
  }
3135
3332
  }
3136
3333
  /** Entry point for the bin. Commander reads process.argv and slices it itself. */
3137
- function run() {
3334
+ async function run() {
3138
3335
  const program = createProgram();
3139
3336
  if (process.argv.length <= 2) {
3140
3337
  program.outputHelp();
3141
3338
  return;
3142
3339
  }
3143
- program.parse();
3340
+ await program.parseAsync();
3144
3341
  }
3145
3342
  //#endregion
3146
3343
  export { handle, run };
package/dist/define.d.ts CHANGED
@@ -108,9 +108,49 @@ declare function component(_options: unknown): never;
108
108
  //#region src/define/resources/enumeration.d.ts
109
109
  declare function enumeration(_options: unknown): never;
110
110
  //#endregion
111
+ //#region src/define/resources/model.d.ts
112
+ type ModelInput = {
113
+ apiId: string;
114
+ apiIdPlural: string;
115
+ displayName: string;
116
+ description?: string;
117
+ };
118
+ /**
119
+ * What `define.model` hands back: the input with every default filled in.
120
+ * Plain data in the same shape the user wrote, not the IR — the canonical
121
+ * form is built from these later and never reaches the config.
122
+ */
123
+ type Model = {
124
+ __typename: "Model";
125
+ apiId: string;
126
+ apiIdPlural: string;
127
+ displayName: string;
128
+ description: string | null;
129
+ };
130
+ /**
131
+ * One model.
132
+ *
133
+ * Nothing here is validated. Format rules, `apiIdPlural` against `apiId` and
134
+ * uniqueness are plan-time checks, reported together rather than thrown one
135
+ * at a time while the config loads.
136
+ */
137
+ declare function model(input: ModelInput): Model;
138
+ //#endregion
111
139
  //#region src/define/resources/environment.d.ts
112
- /** One environment: typed arrays per resource kind. The what. */
113
- declare function environment(_options: unknown): never;
140
+ type EnvironmentInput = {
141
+ models: Model[];
142
+ };
143
+ type Environment = {
144
+ __typename: "Environment";
145
+ models: Model[];
146
+ };
147
+ /**
148
+ * One environment: typed arrays per resource kind. The what.
149
+ *
150
+ * Ordering, keying and positions are not decided here. This returns the
151
+ * models as written; `convertToIR` turns them into the canonical form.
152
+ */
153
+ declare function environment(input: EnvironmentInput): Environment;
114
154
  //#endregion
115
155
  //#region src/define/resources/graphqlRemoteSource.d.ts
116
156
  declare function graphqlRemoteSource(_options: unknown): never;
@@ -118,9 +158,6 @@ declare function graphqlRemoteSource(_options: unknown): never;
118
158
  //#region src/define/resources/locale.d.ts
119
159
  declare function locale(_options: unknown): never;
120
160
  //#endregion
121
- //#region src/define/resources/model.d.ts
122
- declare function model(_options: unknown): never;
123
- //#endregion
124
161
  //#region src/define/resources/restRemoteSource.d.ts
125
162
  declare function restRemoteSource(_options: unknown): never;
126
163
  //#endregion
@@ -128,11 +165,32 @@ declare function restRemoteSource(_options: unknown): never;
128
165
  declare function stage(_options: unknown): never;
129
166
  //#endregion
130
167
  //#region src/define/resources/target.d.ts
168
+ type TargetInput = {
169
+ name: string;
170
+ project: string;
171
+ environment: string;
172
+ /**
173
+ * The management API of the project's region, such as
174
+ * `https://management-eu-central-1.hygraph.com/graphql`.
175
+ */
176
+ endpoint: string;
177
+ token: string;
178
+ apply: Environment;
179
+ };
180
+ type Target = {
181
+ __typename: "Target";
182
+ name: string;
183
+ project: string;
184
+ environment: string;
185
+ endpoint: string;
186
+ token: string;
187
+ apply: Environment;
188
+ };
131
189
  /**
132
- * One environment of one project, its token variable, and the environment
133
- * definition to apply there. The where.
190
+ * One environment of one project, where to reach it and the token to do so,
191
+ * and the environment definition to apply there. The where.
134
192
  */
135
- declare function target(_options: unknown): never;
193
+ declare function target(input: TargetInput): Target;
136
194
  //#endregion
137
195
  //#region src/define/resources/taxonomy.d.ts
138
196
  declare function taxonomy(_options: unknown): never;
package/dist/define.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import { t as __exportAll } from "./rolldown-runtime.js";
2
+ import { t as isEmpty } from "./is-empty.js";
2
3
  //#region src/define/not-implemented.ts
3
4
  /**
4
5
  * Every builder is declared so the authoring surface is fixed, but none of
@@ -200,10 +201,36 @@ function enumeration(_options) {
200
201
  return notImplemented("define.enumeration");
201
202
  }
202
203
  //#endregion
204
+ //#region src/define/resources/model.ts
205
+ /**
206
+ * One model.
207
+ *
208
+ * Nothing here is validated. Format rules, `apiIdPlural` against `apiId` and
209
+ * uniqueness are plan-time checks, reported together rather than thrown one
210
+ * at a time while the config loads.
211
+ */
212
+ function model(input) {
213
+ return {
214
+ __typename: "Model",
215
+ apiId: input.apiId,
216
+ apiIdPlural: input.apiIdPlural,
217
+ displayName: input.displayName,
218
+ description: isEmpty(input.description) ? null : input.description
219
+ };
220
+ }
221
+ //#endregion
203
222
  //#region src/define/resources/environment.ts
204
- /** One environment: typed arrays per resource kind. The what. */
205
- function environment(_options) {
206
- return notImplemented("define.environment");
223
+ /**
224
+ * One environment: typed arrays per resource kind. The what.
225
+ *
226
+ * Ordering, keying and positions are not decided here. This returns the
227
+ * models as written; `convertToIR` turns them into the canonical form.
228
+ */
229
+ function environment(input) {
230
+ return {
231
+ __typename: "Environment",
232
+ models: [...input.models]
233
+ };
207
234
  }
208
235
  //#endregion
209
236
  //#region src/define/resources/graphqlRemoteSource.ts
@@ -216,11 +243,6 @@ function locale(_options) {
216
243
  return notImplemented("define.locale");
217
244
  }
218
245
  //#endregion
219
- //#region src/define/resources/model.ts
220
- function model(_options) {
221
- return notImplemented("define.model");
222
- }
223
- //#endregion
224
246
  //#region src/define/resources/restRemoteSource.ts
225
247
  function restRemoteSource(_options) {
226
248
  return notImplemented("define.restRemoteSource");
@@ -233,11 +255,19 @@ function stage(_options) {
233
255
  //#endregion
234
256
  //#region src/define/resources/target.ts
235
257
  /**
236
- * One environment of one project, its token variable, and the environment
237
- * definition to apply there. The where.
258
+ * One environment of one project, where to reach it and the token to do so,
259
+ * and the environment definition to apply there. The where.
238
260
  */
239
- function target(_options) {
240
- return notImplemented("define.target");
261
+ function target(input) {
262
+ return {
263
+ __typename: "Target",
264
+ name: input.name,
265
+ project: input.project.replace(/-/g, ""),
266
+ environment: input.environment,
267
+ endpoint: input.endpoint,
268
+ token: input.token,
269
+ apply: input.apply
270
+ };
241
271
  }
242
272
  //#endregion
243
273
  //#region src/define/resources/taxonomy.ts
@@ -0,0 +1,11 @@
1
+ //#region src/utils/is-empty.ts
2
+ /**
3
+ * A nullable string that was omitted or written as `""` canonicalises to
4
+ * `null`. Studio writes empty strings where it means nothing, and the server
5
+ * treats the two the same, so the IR keeps one of them.
6
+ */
7
+ function isEmpty(value) {
8
+ return value === void 0 || value === "";
9
+ }
10
+ //#endregion
11
+ export { isEmpty as t };
package/dist/version.js CHANGED
@@ -1,4 +1,4 @@
1
1
  //#region src/version.ts
2
- const VERSION = "0.0.1";
2
+ const VERSION = "0.0.2";
3
3
  //#endregion
4
4
  export { VERSION as t };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hygraph/cli",
3
- "version": "0.0.1",
3
+ "version": "0.0.2",
4
4
  "description": "Manage your Hygraph schema as code",
5
5
  "license": "UNLICENSED",
6
6
  "author": "Hygraph GmbH",
@@ -26,12 +26,21 @@
26
26
  "./package.json": "./package.json"
27
27
  },
28
28
  "publishConfig": {
29
- "access": "public"
29
+ "access": "restricted"
30
+ },
31
+ "dependencies": {
32
+ "jiti": "^2.7.0"
30
33
  },
31
34
  "devDependencies": {
32
35
  "@changesets/cli": "^2.29.7",
36
+ "@graphql-codegen/cli": "^7.4.1",
37
+ "@graphql-codegen/typed-document-node": "^7.1.0",
38
+ "@graphql-codegen/typescript": "^6.1.0",
39
+ "@graphql-codegen/typescript-operations": "^6.1.6",
40
+ "@graphql-typed-document-node/core": "^3.2.0",
33
41
  "@types/node": "^22.18.0",
34
42
  "commander": "^15.0.0",
43
+ "graphql": "^16.14.2",
35
44
  "oxfmt": "^0.68.0",
36
45
  "tsdown": "^0.23.0",
37
46
  "typescript": "^5.9.3",
@@ -46,6 +55,7 @@
46
55
  "build": "tsdown",
47
56
  "cli": "node bin/hygraph.js",
48
57
  "typecheck": "tsc",
58
+ "codegen": "graphql-codegen",
49
59
  "test": "vitest",
50
60
  "test:ci": "vitest --run",
51
61
  "format": "oxfmt",