@tinacms/cli 0.57.1 → 0.58.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/dist/index.js ADDED
@@ -0,0 +1,1182 @@
1
+ var __create = Object.create;
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __getProtoOf = Object.getPrototypeOf;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ var __markAsModule = (target) => __defProp(target, "__esModule", { value: true });
8
+ var __esm = (fn, res) => function __init() {
9
+ return fn && (res = (0, fn[Object.keys(fn)[0]])(fn = 0)), res;
10
+ };
11
+ var __export = (target, all) => {
12
+ __markAsModule(target);
13
+ for (var name2 in all)
14
+ __defProp(target, name2, { get: all[name2], enumerable: true });
15
+ };
16
+ var __reExport = (target, module2, desc) => {
17
+ if (module2 && typeof module2 === "object" || typeof module2 === "function") {
18
+ for (let key of __getOwnPropNames(module2))
19
+ if (!__hasOwnProp.call(target, key) && key !== "default")
20
+ __defProp(target, key, { get: () => module2[key], enumerable: !(desc = __getOwnPropDesc(module2, key)) || desc.enumerable });
21
+ }
22
+ return target;
23
+ };
24
+ var __toModule = (module2) => {
25
+ return __reExport(__markAsModule(__defProp(module2 != null ? __create(__getProtoOf(module2)) : {}, "default", module2 && module2.__esModule && "default" in module2 ? { get: () => module2.default, enumerable: true } : { value: module2, enumerable: true })), module2);
26
+ };
27
+
28
+ // pnp:/Users/jeffsee/code/tinacms/packages/@tinacms/cli/src/cmds/start-server/server.ts
29
+ var server_exports = {};
30
+ __export(server_exports, {
31
+ default: () => server_default
32
+ });
33
+ var import_cors, import_http, import_express, import_altair_express_middleware, import_body_parser, GITHUB_ACCESS_TOKEN, gqlServer, server_default;
34
+ var init_server = __esm({
35
+ "pnp:/Users/jeffsee/code/tinacms/packages/@tinacms/cli/src/cmds/start-server/server.ts"() {
36
+ import_cors = __toModule(require("cors"));
37
+ import_http = __toModule(require("http"));
38
+ import_express = __toModule(require("express"));
39
+ import_altair_express_middleware = __toModule(require("altair-express-middleware"));
40
+ import_body_parser = __toModule(require("body-parser"));
41
+ GITHUB_ACCESS_TOKEN = process.env.GITHUB_PERSONAL_ACCESS_TOKEN;
42
+ gqlServer = async (database) => {
43
+ const gqlPackage = require("@tinacms/graphql");
44
+ const app = (0, import_express.default)();
45
+ const server = import_http.default.createServer(app);
46
+ app.use((0, import_cors.default)());
47
+ app.use(import_body_parser.default.json());
48
+ app.use("/altair", (0, import_altair_express_middleware.altairExpress)({
49
+ endpointURL: "/graphql",
50
+ initialQuery: `# Welcome to Tina!
51
+ # We've got a simple query set up for you to get started
52
+ # but there's plenty more for you to explore on your own!
53
+ query MyQuery {
54
+ getCollections {
55
+ documents {
56
+ id
57
+ sys {
58
+ filename
59
+ extension
60
+ }
61
+ }
62
+ }
63
+ }`
64
+ }));
65
+ app.post("/graphql", async (req, res) => {
66
+ const { query, variables } = req.body;
67
+ const result = await gqlPackage.resolve({
68
+ database,
69
+ query,
70
+ variables
71
+ });
72
+ return res.json(result);
73
+ });
74
+ app.get("/list-branches", async (req, res) => {
75
+ try {
76
+ const { query } = req;
77
+ const { owner, repo } = query;
78
+ const result = await gqlPackage.listBranches({
79
+ auth: GITHUB_ACCESS_TOKEN,
80
+ owner,
81
+ repo
82
+ });
83
+ return res.json(result.data);
84
+ } catch (error) {
85
+ console.error("There was a problem fetching the branches.", error);
86
+ }
87
+ });
88
+ app.post("/create-branch", async (req, res) => {
89
+ try {
90
+ const { owner, repo, name: name2, baseBranch } = req.body;
91
+ const result = await gqlPackage.createBranch({
92
+ auth: GITHUB_ACCESS_TOKEN,
93
+ owner,
94
+ repo,
95
+ baseBranch,
96
+ name: name2
97
+ });
98
+ return res.json(result);
99
+ } catch (error) {
100
+ res.end();
101
+ console.error("There was a problem creating a new branch.", error);
102
+ }
103
+ });
104
+ return server;
105
+ };
106
+ server_default = gqlServer;
107
+ }
108
+ });
109
+
110
+ // pnp:/Users/jeffsee/code/tinacms/packages/@tinacms/cli/src/index.ts
111
+ __export(exports, {
112
+ defineSchema: () => defineSchema,
113
+ init: () => init
114
+ });
115
+ var commander = __toModule(require("commander"));
116
+
117
+ // pnp:/Users/jeffsee/code/tinacms/packages/@tinacms/cli/package.json
118
+ var name = "@tinacms/cli";
119
+ var version = "0.58.2";
120
+
121
+ // pnp:/Users/jeffsee/code/tinacms/packages/@tinacms/cli/src/utils/theme.ts
122
+ var import_chalk = __toModule(require("chalk"));
123
+ var successText = import_chalk.default.bold.green;
124
+ var dangerText = import_chalk.default.bold.red;
125
+ var neutralText = import_chalk.default.bold.cyan;
126
+ var labelText = import_chalk.default.bold;
127
+ var cmdText = import_chalk.default.inverse;
128
+ var logText = import_chalk.default.italic.gray;
129
+ var warnText = import_chalk.default.yellowBright.bgBlack;
130
+ var CONFIRMATION_TEXT = import_chalk.default.dim("enter to confirm");
131
+
132
+ // pnp:/Users/jeffsee/code/tinacms/packages/@tinacms/cli/src/middleware.ts
133
+ var chain = async (cmds, options) => {
134
+ const ctx = {};
135
+ const next = async (middlewareIndex) => {
136
+ if (middlewareIndex >= cmds.length) {
137
+ process.exit(0);
138
+ }
139
+ try {
140
+ await cmds[middlewareIndex](ctx, () => next(middlewareIndex + 1), options || {});
141
+ } catch (err) {
142
+ console.error(` ${dangerText(err)}`);
143
+ process.exit(1);
144
+ }
145
+ };
146
+ if (cmds.length > 0) {
147
+ await next(0);
148
+ }
149
+ };
150
+
151
+ // pnp:/Users/jeffsee/code/tinacms/packages/@tinacms/cli/src/cmds/query-gen/attachSchema.ts
152
+ var import_graphql = __toModule(require("@tinacms/graphql"));
153
+
154
+ // pnp:/Users/jeffsee/code/tinacms/packages/@tinacms/cli/src/logger/index.ts
155
+ var import_log4js = __toModule(require("log4js"));
156
+ var logger = import_log4js.default.getLogger();
157
+ import_log4js.default.configure({
158
+ appenders: {
159
+ out: { type: "stdout", layout: { type: "messagePassThrough" } }
160
+ },
161
+ categories: { default: { appenders: ["out"], level: "info" } }
162
+ });
163
+ logger.level = "info";
164
+
165
+ // pnp:/Users/jeffsee/code/tinacms/packages/@tinacms/cli/src/cmds/query-gen/attachSchema.ts
166
+ async function attachSchema(ctx, next, options) {
167
+ logger.info(logText("Building schema..."));
168
+ const rootPath = process.cwd();
169
+ const bridge = new import_graphql.FilesystemBridge(rootPath);
170
+ const store = new import_graphql.FilesystemStore({ rootPath });
171
+ const database = await (0, import_graphql.createDatabase)({ store, bridge });
172
+ const schema = await (0, import_graphql.buildSchema)(rootPath, database);
173
+ ctx.schema = schema;
174
+ next();
175
+ }
176
+
177
+ // pnp:/Users/jeffsee/code/tinacms/packages/@tinacms/cli/src/codegen/index.ts
178
+ var import_graphql5 = __toModule(require("graphql"));
179
+ var import_core = __toModule(require("@graphql-codegen/core"));
180
+ var import_typescript = __toModule(require("@graphql-codegen/typescript"));
181
+ var import_typescript_operations = __toModule(require("@graphql-codegen/typescript-operations"));
182
+
183
+ // pnp:/Users/jeffsee/code/tinacms/packages/@tinacms/cli/src/codegen/plugin.ts
184
+ var AddGeneratedClientFunc = (_schema, _documents, _config, _info) => {
185
+ return `
186
+ // TinaSDK generated code
187
+ import { getStaticPropsForTina } from 'tinacms'
188
+ const requester: (doc: any, vars?: any, options?: any) => Promise<any> = async (
189
+ doc,
190
+ vars,
191
+ _options
192
+ ) => {
193
+ // const data = await tinaClient.request(doc, { variables: vars });
194
+ const res = await await getStaticPropsForTina({query: doc, variables: vars})
195
+ return res
196
+ };
197
+
198
+ /**
199
+ * @experimental this class can be used but may change in the future
200
+ **/
201
+ export const ExperimentalGetTinaClient = ()=>getSdk(requester)
202
+ `;
203
+ };
204
+ var AddGeneratedClient = {
205
+ plugin: AddGeneratedClientFunc
206
+ };
207
+
208
+ // pnp:/Users/jeffsee/code/tinacms/packages/@tinacms/cli/src/codegen/sdkPlugin/index.ts
209
+ var import_graphql3 = __toModule(require("graphql"));
210
+ var import_graphql4 = __toModule(require("graphql"));
211
+ var import_path = __toModule(require("path"));
212
+
213
+ // pnp:/Users/jeffsee/code/tinacms/packages/@tinacms/cli/src/codegen/sdkPlugin/visitor.ts
214
+ var import_visitor_plugin_common = __toModule(require("@graphql-codegen/visitor-plugin-common"));
215
+ var import_auto_bind = __toModule(require("auto-bind"));
216
+ var import_graphql2 = __toModule(require("graphql"));
217
+ var GenericSdkVisitor = class extends import_visitor_plugin_common.ClientSideBaseVisitor {
218
+ constructor(schema, fragments, rawConfig) {
219
+ super(schema, fragments, rawConfig, {
220
+ usingObservableFrom: rawConfig.usingObservableFrom
221
+ });
222
+ this._operationsToInclude = [];
223
+ (0, import_auto_bind.default)(this);
224
+ if (this.config.usingObservableFrom) {
225
+ this._additionalImports.push(this.config.usingObservableFrom);
226
+ }
227
+ if (this.config.documentMode !== import_visitor_plugin_common.DocumentMode.string) {
228
+ }
229
+ }
230
+ buildOperation(node, documentVariableName, operationType, operationResultType, operationVariablesTypes) {
231
+ if (node.name == null) {
232
+ throw new Error("Plugin 'generic-sdk' cannot generate SDK for unnamed operation.\n\n" + (0, import_graphql2.print)(node));
233
+ } else {
234
+ this._operationsToInclude.push({
235
+ node,
236
+ documentVariableName,
237
+ operationType,
238
+ operationResultType: `{data: ${operationResultType}, variables: ${operationVariablesTypes}, query: string}`,
239
+ operationVariablesTypes
240
+ });
241
+ }
242
+ return null;
243
+ }
244
+ get sdkContent() {
245
+ const usingObservable = !!this.config.usingObservableFrom;
246
+ const allPossibleActions = this._operationsToInclude.map((o) => {
247
+ const optionalVariables = !o.node.variableDefinitions || o.node.variableDefinitions.length === 0 || o.node.variableDefinitions.every((v) => v.type.kind !== import_graphql2.Kind.NON_NULL_TYPE || v.defaultValue);
248
+ const returnType = usingObservable && o.operationType === "Subscription" ? "Observable" : "Promise";
249
+ return `${o.node.name.value}(variables${optionalVariables ? "?" : ""}: ${o.operationVariablesTypes}, options?: C): ${returnType}<${o.operationResultType}> {
250
+ return requester<${o.operationResultType}, ${o.operationVariablesTypes}>(${o.documentVariableName}, variables, options);
251
+ }`;
252
+ }).map((s) => (0, import_visitor_plugin_common.indentMultiline)(s, 2));
253
+ return `export type Requester<C= {}> = <R, V>(doc: ${this.config.documentMode === import_visitor_plugin_common.DocumentMode.string ? "string" : "DocumentNode"}, vars?: V, options?: C) => ${usingObservable ? "Promise<R> & Observable<R>" : "Promise<R>"}
254
+ export function getSdk<C>(requester: Requester<C>) {
255
+ return {
256
+ ${allPossibleActions.join(",\n")}
257
+ };
258
+ }
259
+ export type Sdk = ReturnType<typeof getSdk>;`;
260
+ }
261
+ };
262
+
263
+ // pnp:/Users/jeffsee/code/tinacms/packages/@tinacms/cli/src/codegen/sdkPlugin/index.ts
264
+ var plugin = (schema, documents, config) => {
265
+ const allAst = (0, import_graphql4.concatAST)(documents.reduce((prev, v) => {
266
+ return [...prev, v.document];
267
+ }, []));
268
+ const allFragments = [
269
+ ...allAst.definitions.filter((d) => d.kind === import_graphql4.Kind.FRAGMENT_DEFINITION).map((fragmentDef) => ({
270
+ node: fragmentDef,
271
+ name: fragmentDef.name.value,
272
+ onType: fragmentDef.typeCondition.name.value,
273
+ isExternal: false
274
+ })),
275
+ ...config.externalFragments || []
276
+ ];
277
+ const visitor = new GenericSdkVisitor(schema, allFragments, config);
278
+ const visitorResult = (0, import_graphql3.visit)(allAst, { leave: visitor });
279
+ return {
280
+ prepend: visitor.getImports(),
281
+ content: [
282
+ visitor.fragments,
283
+ ...visitorResult.definitions.filter((t) => typeof t === "string"),
284
+ visitor.sdkContent
285
+ ].join("\n")
286
+ };
287
+ };
288
+
289
+ // pnp:/Users/jeffsee/code/tinacms/packages/@tinacms/cli/src/codegen/index.ts
290
+ var import_load = __toModule(require("@graphql-tools/load"));
291
+ var import_graphql_file_loader = __toModule(require("@graphql-tools/graphql-file-loader"));
292
+ var generateTypes = async (schema, queryPathGlob = process.cwd(), fragDocPath = process.cwd(), options = { noSDK: false }) => {
293
+ logger.info("Generating types...");
294
+ try {
295
+ let docs = [];
296
+ let fragDocs = [];
297
+ try {
298
+ if (!options.noSDK) {
299
+ docs = await (0, import_load.loadDocuments)(queryPathGlob, {
300
+ loaders: [new import_graphql_file_loader.GraphQLFileLoader()]
301
+ });
302
+ }
303
+ } catch (e) {
304
+ let showErrorMessage = true;
305
+ const message = e.message || "";
306
+ if (message.includes("Unable to find any GraphQL type definitions for the following pointers:")) {
307
+ showErrorMessage = false;
308
+ }
309
+ if (showErrorMessage) {
310
+ console.error(e);
311
+ }
312
+ }
313
+ try {
314
+ if (!options.noSDK) {
315
+ fragDocs = await (0, import_load.loadDocuments)(fragDocPath, {
316
+ loaders: [new import_graphql_file_loader.GraphQLFileLoader()]
317
+ });
318
+ }
319
+ } catch (error) {
320
+ console.error(error);
321
+ }
322
+ const res = await (0, import_core.codegen)({
323
+ filename: process.cwd(),
324
+ schema: (0, import_graphql5.parse)((0, import_graphql5.printSchema)(schema)),
325
+ documents: [...docs, ...fragDocs],
326
+ config: {},
327
+ plugins: [
328
+ { typescript: {} },
329
+ { typescriptOperations: {} },
330
+ {
331
+ typescriptSdk: {
332
+ gqlImport: "tinacms#gql",
333
+ documentNodeImport: "tinacms#DocumentNode"
334
+ }
335
+ },
336
+ { AddGeneratedClient: {} }
337
+ ],
338
+ pluginMap: {
339
+ typescript: {
340
+ plugin: import_typescript.plugin
341
+ },
342
+ typescriptOperations: {
343
+ plugin: import_typescript_operations.plugin
344
+ },
345
+ typescriptSdk: {
346
+ plugin
347
+ },
348
+ AddGeneratedClient
349
+ }
350
+ });
351
+ return res;
352
+ } catch (e) {
353
+ console.error(e);
354
+ }
355
+ };
356
+
357
+ // pnp:/Users/jeffsee/code/tinacms/packages/@tinacms/cli/src/cmds/query-gen/genTypes.ts
358
+ var import_graphql6 = __toModule(require("graphql"));
359
+ var import_fs_extra = __toModule(require("fs-extra"));
360
+ async function genTypes({ schema }, next, options) {
361
+ const typesPath = process.cwd() + "/.tina/__generated__/types.ts";
362
+ const fragPath = process.cwd() + "/.tina/__generated__/*.{graphql,gql}";
363
+ const queryPathGlob = process.cwd() + "/.tina/queries/**/*.{graphql,gql}";
364
+ const typescriptTypes = await generateTypes(schema, queryPathGlob, fragPath, options);
365
+ await import_fs_extra.default.outputFile(typesPath, `//@ts-nocheck
366
+ // DO NOT MODIFY THIS FILE. This file is automatically generated by Tina
367
+ ${typescriptTypes}
368
+ `);
369
+ logger.info(`Typescript types => ${successText(typesPath)}`);
370
+ const schemaString = await (0, import_graphql6.printSchema)(schema);
371
+ const schemaPath = process.cwd() + "/.tina/__generated__/schema.gql";
372
+ await import_fs_extra.default.outputFile(schemaPath, `# DO NOT MODIFY THIS FILE. This file is automatically generated by Tina
373
+ ${schemaString}
374
+ schema {
375
+ query: Query
376
+ mutation: Mutation
377
+ }
378
+ `);
379
+ logger.info(`GraphQL types ====> ${successText(schemaPath)}`);
380
+ next();
381
+ }
382
+
383
+ // pnp:/Users/jeffsee/code/tinacms/packages/@tinacms/cli/src/cmds/start-server/index.ts
384
+ var import_child_process = __toModule(require("child_process"));
385
+ var import_path3 = __toModule(require("path"));
386
+ var import_graphql7 = __toModule(require("@tinacms/graphql"));
387
+
388
+ // pnp:/Users/jeffsee/code/tinacms/packages/@tinacms/cli/src/cmds/compile/index.ts
389
+ var import_fast_glob = __toModule(require("fast-glob"));
390
+ var import_normalize_path = __toModule(require("normalize-path"));
391
+ var import_path2 = __toModule(require("path"));
392
+ var import_fs_extra2 = __toModule(require("fs-extra"));
393
+ var ts = __toModule(require("typescript"));
394
+
395
+ // pnp:/Users/jeffsee/code/tinacms/packages/@tinacms/cli/src/cmds/compile/defaultSchema.ts
396
+ var defaultSchema = `
397
+ import { defineSchema } from "@tinacms/cli";
398
+
399
+ export default defineSchema({
400
+ collections: [
401
+ {
402
+ label: "Blog Posts",
403
+ name: "posts",
404
+ path: "content/posts",
405
+ fields: [
406
+ {
407
+ type: "string",
408
+ label: "Title",
409
+ name: "title",
410
+ },
411
+ {
412
+ type: "string",
413
+ label: "Blog Post Body",
414
+ name: "body",
415
+ isBody: true,
416
+ ui: {
417
+ component: "textarea"
418
+ },
419
+ },
420
+ ],
421
+ },
422
+ ],
423
+ });
424
+ `;
425
+
426
+ // pnp:/Users/jeffsee/code/tinacms/packages/@tinacms/cli/src/cmds/compile/index.ts
427
+ var tinaPath = import_path2.default.join(process.cwd(), ".tina");
428
+ var tinaGeneratedPath = import_path2.default.join(tinaPath, "__generated__");
429
+ var tinaTempPath = import_path2.default.join(tinaGeneratedPath, "temp");
430
+ var tinaConfigPath = import_path2.default.join(tinaGeneratedPath, "config");
431
+ var resetGeneratedFolder = async () => {
432
+ try {
433
+ await import_fs_extra2.default.rmdir(tinaGeneratedPath, {
434
+ recursive: true
435
+ });
436
+ } catch (e) {
437
+ console.log(e);
438
+ }
439
+ await import_fs_extra2.default.mkdir(tinaGeneratedPath);
440
+ await import_fs_extra2.default.outputFile(import_path2.default.join(tinaGeneratedPath, ".gitignore"), "db");
441
+ };
442
+ var compile = async (_ctx, _next) => {
443
+ logger.info(logText("Compiling..."));
444
+ if (!import_fs_extra2.default.existsSync(tinaPath) || !import_fs_extra2.default.existsSync(import_path2.default.join(tinaPath, "schema.ts"))) {
445
+ logger.info(dangerText(`
446
+ .tina/schema.ts not found, Creating one for you...
447
+ See Documentation: https://tina.io/docs/tina-cloud/cli/#getting-started"
448
+ `));
449
+ const file = import_path2.default.join(tinaPath, "schema.ts");
450
+ await import_fs_extra2.default.ensureFile(file);
451
+ await import_fs_extra2.default.writeFile(file, defaultSchema);
452
+ }
453
+ await transpile2(tinaPath, tinaTempPath);
454
+ Object.keys(require.cache).map((key) => {
455
+ if (key.startsWith(tinaTempPath)) {
456
+ delete require.cache[require.resolve(key)];
457
+ }
458
+ });
459
+ const schemaFunc = require(import_path2.default.join(tinaTempPath, "schema.js"));
460
+ const schemaObject = schemaFunc.default;
461
+ await import_fs_extra2.default.outputFile(import_path2.default.join(tinaConfigPath, "schema.json"), JSON.stringify(schemaObject, null, 2));
462
+ await import_fs_extra2.default.remove(tinaTempPath);
463
+ };
464
+ var transpile2 = async (projectDir, tempDir) => {
465
+ logger.info(logText("Transpiling..."));
466
+ const posixProjectDir = (0, import_normalize_path.default)(projectDir);
467
+ const posixTempDir = (0, import_normalize_path.default)(tempDir);
468
+ return Promise.all(import_fast_glob.default.sync(import_path2.default.join(projectDir, "**", "*.ts").replace(/\\/g, "/"), {
469
+ ignore: [
470
+ import_path2.default.join(projectDir, "__generated__", "**", "*.ts").replace(/\\/g, "/")
471
+ ]
472
+ }).map(async function(file) {
473
+ const fullPath = import_path2.default.resolve(file);
474
+ const contents = await import_fs_extra2.default.readFileSync(fullPath).toString();
475
+ const newContent = ts.transpile(contents);
476
+ const newPath = file.replace(posixProjectDir, posixTempDir).replace(".ts", ".js");
477
+ await import_fs_extra2.default.outputFile(newPath, newContent);
478
+ return true;
479
+ }));
480
+ };
481
+ var defineSchema = (config) => {
482
+ return config;
483
+ };
484
+
485
+ // pnp:/Users/jeffsee/code/tinacms/packages/@tinacms/cli/src/cmds/start-server/index.ts
486
+ var import_chokidar = __toModule(require("chokidar"));
487
+ var gqlPackageFile = require.resolve("@tinacms/graphql");
488
+ async function startServer(_ctx, _next, { port = 4001, command, noWatch, experimentalData, noSDK }) {
489
+ const rootPath = process.cwd();
490
+ if (!process.env.CI && !noWatch) {
491
+ await resetGeneratedFolder();
492
+ }
493
+ const bridge = new import_graphql7.FilesystemBridge(rootPath);
494
+ const store = experimentalData ? new import_graphql7.LevelStore(rootPath) : new import_graphql7.FilesystemStore({ rootPath });
495
+ const shouldBuild = bridge.supportsBuilding();
496
+ const database = await (0, import_graphql7.createDatabase)({ store, bridge });
497
+ const startSubprocess = () => {
498
+ if (typeof command === "string") {
499
+ const commands = command.split(" ");
500
+ const firstCommand = commands[0];
501
+ const args = commands.slice(1) || [];
502
+ const ps = import_child_process.default.spawn(firstCommand, args, {
503
+ stdio: "inherit",
504
+ shell: true
505
+ });
506
+ ps.on("error", (code) => {
507
+ logger.error(dangerText(`An error has occurred in the Next.js child process. Error message below`));
508
+ logger.error(`name: ${code.name}
509
+ message: ${code.message}
510
+
511
+ stack: ${code.stack || "No stack was provided"}`);
512
+ });
513
+ ps.on("close", (code) => {
514
+ logger.info(`child process exited with code ${code}`);
515
+ process.exit(code);
516
+ });
517
+ }
518
+ };
519
+ let ready = false;
520
+ if (!noWatch && !process.env.CI) {
521
+ import_chokidar.default.watch([`${rootPath}/**/*.{ts,gql,graphql}`], {
522
+ ignored: `${import_path3.default.resolve(rootPath)}/.tina/__generated__/**/*`
523
+ }).on("ready", async () => {
524
+ console.log("Generating Tina config");
525
+ try {
526
+ if (shouldBuild) {
527
+ await build(noSDK);
528
+ }
529
+ ready = true;
530
+ startSubprocess();
531
+ } catch (e) {
532
+ logger.info(dangerText(`${e.message}`));
533
+ console.log(e);
534
+ process.exit(0);
535
+ }
536
+ }).on("all", async () => {
537
+ if (ready) {
538
+ logger.info("Tina change detected, regenerating config");
539
+ try {
540
+ if (shouldBuild) {
541
+ await build(noSDK);
542
+ }
543
+ } catch (e) {
544
+ logger.info(dangerText("Compilation failed with errors. Server has not been restarted.") + ` see error below
545
+ ${e.message}`);
546
+ }
547
+ }
548
+ });
549
+ }
550
+ const build = async (noSDK2) => {
551
+ await compile(null, null);
552
+ const schema = await (0, import_graphql7.buildSchema)(rootPath, database);
553
+ await genTypes({ schema }, () => {
554
+ }, { noSDK: noSDK2 });
555
+ };
556
+ const state = {
557
+ server: null,
558
+ sockets: []
559
+ };
560
+ let isReady = false;
561
+ const start = async () => {
562
+ const s = (init_server(), server_exports);
563
+ state.server = await s.default(database);
564
+ state.server.listen(port, () => {
565
+ logger.info(`Started Filesystem GraphQL server on port: ${port}`);
566
+ logger.info(`Visit the playground at http://localhost:${port}/altair/`);
567
+ });
568
+ state.server.on("error", function(e) {
569
+ if (e.code === "EADDRINUSE") {
570
+ logger.error(dangerText(`Port 4001 already in use`));
571
+ process.exit();
572
+ }
573
+ throw e;
574
+ });
575
+ state.server.on("connection", (socket) => {
576
+ state.sockets.push(socket);
577
+ });
578
+ };
579
+ const restart = async () => {
580
+ logger.info("Detected change to gql package, restarting...");
581
+ delete require.cache[gqlPackageFile];
582
+ state.sockets.forEach((socket) => {
583
+ if (socket.destroyed === false) {
584
+ socket.destroy();
585
+ }
586
+ });
587
+ state.sockets = [];
588
+ state.server.close(() => {
589
+ logger.info("Server closed");
590
+ start();
591
+ });
592
+ };
593
+ if (!noWatch && !process.env.CI) {
594
+ import_chokidar.default.watch([gqlPackageFile]).on("ready", async () => {
595
+ isReady = true;
596
+ start();
597
+ }).on("all", async () => {
598
+ if (isReady) {
599
+ restart();
600
+ }
601
+ });
602
+ } else {
603
+ if (process.env.CI) {
604
+ logger.info("Detected CI environment, omitting watch commands...");
605
+ }
606
+ start();
607
+ startSubprocess();
608
+ }
609
+ }
610
+
611
+ // pnp:/Users/jeffsee/code/tinacms/packages/@tinacms/cli/src/cmds/init/index.ts
612
+ var import_fs_extra3 = __toModule(require("fs-extra"));
613
+ var import_path4 = __toModule(require("path"));
614
+ var import_progress = __toModule(require("progress"));
615
+ var import_prompts = __toModule(require("prompts"));
616
+
617
+ // pnp:/Users/jeffsee/code/tinacms/packages/@tinacms/cli/src/cmds/init/setup-files/index.ts
618
+ var adminPage = `import { TinaAdmin } from 'tinacms';
619
+ export default TinaAdmin;
620
+ `;
621
+ var blogPost = `---
622
+ title: Vote For Pedro
623
+ ---
624
+ # Welcome to the blog.
625
+
626
+ > To edit this site head over to the [\` /
627
+ admin\`](/admin) route. Then click the pencil icon in the bottom lefthand corner to start editing \u{1F999}.
628
+
629
+
630
+ # Dixi gaude Arethusa
631
+
632
+ ## Oscula mihi
633
+
634
+ Lorem markdownum numerabilis armentorum platanus, cultros coniunx sibi per
635
+ silvas, nostris clausit sequemur diverso scopulosque. Fecit tum alta sed non
636
+ falcato murmura, geminas donata Amyntore, quoque Nox. Invitam inquit, modo
637
+ nocte; ut ignis faciemque manes in imagine sinistra ut mucrone non ramos
638
+ sepulcro supplex. Crescentesque populos motura, fit cumque. Verumque est; retro
639
+ sibi tristia bracchia Aetola telae caruerunt et.
640
+
641
+
642
+ ## Mutato fefellimus sit demisit aut alterius sollicito
643
+
644
+ Phaethonteos vestes quem involvite iuvenca; furiali anne: sati totumque,
645
+ **corpora** cum rapacibus nunc! Nervis repetatne, miserabile doleas, deprensum
646
+ hunc, fluctus Threicio, ad urbes, magicaeque, quid. Per credensque series adicis
647
+ poteram [quidem](#)! Iam uni mensas victrix
648
+ vittas ut flumina Satyri adulter; bellum iacet domitae repercusso truncis urnis
649
+ mille rigidi sub taurum.
650
+
651
+
652
+ `;
653
+ var nextPostPage = () => `// THIS FILE HAS BEEN GENERATED WITH THE TINA CLI.
654
+ // This is a demo file once you have tina setup feel free to delete this file
655
+
656
+ import { staticRequest, gql, getStaticPropsForTina } from "tinacms";
657
+ import Head from "next/head";
658
+ import { createGlobalStyle } from "styled-components";
659
+
660
+ // Styles for markdown
661
+ const GlobalStyle = createGlobalStyle\`
662
+ h1,h2,h3,h4,h5 {
663
+ margin-bottom: 1.5rem;
664
+ margin-top: 1.5rem;
665
+ }
666
+ blockquote {
667
+ background-color: rgb(209,250,229);
668
+ }
669
+ h1 {
670
+ font-size: 45px;
671
+ }
672
+ h2 {
673
+ font-size: 35px;
674
+ }
675
+ h3 {
676
+ font-size: 25px;
677
+ }
678
+ h4 {
679
+ font-size: 22px;
680
+ }
681
+ ul {
682
+ padding-left: 0;
683
+ }
684
+ li {
685
+ list-style-type: none;
686
+ }
687
+ a {
688
+ font-weight: bold;
689
+ color: rgb(59,130,246);
690
+ text-decoration: underline;
691
+ }
692
+ \`;
693
+ const defaultMarked = (markdown) => markdown;
694
+ // Use the props returned by get static props (this can be deleted when the edit provider and tina-wrapper are moved to _app.js)
695
+ const BlogPage = (props) => {
696
+ return (
697
+ <>
698
+ <Head>
699
+ {/* Tailwind CDN */}
700
+ <link
701
+ rel="stylesheet"
702
+ href="https://cdnjs.cloudflare.com/ajax/libs/tailwindcss/2.2.7/tailwind.min.css"
703
+ integrity="sha512-y6ZMKFUQrn+UUEVoqYe8ApScqbjuhjqzTuwUMEGMDuhS2niI8KA3vhH2LenreqJXQS+iIXVTRL2iaNfJbDNA1Q=="
704
+ crossOrigin="anonymous"
705
+ referrerPolicy="no-referrer"
706
+ />
707
+ {/* Marked CDN */}
708
+ <script
709
+ type="text/javascript"
710
+ crossOrigin="anonymous"
711
+ src="https://cdnjs.cloudflare.com/ajax/libs/marked/4.0.0/marked.min.js"
712
+ />
713
+ </Head>
714
+ <div>
715
+ <div
716
+ style={{
717
+ textAlign: "center",
718
+ }}
719
+ >
720
+ <h1 className="text-3xl m-8 text-center leading-8 font-extrabold tracking-tight text-gray-900 sm:text-4xl">
721
+ {props.data.getPostsDocument.data.title}
722
+ </h1>
723
+ {/* Convert markdown to html in the browser only */}
724
+ {typeof window !== "undefined" && (
725
+ <ContentSection
726
+ content={window.marked.parse(props.data.getPostsDocument.data.body)}
727
+ ></ContentSection>
728
+ )}
729
+ </div>
730
+ <div className="bg-green-100 text-center">
731
+ Lost and looking for a place to start?
732
+ <a
733
+ href="https://tina.io/guides/tina-cloud/getting-started/overview/"
734
+ className="text-blue-500 underline"
735
+ >
736
+ {" "}
737
+ Check out this guide
738
+ </a>{" "}
739
+ to see how add TinaCMS to an existing Next.js site.
740
+ </div>
741
+ </div>
742
+ </>
743
+ );
744
+ };
745
+
746
+ export const getStaticProps = async ({ params }) => {
747
+ const tinaProps = await getStaticPropsForTina({
748
+ query: gql\`
749
+ query BlogPostQuery($relativePath: String!) {
750
+ getPostsDocument(relativePath: $relativePath) {
751
+ data {
752
+ title
753
+ body
754
+ }
755
+ }
756
+ }
757
+ \`,
758
+ variables: { relativePath: \`\${params.filename}.md\` },
759
+ });
760
+ return {
761
+ props: {
762
+ ...tinaProps,
763
+ },
764
+ };
765
+ };
766
+
767
+ export const getStaticPaths = async () => {
768
+ const postsListData = (await staticRequest({
769
+ query: gql\`
770
+ query GetPostsList {
771
+ getPostsList {
772
+ edges {
773
+ node {
774
+ sys {
775
+ filename
776
+ }
777
+ }
778
+ }
779
+ }
780
+ }
781
+ \`,
782
+ }));
783
+
784
+ return {
785
+ paths: postsListData.getPostsList.edges.map((post) => ({
786
+ params: { filename: post.node.sys.filename },
787
+ })),
788
+ fallback: false,
789
+ };
790
+ };
791
+
792
+ export default BlogPage;
793
+
794
+ const ContentSection = ({ content }) => {
795
+ return (
796
+ <div className="relative py-16 bg-white overflow-hidden">
797
+ <div className="hidden lg:block lg:absolute lg:inset-y-0 lg:h-full lg:w-full">
798
+ <div
799
+ className="relative h-full text-lg max-w-prose mx-auto"
800
+ aria-hidden="true"
801
+ >
802
+ <svg
803
+ className="absolute top-12 left-full transform translate-x-32"
804
+ width={404}
805
+ height={384}
806
+ fill="none"
807
+ viewBox="0 0 404 384"
808
+ >
809
+ <defs>
810
+ <pattern
811
+ id="74b3fd99-0a6f-4271-bef2-e80eeafdf357"
812
+ x={0}
813
+ y={0}
814
+ width={20}
815
+ height={20}
816
+ patternUnits="userSpaceOnUse"
817
+ >
818
+ <rect
819
+ x={0}
820
+ y={0}
821
+ width={4}
822
+ height={4}
823
+ className="text-gray-200"
824
+ fill="currentColor"
825
+ />
826
+ </pattern>
827
+ </defs>
828
+ <rect
829
+ width={404}
830
+ height={384}
831
+ fill="url(#74b3fd99-0a6f-4271-bef2-e80eeafdf357)"
832
+ />
833
+ </svg>
834
+ <svg
835
+ className="absolute top-1/2 right-full transform -translate-y-1/2 -translate-x-32"
836
+ width={404}
837
+ height={384}
838
+ fill="none"
839
+ viewBox="0 0 404 384"
840
+ >
841
+ <defs>
842
+ <pattern
843
+ id="f210dbf6-a58d-4871-961e-36d5016a0f49"
844
+ x={0}
845
+ y={0}
846
+ width={20}
847
+ height={20}
848
+ patternUnits="userSpaceOnUse"
849
+ >
850
+ <rect
851
+ x={0}
852
+ y={0}
853
+ width={4}
854
+ height={4}
855
+ className="text-gray-200"
856
+ fill="currentColor"
857
+ />
858
+ </pattern>
859
+ </defs>
860
+ <rect
861
+ width={404}
862
+ height={384}
863
+ fill="url(#f210dbf6-a58d-4871-961e-36d5016a0f49)"
864
+ />
865
+ </svg>
866
+ <svg
867
+ className="absolute bottom-12 left-full transform translate-x-32"
868
+ width={404}
869
+ height={384}
870
+ fill="none"
871
+ viewBox="0 0 404 384"
872
+ >
873
+ <defs>
874
+ <pattern
875
+ id="d3eb07ae-5182-43e6-857d-35c643af9034"
876
+ x={0}
877
+ y={0}
878
+ width={20}
879
+ height={20}
880
+ patternUnits="userSpaceOnUse"
881
+ >
882
+ <rect
883
+ x={0}
884
+ y={0}
885
+ width={4}
886
+ height={4}
887
+ className="text-gray-200"
888
+ fill="currentColor"
889
+ />
890
+ </pattern>
891
+ </defs>
892
+ <rect
893
+ width={404}
894
+ height={384}
895
+ fill="url(#d3eb07ae-5182-43e6-857d-35c643af9034)"
896
+ />
897
+ </svg>
898
+ </div>
899
+ </div>
900
+ <div className="relative px-4 sm:px-6 lg:px-8">
901
+ <div className="text-lg max-w-prose mx-auto">
902
+ <div dangerouslySetInnerHTML={{ __html: content }}></div>
903
+ <GlobalStyle />
904
+ </div>
905
+ </div>
906
+ </div>
907
+ );
908
+ };
909
+
910
+ `;
911
+ var AppJsContent = (extraImports) => `import dynamic from 'next/dynamic'
912
+ import { TinaEditProvider } from 'tinacms/dist/edit-state'
913
+ const TinaCMS = dynamic(() => import('tinacms'), { ssr: false })
914
+ ${extraImports || ""}
915
+
916
+ const App = ({ Component, pageProps }) => {
917
+ return (
918
+ <>
919
+ <TinaEditProvider
920
+ editMode={
921
+ <TinaCMS
922
+ clientId={process.env.NEXT_PUBLIC_TINA_CLIENT_ID}
923
+ branch={process.env.NEXT_PUBLIC_EDIT_BRANCH}
924
+ isLocalClient={Boolean(
925
+ Number(process.env.NEXT_PUBLIC_USE_LOCAL_CLIENT ?? true)
926
+ )}
927
+ {...pageProps}
928
+ >
929
+ {(livePageProps) => <Component {...livePageProps} />}
930
+ </TinaCMS>
931
+ }
932
+ >
933
+ <Component {...pageProps} />
934
+ </TinaEditProvider>
935
+ </>
936
+ )
937
+ }
938
+
939
+ export default App
940
+ `;
941
+
942
+ // pnp:/Users/jeffsee/code/tinacms/packages/@tinacms/cli/src/cmds/init/index.ts
943
+ var import_chalk2 = __toModule(require("chalk"));
944
+ function execShellCommand(cmd) {
945
+ const exec = require("child_process").exec;
946
+ return new Promise((resolve, reject) => {
947
+ exec(cmd, (error, stdout, stderr) => {
948
+ if (error) {
949
+ console.warn(error);
950
+ }
951
+ resolve(stdout ? stdout : stderr);
952
+ });
953
+ });
954
+ }
955
+ async function initTina(ctx, next, options) {
956
+ logger.info(successText("Setting up Tina..."));
957
+ next();
958
+ }
959
+ async function installDeps(ctx, next, options) {
960
+ const bar = new import_progress.default("Installing Tina packages. This might take a moment... :prog", 2);
961
+ const deps = ["tinacms", "styled-components", "@tinacms/cli"];
962
+ bar.tick({
963
+ prog: ""
964
+ });
965
+ const installCMD = `yarn add ${deps.join(" ")}`;
966
+ await execShellCommand(installCMD);
967
+ bar.tick({
968
+ prog: "\u2705"
969
+ });
970
+ logger.level = "fatal";
971
+ next();
972
+ }
973
+ var baseDir = process.cwd();
974
+ var TinaWrapperPathDir = import_path4.default.join(baseDir, "components");
975
+ var TinaWrapperPath = import_path4.default.join(TinaWrapperPathDir, "tina-wrapper.tsx");
976
+ var blogContentPath = import_path4.default.join(baseDir, "content", "posts");
977
+ var blogPostPath = import_path4.default.join(blogContentPath, "HelloWorld.md");
978
+ async function tinaSetup(ctx, next, options) {
979
+ const useingSrc = import_fs_extra3.default.pathExistsSync(import_path4.default.join(baseDir, "src"));
980
+ if (!import_fs_extra3.default.pathExistsSync(blogPostPath)) {
981
+ logger.info(logText("Adding a content folder..."));
982
+ import_fs_extra3.default.mkdirpSync(blogContentPath);
983
+ import_fs_extra3.default.writeFileSync(blogPostPath, blogPost);
984
+ }
985
+ logger.level = "info";
986
+ const pagesPath = import_path4.default.join(baseDir, useingSrc ? "src" : "", "pages");
987
+ const appPath = import_path4.default.join(pagesPath, "_app.js");
988
+ const appPathTS = import_path4.default.join(pagesPath, "_app.tsx");
989
+ const appExtension = import_fs_extra3.default.existsSync(appPath) ? ".js" : ".tsx";
990
+ let wrapper = false;
991
+ if (!import_fs_extra3.default.pathExistsSync(appPath) && !import_fs_extra3.default.pathExistsSync(appPathTS)) {
992
+ logger.info(logText("Adding _app.js ... \u2705"));
993
+ import_fs_extra3.default.writeFileSync(appPath, AppJsContent());
994
+ } else {
995
+ const override = await (0, import_prompts.default)({
996
+ name: "res",
997
+ type: "confirm",
998
+ message: `do you want us to ${import_chalk2.default.bold(`override`)} your _app${appExtension}?`
999
+ });
1000
+ if (override.res) {
1001
+ logger.info(logText(`Adding _app${appExtension} ... \u2705`));
1002
+ const appPathWithExtension = import_path4.default.join(pagesPath, `_app${appExtension}`);
1003
+ const fileContent = import_fs_extra3.default.pathExistsSync(appPath) ? (0, import_fs_extra3.readFileSync)(appPath) : (0, import_fs_extra3.readFileSync)(appPathTS);
1004
+ const matches = [
1005
+ ...fileContent.toString().matchAll(/^.*import.*\.css("|').*$/gm)
1006
+ ];
1007
+ const primaryMatches = matches.map((x) => x[0]);
1008
+ import_fs_extra3.default.writeFileSync(appPathWithExtension, AppJsContent(primaryMatches.join("\n")));
1009
+ } else {
1010
+ wrapper = true;
1011
+ logger.info(dangerText(`Heads up, to enable live-editing you'll need to wrap your page or site in Tina:
1012
+ `, warnText(AppJsContent())));
1013
+ }
1014
+ }
1015
+ const tinaBlogPagePath = import_path4.default.join(pagesPath, "demo", "blog");
1016
+ const tinaBlogPagePathFile = import_path4.default.join(tinaBlogPagePath, "[filename].js");
1017
+ if (!import_fs_extra3.default.pathExistsSync(tinaBlogPagePathFile)) {
1018
+ import_fs_extra3.default.mkdirpSync(tinaBlogPagePath);
1019
+ import_fs_extra3.default.writeFileSync(tinaBlogPagePathFile, nextPostPage());
1020
+ }
1021
+ logger.info("Adding a content folder... \u2705");
1022
+ const packagePath = import_path4.default.join(baseDir, "package.json");
1023
+ const pack = JSON.parse((0, import_fs_extra3.readFileSync)(packagePath).toString());
1024
+ const oldScripts = pack.scripts || {};
1025
+ const newPack = JSON.stringify({
1026
+ ...pack,
1027
+ scripts: {
1028
+ ...oldScripts,
1029
+ "tina-dev": 'yarn tinacms server:start -c "next dev"',
1030
+ "tina-build": 'yarn tinacms server:start -c "next build"',
1031
+ "tina-start": 'yarn tinacms server:start -c "next start"'
1032
+ }
1033
+ }, null, 2);
1034
+ (0, import_fs_extra3.writeFileSync)(packagePath, newPack);
1035
+ const adminPath = import_path4.default.join(pagesPath, "admin", "[[...tina]].js");
1036
+ if (import_fs_extra3.default.pathExistsSync(import_path4.default.join(pagesPath, "admin"))) {
1037
+ logger.warn(`Unable to add /pages/admin/[[...tina]].js, this path already exists.
1038
+ Learn more about toggling edit-mode at https://tina.io/docs/tinacms-context/#manually-toggling-edit-mode`);
1039
+ return next();
1040
+ }
1041
+ (0, import_fs_extra3.outputFileSync)(adminPath, adminPage);
1042
+ next();
1043
+ }
1044
+ async function successMessage(ctx, next, options) {
1045
+ const baseDir2 = process.cwd();
1046
+ logger.info(`Tina setup ${import_chalk2.default.underline.green("done")} \u2705
1047
+ Start your dev server with ${successText(`yarn tina-dev`)} and go to http://localhost:3000/demo/blog/HelloWorld to ${successText("check it out the page that was created for you")}
1048
+ Enjoy Tina \u{1F999} !
1049
+ `);
1050
+ next();
1051
+ }
1052
+
1053
+ // pnp:/Users/jeffsee/code/tinacms/packages/@tinacms/cli/src/cmds/baseCmds.ts
1054
+ var CMD_GEN_TYPES = "schema:types";
1055
+ var CMD_START_SERVER = "server:start";
1056
+ var CMD_COMPILE_MODELS = "schema:compile";
1057
+ var INIT = "init";
1058
+ var startServerPortOption = {
1059
+ name: "--port <port>",
1060
+ description: "Specify a port to run the server on. (default 4001)"
1061
+ };
1062
+ var experimentalDatalayer = {
1063
+ name: "--experimentalData",
1064
+ description: "Build the server with additional data querying capabilities"
1065
+ };
1066
+ var subCommand = {
1067
+ name: "-c, --command <command>",
1068
+ description: "The sub-command to run"
1069
+ };
1070
+ var noWatchOption = {
1071
+ name: "--noWatch",
1072
+ description: "Don't regenerate config on file changes"
1073
+ };
1074
+ var noSDKCodegenOption = {
1075
+ name: "--noSDK",
1076
+ description: "Don't generate the generated client SDK"
1077
+ };
1078
+ var baseCmds = [
1079
+ {
1080
+ command: CMD_START_SERVER,
1081
+ description: "Start Filesystem Graphql Server",
1082
+ options: [
1083
+ startServerPortOption,
1084
+ subCommand,
1085
+ experimentalDatalayer,
1086
+ noWatchOption,
1087
+ noSDKCodegenOption
1088
+ ],
1089
+ action: (options) => chain([startServer], options)
1090
+ },
1091
+ {
1092
+ command: CMD_COMPILE_MODELS,
1093
+ description: "Compile schema into static files for the server",
1094
+ options: [experimentalDatalayer],
1095
+ action: (options) => chain([compile], options)
1096
+ },
1097
+ {
1098
+ command: CMD_GEN_TYPES,
1099
+ description: "Generate a GraphQL query for your site's schema, (and optionally Typescript types)",
1100
+ options: [experimentalDatalayer, noSDKCodegenOption],
1101
+ action: (options) => chain([attachSchema, genTypes], options)
1102
+ },
1103
+ {
1104
+ command: INIT,
1105
+ options: [experimentalDatalayer],
1106
+ description: "Add Tina Cloud to an existing project",
1107
+ action: (options) => chain([
1108
+ initTina,
1109
+ installDeps,
1110
+ async (_ctx, next) => {
1111
+ await compile(_ctx, next);
1112
+ next();
1113
+ },
1114
+ attachSchema,
1115
+ genTypes,
1116
+ tinaSetup,
1117
+ successMessage
1118
+ ], options)
1119
+ }
1120
+ ];
1121
+
1122
+ // pnp:/Users/jeffsee/code/tinacms/packages/@tinacms/cli/src/index.ts
1123
+ var program = new commander.Command(name);
1124
+ var registerCommands = (commands, noHelp = false) => {
1125
+ commands.forEach((command, i) => {
1126
+ let newCmd = program.command(command.command, { noHelp }).description(command.description).action((...args) => {
1127
+ logger.info("");
1128
+ command.action(...args);
1129
+ });
1130
+ if (command.alias) {
1131
+ newCmd = newCmd.alias(command.alias);
1132
+ }
1133
+ newCmd.on("--help", function() {
1134
+ if (command.examples) {
1135
+ logger.info(`
1136
+ Examples:
1137
+ ${command.examples}`);
1138
+ }
1139
+ if (command.subCommands) {
1140
+ logger.info("\nCommands:");
1141
+ const optionTag = " [options]";
1142
+ command.subCommands.forEach((subcommand, i2) => {
1143
+ const commandStr = `${subcommand.command}${(subcommand.options || []).length ? optionTag : ""}`;
1144
+ const padLength = Math.max(...command.subCommands.map((sub) => sub.command.length)) + optionTag.length;
1145
+ logger.info(`${commandStr.padEnd(padLength)} ${subcommand.description}`);
1146
+ });
1147
+ }
1148
+ logger.info("");
1149
+ });
1150
+ (command.options || []).forEach((option) => {
1151
+ newCmd.option(option.name, option.description);
1152
+ });
1153
+ if (command.subCommands) {
1154
+ registerCommands(command.subCommands, true);
1155
+ }
1156
+ });
1157
+ };
1158
+ async function init(args) {
1159
+ program.version(version);
1160
+ const commands = [...baseCmds];
1161
+ registerCommands(commands);
1162
+ program.usage("command [options]");
1163
+ program.on("command:*", function() {
1164
+ logger.error("Invalid command: %s\nSee --help for a list of available commands.", args.join(" "));
1165
+ process.exit(1);
1166
+ });
1167
+ program.on("--help", function() {
1168
+ logger.info(logText(`
1169
+ You can get help on any command with "-h" or "--help".
1170
+ e.g: "tinacms server:start --help"
1171
+ `));
1172
+ });
1173
+ if (!process.argv.slice(2).length) {
1174
+ program.help();
1175
+ }
1176
+ program.parse(args);
1177
+ }
1178
+ // Annotate the CommonJS export names for ESM import in node:
1179
+ 0 && (module.exports = {
1180
+ defineSchema,
1181
+ init
1182
+ });