create-theokit 0.1.0-alpha.2 → 0.1.0-alpha.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.
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for describing the origin of the Work and
141
+ reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 usetheo.dev
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/dist/cli.js CHANGED
@@ -4,9 +4,49 @@
4
4
  import { resolve as resolve2 } from "path";
5
5
 
6
6
  // src/index.ts
7
- import { existsSync, cpSync, readFileSync, writeFileSync, renameSync, unlinkSync, readdirSync } from "fs";
8
- import { resolve, join, dirname } from "path";
7
+ import {
8
+ existsSync as existsSync2,
9
+ cpSync,
10
+ readFileSync as readFileSync2,
11
+ writeFileSync as writeFileSync2,
12
+ renameSync,
13
+ unlinkSync as unlinkSync2,
14
+ readdirSync,
15
+ rmSync
16
+ } from "fs";
17
+ import { resolve, join as join2, dirname } from "path";
9
18
  import { fileURLToPath } from "url";
19
+
20
+ // src/bare-transform.ts
21
+ import { existsSync, readFileSync, writeFileSync, unlinkSync } from "fs";
22
+ import { join } from "path";
23
+ var HELLO_PAGE = `export default function Page() {
24
+ return <h1>Hello Theo</h1>
25
+ }
26
+ `;
27
+ function applyBareTransform(targetDir, options = {}) {
28
+ if (options._testForceError) {
29
+ throw new Error(`Forced transform failure: ${options._testForceError}`);
30
+ }
31
+ const pkgPath = join(targetDir, "package.json");
32
+ if (existsSync(pkgPath)) {
33
+ const pkg = JSON.parse(readFileSync(pkgPath, "utf-8"));
34
+ if (pkg.dependencies && "@usetheo/ui" in pkg.dependencies) {
35
+ delete pkg.dependencies["@usetheo/ui"];
36
+ }
37
+ writeFileSync(pkgPath, JSON.stringify(pkg, null, 2) + "\n");
38
+ }
39
+ const pagePath = join(targetDir, "app/page.tsx");
40
+ if (existsSync(pagePath)) {
41
+ writeFileSync(pagePath, HELLO_PAGE);
42
+ }
43
+ const chatPath = join(targetDir, "server/routes/chat.ts");
44
+ if (existsSync(chatPath)) {
45
+ unlinkSync(chatPath);
46
+ }
47
+ }
48
+
49
+ // src/index.ts
10
50
  var __dirname = dirname(fileURLToPath(import.meta.url));
