@flexacms/cli 0.0.0-stage → 0.1.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Ivan Mercedes
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,23 @@
1
- # Temporary Holding Version
1
+ # @flexacms/cli
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Generate TypeScript types from the content models of your [Flexa](https://github.com/flexacms) workspace.
4
+
5
+ ```bash
6
+ FLEXA_URL=https://cms.example.com FLEXA_API_KEY=flx_... npx @flexacms/cli generate --out src/flexa.d.ts
7
+ ```
8
+
9
+ The file contains one `<Entity>Values` interface per content model and a `FlexaSchema` map. Pass it to any Flexa SDK:
10
+
11
+ ```ts
12
+ import type { FlexaSchema } from './flexa';
13
+
14
+ const flexa = createClient<FlexaSchema>({ url, apiKey });
15
+ ```
16
+
17
+ Field types map to their API values: translatable fields become `Localized<T>`, selects become unions of their options, repeaters become arrays of typed items, relationships become ids, and optional fields are `| null`. Run the command again whenever a content model changes.
18
+
19
+ | Option | Default |
20
+ | ------- | ------------------------------- |
21
+ | `--url` | `$FLEXA_URL` |
22
+ | `--key` | `$FLEXA_API_KEY` (Read ability) |
23
+ | `--out` | `flexa.d.ts` |
package/dist/cli.js ADDED
@@ -0,0 +1,202 @@
1
+ #!/usr/bin/env node
2
+
3
+ // src/cli.ts
4
+ import { mkdir, writeFile } from "fs/promises";
5
+ import { dirname, resolve } from "path";
6
+ import { parseArgs } from "util";
7
+ import { createClient, isFlexaError } from "@flexacms/client";
8
+
9
+ // src/generate.ts
10
+ function generateTypes(schemas) {
11
+ const lines = [
12
+ "// Generated by @flexacms/cli. Do not edit by hand: run `npx @flexacms/cli generate` again instead.",
13
+ "import type { Localized } from '@flexacms/client';",
14
+ ""
15
+ ];
16
+ const names = /* @__PURE__ */ new Map();
17
+ for (const schema of schemas) {
18
+ names.set(
19
+ schema.slug,
20
+ uniqueName(`${pascalCase(schema.slug)}Values`, names)
21
+ );
22
+ }
23
+ for (const schema of schemas) {
24
+ lines.push(
25
+ `/** ${schema.name}${schema.description ? ` \u2014 ${schema.description}` : ""} */`
26
+ );
27
+ lines.push(`export interface ${names.get(schema.slug)} {`);
28
+ for (const field of schema.fields.filter(
29
+ (item) => item.is_active !== false
30
+ )) {
31
+ const type = fieldType(field);
32
+ const doc = [field.label, field.description].filter(Boolean).join(" \u2014 ");
33
+ lines.push(` /** ${escapeComment(doc)} */`);
34
+ lines.push(
35
+ ` ${propertyName(field.key)}: ${field.is_required ? type : `${wrap(type)} | null`};`
36
+ );
37
+ }
38
+ lines.push("}", "");
39
+ }
40
+ lines.push("export interface FlexaSchema {");
41
+ for (const schema of schemas) {
42
+ lines.push(
43
+ ` ${propertyName(schema.slug)}: ${names.get(schema.slug)};`
44
+ );
45
+ }
46
+ lines.push("}", "");
47
+ return lines.join("\n");
48
+ }
49
+ function fieldType(field) {
50
+ const base = baseType(field);
51
+ return field.translatable ? `Localized<${base}>` : base;
52
+ }
53
+ function baseType(field) {
54
+ switch (field.type) {
55
+ case "number":
56
+ return "number";
57
+ case "boolean":
58
+ return "boolean";
59
+ case "select":
60
+ return optionsUnion(field.options);
61
+ case "multiselect":
62
+ return `${wrap(optionsUnion(field.options))}[]`;
63
+ case "tags":
64
+ return "string[]";
65
+ case "image":
66
+ case "file":
67
+ return field.multiple ? "string[]" : "string";
68
+ case "relationship":
69
+ return field.multiple ? "number[]" : "number";
70
+ case "json":
71
+ return "unknown";
72
+ case "address":
73
+ return `{ ${(field.address_parts ?? [
74
+ "street",
75
+ "city",
76
+ "state",
77
+ "postal_code",
78
+ "country"
79
+ ]).map((part) => `${propertyName(part)}?: string | null`).join("; ")} }`;
80
+ case "repeater":
81
+ return `Array<${repeaterItem(field.repeater_subfields)}>`;
82
+ default:
83
+ return "string";
84
+ }
85
+ }
86
+ function repeaterItem(subfields) {
87
+ if (!subfields || subfields.length === 0) {
88
+ return "Record<string, unknown>";
89
+ }
90
+ const properties = subfields.map((subfield) => {
91
+ const type = baseType({
92
+ type: subfield.type,
93
+ options: isOptionMap(subfield.options) ? subfield.options : null,
94
+ multiple: Boolean(
95
+ subfield.settings?.multiple ?? subfield.multiple
96
+ ),
97
+ address_parts: void 0,
98
+ repeater_subfields: null
99
+ });
100
+ return subfield.is_required === true ? `${propertyName(subfield.key)}: ${type}` : `${propertyName(subfield.key)}?: ${wrap(type)} | null`;
101
+ });
102
+ return `{ ${properties.join("; ")} }`;
103
+ }
104
+ function optionsUnion(options) {
105
+ const keys = isOptionMap(options) ? Object.keys(options) : [];
106
+ return keys.length > 0 ? keys.map((key) => JSON.stringify(key)).join(" | ") : "string";
107
+ }
108
+ function isOptionMap(value) {
109
+ return value !== null && typeof value === "object" && !Array.isArray(value);
110
+ }
111
+ function wrap(type) {
112
+ let depth = 0;
113
+ for (let index = 0; index < type.length; index++) {
114
+ const character = type[index];
115
+ if (character === "(" || character === "[" || character === "{" || character === "<") {
116
+ depth++;
117
+ } else if (character === ")" || character === "]" || character === "}" || character === ">") {
118
+ depth--;
119
+ } else if (depth === 0 && type.startsWith(" | ", index)) {
120
+ return `(${type})`;
121
+ }
122
+ }
123
+ return type;
124
+ }
125
+ function pascalCase(value) {
126
+ const name = value.split(/[^A-Za-z0-9]+/).filter(Boolean).map((part) => part.charAt(0).toUpperCase() + part.slice(1)).join("");
127
+ return /^[0-9]/.test(name) || name === "" ? `Entity${name}` : name;
128
+ }
129
+ function uniqueName(name, taken) {
130
+ const used = new Set(taken.values());
131
+ let candidate = name;
132
+ let suffix = 2;
133
+ while (used.has(candidate)) {
134
+ candidate = `${name}${suffix++}`;
135
+ }
136
+ return candidate;
137
+ }
138
+ function propertyName(key) {
139
+ return /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(key) ? key : JSON.stringify(key);
140
+ }
141
+ function escapeComment(text) {
142
+ return text.replace(/\*\//g, "*\\/").replace(/\s+/g, " ").trim();
143
+ }
144
+
145
+ // src/cli.ts
146
+ var HELP = `Usage: flexa generate [options]
147
+
148
+ Generate TypeScript types for your Flexa workspace's content models.
149
+
150
+ Options:
151
+ --url <url> Flexa URL (default: $FLEXA_URL)
152
+ --key <key> API key with the Read ability (default: $FLEXA_API_KEY)
153
+ --out <file> Output file (default: flexa.d.ts)
154
+ -h, --help Show this help
155
+ `;
156
+ async function main(argv) {
157
+ const { positionals, values } = parseArgs({
158
+ args: argv,
159
+ allowPositionals: true,
160
+ options: {
161
+ url: { type: "string" },
162
+ key: { type: "string" },
163
+ out: { type: "string", default: "flexa.d.ts" },
164
+ help: { type: "boolean", short: "h" }
165
+ }
166
+ });
167
+ if (values.help || positionals[0] !== "generate") {
168
+ process.stdout.write(HELP);
169
+ return values.help ? 0 : 1;
170
+ }
171
+ const url = values.url ?? process.env.FLEXA_URL;
172
+ const apiKey = values.key ?? process.env.FLEXA_API_KEY;
173
+ if (!url || !apiKey) {
174
+ process.stderr.write(
175
+ "Missing --url/--key (or the FLEXA_URL and FLEXA_API_KEY environment variables).\n"
176
+ );
177
+ return 1;
178
+ }
179
+ const client = createClient({ url, apiKey });
180
+ const entities = await client.entities();
181
+ const schemas = await Promise.all(
182
+ entities.map((entity) => client.entity(entity.slug).schema())
183
+ );
184
+ const output = resolve(process.cwd(), values.out ?? "flexa.d.ts");
185
+ await mkdir(dirname(output), { recursive: true });
186
+ await writeFile(output, generateTypes(schemas));
187
+ process.stdout.write(
188
+ `Generated types for ${schemas.length} content model(s) in ${output}
189
+ `
190
+ );
191
+ return 0;
192
+ }
193
+ main(process.argv.slice(2)).then(
194
+ (code) => process.exit(code),
195
+ (error) => {
196
+ process.stderr.write(
197
+ `${isFlexaError(error) ? `Flexa API error (${error.status}): ` : ""}${error instanceof Error ? error.message : String(error)}
198
+ `
199
+ );
200
+ process.exit(1);
201
+ }
202
+ );
@@ -0,0 +1,9 @@
1
+ import { EntitySchema } from '@flexacms/client';
2
+
3
+ /**
4
+ * Turn entity schemas into TypeScript declarations: one `<Entity>Values`
5
+ * interface per entity and a `FlexaSchema` map for `createClient<FlexaSchema>()`.
6
+ */
7
+ declare function generateTypes(schemas: EntitySchema[]): string;
8
+
9
+ export { generateTypes };
package/dist/index.js ADDED
@@ -0,0 +1,138 @@
1
+ // src/generate.ts
2
+ function generateTypes(schemas) {
3
+ const lines = [
4
+ "// Generated by @flexacms/cli. Do not edit by hand: run `npx @flexacms/cli generate` again instead.",
5
+ "import type { Localized } from '@flexacms/client';",
6
+ ""
7
+ ];
8
+ const names = /* @__PURE__ */ new Map();
9
+ for (const schema of schemas) {
10
+ names.set(
11
+ schema.slug,
12
+ uniqueName(`${pascalCase(schema.slug)}Values`, names)
13
+ );
14
+ }
15
+ for (const schema of schemas) {
16
+ lines.push(
17
+ `/** ${schema.name}${schema.description ? ` \u2014 ${schema.description}` : ""} */`
18
+ );
19
+ lines.push(`export interface ${names.get(schema.slug)} {`);
20
+ for (const field of schema.fields.filter(
21
+ (item) => item.is_active !== false
22
+ )) {
23
+ const type = fieldType(field);
24
+ const doc = [field.label, field.description].filter(Boolean).join(" \u2014 ");
25
+ lines.push(` /** ${escapeComment(doc)} */`);
26
+ lines.push(
27
+ ` ${propertyName(field.key)}: ${field.is_required ? type : `${wrap(type)} | null`};`
28
+ );
29
+ }
30
+ lines.push("}", "");
31
+ }
32
+ lines.push("export interface FlexaSchema {");
33
+ for (const schema of schemas) {
34
+ lines.push(
35
+ ` ${propertyName(schema.slug)}: ${names.get(schema.slug)};`
36
+ );
37
+ }
38
+ lines.push("}", "");
39
+ return lines.join("\n");
40
+ }
41
+ function fieldType(field) {
42
+ const base = baseType(field);
43
+ return field.translatable ? `Localized<${base}>` : base;
44
+ }
45
+ function baseType(field) {
46
+ switch (field.type) {
47
+ case "number":
48
+ return "number";
49
+ case "boolean":
50
+ return "boolean";
51
+ case "select":
52
+ return optionsUnion(field.options);
53
+ case "multiselect":
54
+ return `${wrap(optionsUnion(field.options))}[]`;
55
+ case "tags":
56
+ return "string[]";
57
+ case "image":
58
+ case "file":
59
+ return field.multiple ? "string[]" : "string";
60
+ case "relationship":
61
+ return field.multiple ? "number[]" : "number";
62
+ case "json":
63
+ return "unknown";
64
+ case "address":
65
+ return `{ ${(field.address_parts ?? [
66
+ "street",
67
+ "city",
68
+ "state",
69
+ "postal_code",
70
+ "country"
71
+ ]).map((part) => `${propertyName(part)}?: string | null`).join("; ")} }`;
72
+ case "repeater":
73
+ return `Array<${repeaterItem(field.repeater_subfields)}>`;
74
+ default:
75
+ return "string";
76
+ }
77
+ }
78
+ function repeaterItem(subfields) {
79
+ if (!subfields || subfields.length === 0) {
80
+ return "Record<string, unknown>";
81
+ }
82
+ const properties = subfields.map((subfield) => {
83
+ const type = baseType({
84
+ type: subfield.type,
85
+ options: isOptionMap(subfield.options) ? subfield.options : null,
86
+ multiple: Boolean(
87
+ subfield.settings?.multiple ?? subfield.multiple
88
+ ),
89
+ address_parts: void 0,
90
+ repeater_subfields: null
91
+ });
92
+ return subfield.is_required === true ? `${propertyName(subfield.key)}: ${type}` : `${propertyName(subfield.key)}?: ${wrap(type)} | null`;
93
+ });
94
+ return `{ ${properties.join("; ")} }`;
95
+ }
96
+ function optionsUnion(options) {
97
+ const keys = isOptionMap(options) ? Object.keys(options) : [];
98
+ return keys.length > 0 ? keys.map((key) => JSON.stringify(key)).join(" | ") : "string";
99
+ }
100
+ function isOptionMap(value) {
101
+ return value !== null && typeof value === "object" && !Array.isArray(value);
102
+ }
103
+ function wrap(type) {
104
+ let depth = 0;
105
+ for (let index = 0; index < type.length; index++) {
106
+ const character = type[index];
107
+ if (character === "(" || character === "[" || character === "{" || character === "<") {
108
+ depth++;
109
+ } else if (character === ")" || character === "]" || character === "}" || character === ">") {
110
+ depth--;
111
+ } else if (depth === 0 && type.startsWith(" | ", index)) {
112
+ return `(${type})`;
113
+ }
114
+ }
115
+ return type;
116
+ }
117
+ function pascalCase(value) {
118
+ const name = value.split(/[^A-Za-z0-9]+/).filter(Boolean).map((part) => part.charAt(0).toUpperCase() + part.slice(1)).join("");
119
+ return /^[0-9]/.test(name) || name === "" ? `Entity${name}` : name;
120
+ }
121
+ function uniqueName(name, taken) {
122
+ const used = new Set(taken.values());
123
+ let candidate = name;
124
+ let suffix = 2;
125
+ while (used.has(candidate)) {
126
+ candidate = `${name}${suffix++}`;
127
+ }
128
+ return candidate;
129
+ }
130
+ function propertyName(key) {
131
+ return /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(key) ? key : JSON.stringify(key);
132
+ }
133
+ function escapeComment(text) {
134
+ return text.replace(/\*\//g, "*\\/").replace(/\s+/g, " ").trim();
135
+ }
136
+ export {
137
+ generateTypes
138
+ };
package/package.json CHANGED
@@ -1,6 +1,50 @@
1
1
  {
2
- "name": "@flexacms/cli",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
2
+ "name": "@flexacms/cli",
3
+ "version": "0.1.0",
4
+ "description": "Generate TypeScript types from your Flexa CMS content models.",
5
+ "keywords": [
6
+ "cms",
7
+ "codegen",
8
+ "flexa",
9
+ "headless",
10
+ "typescript"
11
+ ],
12
+ "homepage": "https://github.com/flexacms/sdk/tree/main/packages/cli#readme",
13
+ "bugs": {
14
+ "url": "https://github.com/flexacms/sdk/issues"
15
+ },
16
+ "license": "MIT",
17
+ "repository": {
18
+ "type": "git",
19
+ "url": "git+https://github.com/flexacms/sdk.git",
20
+ "directory": "packages/cli"
21
+ },
22
+ "bin": {
23
+ "flexa": "./dist/cli.js"
24
+ },
25
+ "files": [
26
+ "dist",
27
+ "README.md",
28
+ "LICENSE"
29
+ ],
30
+ "type": "module",
31
+ "exports": {
32
+ ".": {
33
+ "types": "./dist/index.d.ts",
34
+ "default": "./dist/index.js"
35
+ }
36
+ },
37
+ "publishConfig": {
38
+ "access": "public"
39
+ },
40
+ "scripts": {
41
+ "build": "tsup",
42
+ "typecheck": "tsc -p tsconfig.json"
43
+ },
44
+ "dependencies": {
45
+ "@flexacms/client": "^0.1.0"
46
+ },
47
+ "engines": {
48
+ "node": ">=20"
49
+ }
50
+ }