11
51
  function getTemplateDir(templateName = "default") {
12
52
  return resolve(__dirname, "../templates", templateName);
@@ -14,9 +54,14 @@ function getTemplateDir(templateName = "default") {
14
54
  function isValidProjectName(name) {
15
55
  return /^[a-z0-9][a-z0-9._-]*$/.test(name);
16
56
  }
17
- function scaffold(targetDir, projectName, templateName = "default") {
57
+ function scaffold(targetDir, projectName, templateName = "default", options = {}) {
58
+ if (options.bare && templateName !== "default") {
59
+ throw new Error(
60
+ `--bare flag only applies to the default template; got "${templateName}". Use \`npx create-theokit <name> --template=default --bare\` or pick a different template.`
61
+ );
62
+ }
18
63
  const templateDir = getTemplateDir(templateName);
19
- if (!existsSync(templateDir)) {
64
+ if (!existsSync2(templateDir)) {
20
65
  throw new Error(
21
66
  `Template "${templateName}" not found. Available templates: default, dashboard, api-only, postgres`
22
67
  );
@@ -26,7 +71,7 @@ function scaffold(targetDir, projectName, templateName = "default") {
26
71
  `Invalid project name "${projectName}". Use lowercase letters, numbers, hyphens, and dots. Must start with a letter or number.`
27
72
  );
28
73
  }
29
- if (existsSync(targetDir)) {
74
+ if (existsSync2(targetDir)) {
30
75
  const contents = readdirSync(targetDir);
31
76
  if (contents.length > 0) {
32
77
  throw new Error(
@@ -35,17 +80,31 @@ function scaffold(targetDir, projectName, templateName = "default") {
35
80
  }
36
81
  }
37
82
  cpSync(templateDir, targetDir, { recursive: true });
38
- const gitignoreSrc = join(targetDir, "_gitignore");
39
- const gitignoreDest = join(targetDir, ".gitignore");
40
- if (existsSync(gitignoreSrc)) {
83
+ const gitignoreSrc = join2(targetDir, "_gitignore");
84
+ const gitignoreDest = join2(targetDir, ".gitignore");
85
+ if (existsSync2(gitignoreSrc)) {
41
86
  renameSync(gitignoreSrc, gitignoreDest);
42
87
  }
43
- const tmplPath = join(targetDir, "package.json.tmpl");
44
- if (existsSync(tmplPath)) {
45
- const content = readFileSync(tmplPath, "utf-8");
88
+ const tmplPath = join2(targetDir, "package.json.tmpl");
89
+ if (existsSync2(tmplPath)) {
90
+ const content = readFileSync2(tmplPath, "utf-8");
46
91
  const replaced = content.replace(/\{\{name\}\}/g, projectName);
47
- writeFileSync(join(targetDir, "package.json"), replaced);
48
- unlinkSync(tmplPath);
92
+ writeFileSync2(join2(targetDir, "package.json"), replaced);
93
+ unlinkSync2(tmplPath);
94
+ }
95
+ if (options.bare) {
96
+ try {
97
+ applyBareTransform(targetDir, {
98
+ _testForceError: options._testForceTransformError
99
+ });
100
+ } catch (err) {
101
+ rmSync(targetDir, { recursive: true, force: true });
102
+ const original = err instanceof Error ? err.message : String(err);
103
+ throw new Error(
104
+ `Scaffold rolled back: bare transform failed. Check filesystem perms.
105
+ Original error: ${original}`
106
+ );
107
+ }
49
108
  }
50
109
  }
51
110
 
@@ -77,21 +136,24 @@ function main() {
77
136
  const positionalArgs = args.filter((a) => !a.startsWith("--"));
78
137
  const projectName = positionalArgs[0];
79
138
  if (!projectName) {
80
- console.error("Usage: create-theokit <project-name> [--template=name]");
139
+ console.error("Usage: create-theokit <project-name> [--template=name] [--bare]");
81
140
  console.error("");
82
141
  console.error("Example:");
83
142
  console.error(" npx create-theokit my-app");
84
143
  console.error(" npx create-theokit my-app --template=dashboard");
144
+ console.error(" npx create-theokit my-app --bare (skip @usetheo/ui defaults)");
85
145
  process.exit(1);
86
146
  }
87
147
  const templateFlag = args.find((a) => a.startsWith("--template="));
88
148
  const templateName = templateFlag ? templateFlag.split("=")[1] : "default";
149
+ const bare = args.includes("--bare");
89
150
  const targetDir = resolve2(process.cwd(), projectName);
90
151
  try {
152
+ const suffix = bare ? " [--bare: skipping TheoUI defaults]" : "";
91
153
  console.log(`
92
- Creating TheoKit project "${projectName}" (template: ${templateName})...
154
+ Creating TheoKit project "${projectName}" (template: ${templateName})${suffix}...
93
155
  `);
94
- scaffold(targetDir, projectName, templateName);
156
+ scaffold(targetDir, projectName, templateName, { bare });
95
157
  const pkgManager = detectPkgManager();
96
158
  console.log(`Installing dependencies with ${pkgManager}...
97
159
  `);
package/dist/cli.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/cli.ts","../src/index.ts","../src/pkg-manager.ts","../src/install.ts"],"sourcesContent":["import { resolve } from 'node:path'\nimport { scaffold } from './index.js'\nimport { detectPkgManager } from './pkg-manager.js'\nimport { runInstall } from './install.js'\n\nexport function main(): void {\n const args = process.argv.slice(2)\n const positionalArgs = args.filter((a) => !a.startsWith('--'))\n const projectName = positionalArgs[0]\n\n if (!projectName) {\n console.error('Usage: create-theokit <project-name> [--template=name]')\n console.error('')\n console.error('Example:')\n console.error(' npx create-theokit my-app')\n console.error(' npx create-theokit my-app --template=dashboard')\n process.exit(1)\n }\n\n // Parse --template flag\n const templateFlag = args.find((a) => a.startsWith('--template='))\n const templateName = templateFlag ? templateFlag.split('=')[1] : 'default'\n\n const targetDir = resolve(process.cwd(), projectName)\n\n try {\n console.log(`\\nCreating TheoKit project \"${projectName}\" (template: ${templateName})...\\n`)\n\n scaffold(targetDir, projectName, templateName)\n\n const pkgManager = detectPkgManager()\n console.log(`Installing dependencies with ${pkgManager}...\\n`)\n runInstall(targetDir, pkgManager)\n\n console.log(`\\n ✓ Project created at ${targetDir}\\n`)\n console.log(` Next steps:\\n`)\n console.log(` cd ${projectName}`)\n console.log(` ${pkgManager === 'npm' ? 'npx' : pkgManager} theokit dev\\n`)\n } catch (err) {\n console.error(`\\n ✗ ${(err as Error).message}\\n`)\n process.exit(1)\n }\n}\n\n// Auto-execute when run as script\nmain()\n","import { existsSync, cpSync, readFileSync, writeFileSync, renameSync, unlinkSync, readdirSync } from 'node:fs'\nimport { resolve, join, dirname } from 'node:path'\nimport { fileURLToPath } from 'node:url'\n\nconst __dirname = dirname(fileURLToPath(import.meta.url))\n\nfunction getTemplateDir(templateName = 'default'): string {\n return resolve(__dirname, '../templates', templateName)\n}\n\nfunction isValidProjectName(name: string): boolean {\n return /^[a-z0-9][a-z0-9._-]*$/.test(name)\n}\n\nexport function scaffold(targetDir: string, projectName: string, templateName = 'default'): void {\n const templateDir = getTemplateDir(templateName)\n\n if (!existsSync(templateDir)) {\n throw new Error(\n `Template \"${templateName}\" not found. Available templates: default, dashboard, api-only, postgres`,\n )\n }\n\n if (!isValidProjectName(projectName)) {\n throw new Error(\n `Invalid project name \"${projectName}\". ` +\n `Use lowercase letters, numbers, hyphens, and dots. Must start with a letter or number.`,\n )\n }\n\n if (existsSync(targetDir)) {\n const contents = readdirSync(targetDir)\n if (contents.length > 0) {\n throw new Error(\n `Directory \"${targetDir}\" is not empty. Please use an empty directory.`,\n )\n }\n }\n\n // Copy template\n cpSync(templateDir, targetDir, { recursive: true })\n\n // Rename _gitignore → .gitignore\n const gitignoreSrc = join(targetDir, '_gitignore')\n const gitignoreDest = join(targetDir, '.gitignore')\n if (existsSync(gitignoreSrc)) {\n renameSync(gitignoreSrc, gitignoreDest)\n }\n\n // Process package.json.tmpl → package.json\n const tmplPath = join(targetDir, 'package.json.tmpl')\n if (existsSync(tmplPath)) {\n const content = readFileSync(tmplPath, 'utf-8')\n const replaced = content.replace(/\\{\\{name\\}\\}/g, projectName)\n writeFileSync(join(targetDir, 'package.json'), replaced)\n unlinkSync(tmplPath)\n }\n}\n","export type PkgManager = 'npm' | 'pnpm' | 'yarn' | 'bun'\n\nexport function detectPkgManager(): PkgManager {\n const ua = process.env.npm_config_user_agent ?? ''\n if (ua.startsWith('yarn')) return 'yarn'\n if (ua.startsWith('pnpm')) return 'pnpm'\n if (ua.startsWith('bun')) return 'bun'\n return 'npm'\n}\n","import spawn from 'cross-spawn'\nimport type { PkgManager } from './pkg-manager.js'\n\nexport function runInstall(cwd: string, pkgManager: PkgManager): void {\n const result = spawn.sync(pkgManager, ['install'], {\n cwd,\n stdio: 'inherit',\n env: { ...process.env, NODE_ENV: 'development' },\n })\n\n if (result.status !== 0) {\n throw new Error(`Failed to install dependencies with ${pkgManager}`)\n }\n}\n"],"mappings":";;;AAA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UAAU;AAEhC,YAAQ,IAAI;AAAA,8BAA4B,SAAS;AAAA,CAAI;AACrD,YAAQ,IAAI;AAAA,CAAiB;AAC7B,YAAQ,IAAI,UAAU,WAAW,EAAE;AACnC,YAAQ,IAAI,OAAO,eAAe,QAAQ,QAAQ,UAAU;AAAA,CAAgB;AAAA,EAC9E,SAAS,KAAK;AACZ,YAAQ,MAAM;AAAA,WAAU,IAAc,OAAO;AAAA,CAAI;AACjD,YAAQ,KAAK,CAAC;AAAA,EAChB;AACF;AAGA,KAAK;","names":["resolve","resolve"]}
1
+ {"version":3,"sources":["../src/cli.ts","../src/index.ts","../src/bare-transform.ts","../src/pkg-manager.ts","../src/install.ts"],"sourcesContent":["import { resolve } from 'node:path'\nimport { scaffold } from './index.js'\nimport { detectPkgManager } from './pkg-manager.js'\nimport { runInstall } from './install.js'\n\nexport function main(): void {\n const args = process.argv.slice(2)\n const positionalArgs = args.filter((a) => !a.startsWith('--'))\n const projectName = positionalArgs[0]\n\n if (!projectName) {\n console.error('Usage: create-theokit <project-name> [--template=name] [--bare]')\n console.error('')\n console.error('Example:')\n console.error(' npx create-theokit my-app')\n console.error(' npx create-theokit my-app --template=dashboard')\n console.error(' npx create-theokit my-app --bare (skip @usetheo/ui defaults)')\n process.exit(1)\n }\n\n // Parse --template flag\n const templateFlag = args.find((a) => a.startsWith('--template='))\n const templateName = templateFlag ? templateFlag.split('=')[1] : 'default'\n\n // Parse --bare flag (only applies to default template)\n const bare = args.includes('--bare')\n\n const targetDir = resolve(process.cwd(), projectName)\n\n try {\n const suffix = bare ? ' [--bare: skipping TheoUI defaults]' : ''\n console.log(`\\nCreating TheoKit project \"${projectName}\" (template: ${templateName})${suffix}...\\n`)\n\n scaffold(targetDir, projectName, templateName, { bare })\n\n const pkgManager = detectPkgManager()\n console.log(`Installing dependencies with ${pkgManager}...\\n`)\n runInstall(targetDir, pkgManager)\n\n console.log(`\\n ✓ Project created at ${targetDir}\\n`)\n console.log(` Next steps:\\n`)\n console.log(` cd ${projectName}`)\n console.log(` ${pkgManager === 'npm' ? 'npx' : pkgManager} theokit dev\\n`)\n } catch (err) {\n console.error(`\\n ✗ ${(err as Error).message}\\n`)\n process.exit(1)\n }\n}\n\n// Auto-execute when run as script\nmain()\n","import {\n existsSync,\n cpSync,\n readFileSync,\n writeFileSync,\n renameSync,\n unlinkSync,\n readdirSync,\n rmSync,\n} from 'node:fs'\nimport { resolve, join, dirname } from 'node:path'\nimport { fileURLToPath } from 'node:url'\nimport { applyBareTransform } from './bare-transform.js'\n\nconst __dirname = dirname(fileURLToPath(import.meta.url))\n\nfunction getTemplateDir(templateName = 'default'): string {\n return resolve(__dirname, '../templates', templateName)\n}\n\nfunction isValidProjectName(name: string): boolean {\n return /^[a-z0-9][a-z0-9._-]*$/.test(name)\n}\n\nexport interface ScaffoldOptions {\n bare?: boolean\n /** Test-only — force the bare transform to throw to validate EC-4 rollback. */\n _testForceTransformError?: string\n}\n\nexport function scaffold(\n targetDir: string,\n projectName: string,\n templateName = 'default',\n options: ScaffoldOptions = {},\n): void {\n // EC-4 + ADR D5: --bare only applies to default template\n if (options.bare && templateName !== 'default') {\n throw new Error(\n `--bare flag only applies to the default template; got \"${templateName}\". ` +\n `Use \\`npx create-theokit <name> --template=default --bare\\` or pick a different template.`,\n )\n }\n\n const templateDir = getTemplateDir(templateName)\n\n if (!existsSync(templateDir)) {\n throw new Error(\n `Template \"${templateName}\" not found. Available templates: default, dashboard, api-only, postgres`,\n )\n }\n\n if (!isValidProjectName(projectName)) {\n throw new Error(\n `Invalid project name \"${projectName}\". ` +\n `Use lowercase letters, numbers, hyphens, and dots. Must start with a letter or number.`,\n )\n }\n\n if (existsSync(targetDir)) {\n const contents = readdirSync(targetDir)\n if (contents.length > 0) {\n throw new Error(\n `Directory \"${targetDir}\" is not empty. Please use an empty directory.`,\n )\n }\n }\n\n cpSync(templateDir, targetDir, { recursive: true })\n\n const gitignoreSrc = join(targetDir, '_gitignore')\n const gitignoreDest = join(targetDir, '.gitignore')\n if (existsSync(gitignoreSrc)) {\n renameSync(gitignoreSrc, gitignoreDest)\n }\n\n const tmplPath = join(targetDir, 'package.json.tmpl')\n if (existsSync(tmplPath)) {\n const content = readFileSync(tmplPath, 'utf-8')\n const replaced = content.replace(/\\{\\{name\\}\\}/g, projectName)\n writeFileSync(join(targetDir, 'package.json'), replaced)\n unlinkSync(tmplPath)\n }\n\n // T4.1 — Apply --bare transform with EC-4 atomic rollback\n if (options.bare) {\n try {\n applyBareTransform(targetDir, {\n _testForceError: options._testForceTransformError,\n })\n } catch (err) {\n // EC-4: roll back partial state\n rmSync(targetDir, { recursive: true, force: true })\n const original = err instanceof Error ? err.message : String(err)\n throw new Error(\n `Scaffold rolled back: bare transform failed. Check filesystem perms.\\nOriginal error: ${original}`,\n )\n }\n }\n}\n","/**\n * T4.1 — `--bare` transformation.\n *\n * Applied AFTER the default template is copied. Removes:\n * - `@usetheo/ui` from `package.json` dependencies\n * - `app/page.tsx` agent-surface content (replaces with Hello Theo)\n * - `server/routes/chat.ts` (mock chat — depends on TheoUI events)\n *\n * EC-4: callers MUST wrap this in try/catch + `rmSync` rollback so a partial\n * transform never leaves the target dir in a broken state.\n */\n\nimport { existsSync, readFileSync, writeFileSync, unlinkSync } from 'node:fs'\nimport { join } from 'node:path'\n\nconst HELLO_PAGE = `export default function Page() {\n return <h1>Hello Theo</h1>\n}\n`\n\nexport interface BareTransformOptions {\n /** Test-only — force a synthetic write failure to validate rollback path. */\n _testForceError?: string\n}\n\nexport function applyBareTransform(\n targetDir: string,\n options: BareTransformOptions = {},\n): void {\n if (options._testForceError) {\n throw new Error(`Forced transform failure: ${options._testForceError}`)\n }\n\n // 1. Remove @usetheo/ui from package.json deps\n const pkgPath = join(targetDir, 'package.json')\n if (existsSync(pkgPath)) {\n const pkg = JSON.parse(readFileSync(pkgPath, 'utf-8'))\n if (pkg.dependencies && '@usetheo/ui' in pkg.dependencies) {\n delete pkg.dependencies['@usetheo/ui']\n }\n writeFileSync(pkgPath, JSON.stringify(pkg, null, 2) + '\\n')\n }\n\n // 2. Replace app/page.tsx with Hello Theo\n const pagePath = join(targetDir, 'app/page.tsx')\n if (existsSync(pagePath)) {\n writeFileSync(pagePath, HELLO_PAGE)\n }\n\n // 3. Remove mock chat route (depends on AgentEvent type and TheoUI deps)\n const chatPath = join(targetDir, 'server/routes/chat.ts')\n if (existsSync(chatPath)) {\n unlinkSync(chatPath)\n }\n}\n","export type PkgManager = 'npm' | 'pnpm' | 'yarn' | 'bun'\n\nexport function detectPkgManager(): PkgManager {\n const ua = process.env.npm_config_user_agent ?? ''\n if (ua.startsWith('yarn')) return 'yarn'\n if (ua.startsWith('pnpm')) return 'pnpm'\n if (ua.startsWith('bun')) return 'bun'\n return 'npm'\n}\n","import spawn from 'cross-spawn'\nimport type { PkgManager } from './pkg-manager.js'\n\nexport function runInstall(cwd: string, pkgManager: PkgManager): void {\n const result = spawn.sync(pkgManager, ['install'], {\n cwd,\n stdio: 'inherit',\n env: { ...process.env, NODE_ENV: 'development' },\n })\n\n if (result.status !== 0) {\n throw new Error(`Failed to install dependencies with ${pkgManager}`)\n }\n}\n"],"mappings":";;;AAAA,SAAS,WAAAA,gBAAe;;;ACAxB;AAAA,EACE,cAAAC;AAAA,EACA;AAAA,EACA,gBAAAC;AAAA,EACA,iBAAAC;AAAA,EACA;AAAA,EACA,cAAAC;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,SAAS,QAAAC,OAAM,eAAe;AACvC,SAAS,qBAAqB;;;ACC9B,SAAS,YAAY,cAAc,eAAe,kBAAkB;AACpE,SAAS,YAAY;AAErB,IAAM,aAAa;AAAA;AAAA;AAAA;AAUZ,SAAS,mBACd,WACA,UAAgC,CAAC,GAC3B;AACN,MAAI,QAAQ,iBAAiB;AAC3B,UAAM,IAAI,MAAM,6BAA6B,QAAQ,eAAe,EAAE;AAAA,EACxE;AAGA,QAAM,UAAU,KAAK,WAAW,cAAc;AAC9C,MAAI,WAAW,OAAO,GAAG;AACvB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","writeFileSync","unlinkSync","join","existsSync","join","readFileSync","writeFileSync","unlinkSync","resolve"]}
package/package.json CHANGED
@@ -1,11 +1,9 @@
1
1
  {
2
2
  "name": "create-theokit",
3
- "version": "0.1.0-alpha.2",
3
+ "version": "0.1.0-alpha.3",
4
4
  "type": "module",
5
5
  "description": "Scaffold a new TheoKit project",
6
- "scripts": {
7
- "build": "tsup"
8
- },
6
+ "license": "Apache-2.0",
9
7
  "bin": {
10
8
  "create-theokit": "./dist/cli.js"
11
9
  },
@@ -15,5 +13,8 @@
15
13
  ],
16
14
  "dependencies": {
17
15
  "cross-spawn": "^7.0.6"
16
+ },
17
+ "scripts": {
18
+ "build": "tsup"
18
19
  }
19
- }
20
+ }
@@ -1,3 +1,106 @@
1
+ 'use client'
2
+
3
+ import { useState } from 'react'
4
+ import {
5
+ AgentComposer,
6
+ AgentTimeline,
7
+ type AgentEvent as AgentTimelineRow,
8
+ } from '@usetheo/ui'
9
+
10
+ /**
11
+ * Default scaffold — an Agent Surface.
12
+ *
13
+ * This page boots a working agent UI: timeline on the side, composer at the
14
+ * bottom. Out of the box it talks to /api/chat (mock that emits 3 events).
15
+ * Replace the mock at server/routes/chat.ts with your real LLM provider
16
+ * (OpenAI / Anthropic / local). The shape of AgentEvent (theokit/server) is
17
+ * your contract — any provider that emits compatible events plugs in.
18
+ */
1
19
  export default function Page() {
2
- return <h1>Hello Theo</h1>
20
+ const [composerValue, setComposerValue] = useState('')
21
+ const [rows, setRows] = useState<AgentTimelineRow[]>([
22
+ {
23
+ id: 'seed',
24
+ type: 'tool',
25
+ label: 'Agent ready',
26
+ status: 'success',
27
+ timestamp: new Date().toISOString(),
28
+ },
29
+ ])
30
+
31
+ async function handleSubmit() {
32
+ if (!composerValue.trim()) return
33
+ const userMessage = composerValue
34
+ setComposerValue('')
35
+
36
+ const res = await fetch('/api/chat', {
37
+ method: 'POST',
38
+ headers: { 'content-type': 'application/json' },
39
+ body: JSON.stringify({ message: userMessage }),
40
+ })
41
+ if (!res.body) return
42
+
43
+ const reader = res.body.getReader()
44
+ const decoder = new TextDecoder()
45
+ let buf = ''
46
+ while (true) {
47
+ const { done, value } = await reader.read()
48
+ if (done) break
49
+ buf += decoder.decode(value, { stream: true })
50
+ const chunks = buf.split('\n\n')
51
+ buf = chunks.pop() ?? ''
52
+ for (const chunk of chunks) {
53
+ if (!chunk.startsWith('data:')) continue
54
+ try {
55
+ const event = JSON.parse(chunk.slice(5).trim()) as {
56
+ type: string
57
+ [k: string]: unknown
58
+ }
59
+ setRows((prev) => [
60
+ ...prev,
61
+ {
62
+ id: String(prev.length + 1),
63
+ type: event.type === 'tool_call' ? 'tool' : 'command',
64
+ label:
65
+ event.type === 'message'
66
+ ? String(event.content)
67
+ : event.type === 'tool_call'
68
+ ? `tool: ${String(event.name)}`
69
+ : event.type === 'error'
70
+ ? `error: ${String(event.message)}`
71
+ : event.type,
72
+ status: event.type === 'error' ? 'failed' : 'success',
73
+ timestamp: new Date().toISOString(),
74
+ },
75
+ ])
76
+ } catch {
77
+ // skip malformed chunk
78
+ }
79
+ }
80
+ }
81
+ }
82
+
83
+ return (
84
+ <main style={{ display: 'flex', flexDirection: 'column', height: '100vh', padding: 24, gap: 16 }}>
85
+ <header>
86
+ <h1 style={{ fontSize: 20, fontWeight: 600 }}>Theo Agent</h1>
87
+ <p style={{ color: '#888', fontSize: 14 }}>
88
+ Mock LLM connected. Replace <code>server/routes/chat.ts</code> with your provider.
89
+ </p>
90
+ </header>
91
+
92
+ <section style={{ flex: 1, overflowY: 'auto' }}>
93
+ <AgentTimeline events={rows} />
94
+ </section>
95
+
96
+ <footer>
97
+ <AgentComposer
98
+ value={composerValue}
99
+ onValueChange={setComposerValue}
100
+ onSubmit={handleSubmit}
101
+ placeholder="Ask the agent…"
102
+ />
103
+ </footer>
104
+ </main>
105
+ )
3
106
  }
@@ -7,7 +7,8 @@
7
7
  "dev": "theokit dev"
8
8
  },
9
9
  "dependencies": {
10
- "theokit": "^0.1.0-alpha.1",
10
+ "theokit": "^0.1.0-alpha.3",
11
+ "@usetheo/ui": "^0.1.0-next.0",
11
12
  "react": "^19.0.0",
12
13
  "react-dom": "^19.0.0"
13
14
  },
@@ -0,0 +1,59 @@
1
+ import { defineRoute } from 'theokit/server'
2
+ import { z } from 'zod'
3
+ import type { AgentEvent } from 'theokit/server'
4
+
5
+ /**
6
+ * MOCK AGENT ENDPOINT — REPLACE WITH YOUR REAL LLM PROVIDER.
7
+ *
8
+ * What this is:
9
+ * A demo that emits 3 hardcoded events so the default scaffold has
10
+ * something to render from the first `theokit dev`.
11
+ *
12
+ * What to do here:
13
+ * Substitua este mock pelo seu LLM provider (OpenAI/Anthropic/local).
14
+ * O shape de AgentEvent é o contrato — qualquer provider que produza
15
+ * events compatíveis (`message`, `tool_call`, `tool_result`, `error`)
16
+ * funciona. Para token streaming, prefira UM evento `message` com
17
+ * content acumulado em vez de um evento por token (evita SSE backpressure).
18
+ *
19
+ * Example real handler:
20
+ * import { OpenAI } from 'openai'
21
+ * const stream = await openai.chat.completions.create({ stream: true, ... })
22
+ * for await (const chunk of stream) {
23
+ * // yield { type: 'message', content: chunk.choices[0].delta.content }
24
+ * }
25
+ *
26
+ * The shape on the wire is server-sent events (text/event-stream):
27
+ * data: {"type":"message","content":"..."}\n\n
28
+ * data: {"type":"tool_call","name":"...","args":{...}}\n\n
29
+ * ...
30
+ */
31
+ export const POST = defineRoute({
32
+ body: z.object({ message: z.string().min(1) }),
33
+ handler: ({ body }) => {
34
+ const events: AgentEvent[] = [
35
+ { type: 'message', content: `Recebi: "${body.message}"` },
36
+ { type: 'tool_call', name: 'search', args: { q: body.message } },
37
+ { type: 'message', content: 'Pronto. (Este é um mock — conecte seu LLM aqui.)' },
38
+ ]
39
+
40
+ const stream = new ReadableStream<Uint8Array>({
41
+ start(controller) {
42
+ const encoder = new TextEncoder()
43
+ for (const event of events) {
44
+ controller.enqueue(encoder.encode(`data: ${JSON.stringify(event)}\n\n`))
45
+ }
46
+ controller.close()
47
+ },
48
+ })
49
+
50
+ return new Response(stream, {
51
+ status: 200,
52
+ headers: {
53
+ 'Content-Type': 'text/event-stream',
54
+ 'Cache-Control': 'no-cache',
55
+ Connection: 'keep-alive',
56
+ },
57
+ })
58
+ },
59
+ })