@bagelink/workspace 1.8.26 → 1.8.30

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.
@@ -0,0 +1,495 @@
1
+ 'use strict';
2
+
3
+ const node_fs = require('node:fs');
4
+ const node_path = require('node:path');
5
+ const process = require('node:process');
6
+ const prompts = require('prompts');
7
+
8
+ function _interopDefaultCompat (e) { return e && typeof e === 'object' && 'default' in e ? e.default : e; }
9
+
10
+ const process__default = /*#__PURE__*/_interopDefaultCompat(process);
11
+ const prompts__default = /*#__PURE__*/_interopDefaultCompat(prompts);
12
+
13
+ async function initWorkspace(root = process__default.cwd()) {
14
+ console.log("\n\u{1F680} Creating Bagel workspace...\n");
15
+ const response = await prompts__default([
16
+ {
17
+ type: "text",
18
+ name: "workspaceName",
19
+ message: "Workspace name:",
20
+ initial: "my-workspace"
21
+ },
22
+ {
23
+ type: "text",
24
+ name: "projectId",
25
+ message: "Bagel project ID:",
26
+ initial: "my-project"
27
+ },
28
+ {
29
+ type: "confirm",
30
+ name: "createFirstProject",
31
+ message: "Create first project?",
32
+ initial: true
33
+ },
34
+ {
35
+ type: (prev) => prev ? "text" : null,
36
+ name: "firstProjectName",
37
+ message: "First project name:",
38
+ initial: "web"
39
+ }
40
+ ]);
41
+ if (!response || !response.workspaceName) {
42
+ console.log("\n\u274C Workspace creation cancelled.\n");
43
+ process__default.exit(1);
44
+ }
45
+ const { workspaceName, projectId, createFirstProject, firstProjectName } = response;
46
+ const workspaceDir = node_path.resolve(root, workspaceName);
47
+ createWorkspaceRoot(root, workspaceName, projectId);
48
+ createSharedPackage(workspaceDir);
49
+ if (createFirstProject && firstProjectName) {
50
+ await addProject(firstProjectName, workspaceDir);
51
+ }
52
+ console.log("\n\u2705 Workspace created successfully!");
53
+ console.log("\nNext steps:");
54
+ console.log(` cd ${workspaceName}`);
55
+ console.log(" bun install");
56
+ if (createFirstProject) {
57
+ console.log(` bun run dev:${firstProjectName}`);
58
+ } else {
59
+ console.log(" bgl add <project-name> # Add a project");
60
+ }
61
+ console.log("");
62
+ }
63
+ function createWorkspaceRoot(root, name, projectId) {
64
+ const workspaceDir = node_path.resolve(root, name);
65
+ if (node_fs.existsSync(workspaceDir)) {
66
+ console.error(`\u274C Directory ${name} already exists`);
67
+ process__default.exit(1);
68
+ }
69
+ node_fs.mkdirSync(workspaceDir, { recursive: true });
70
+ const packageJson = {
71
+ name,
72
+ private: true,
73
+ workspaces: ["*", "!node_modules"],
74
+ scripts: {
75
+ "dev": "bgl dev",
76
+ "dev:local": "bgl dev --mode localhost",
77
+ "dev:verbose": "bun run --filter './!shared*' dev",
78
+ "build": "bgl build",
79
+ "typecheck": "tsc --noEmit",
80
+ "lint": "eslint . --cache",
81
+ "lint:fix": "eslint . --cache --fix"
82
+ },
83
+ dependencies: {
84
+ "@bagelink/auth": "latest",
85
+ "@bagelink/sdk": "latest",
86
+ "@bagelink/vue": "latest",
87
+ "pinia": "latest",
88
+ "vue": "latest",
89
+ "vue-router": "latest"
90
+ },
91
+ devDependencies: {
92
+ "@bagelink/lint-config": "latest",
93
+ "@bagelink/workspace": "latest",
94
+ "@vitejs/plugin-vue": "latest",
95
+ "eslint": "latest",
96
+ "typescript": "^5.0.0",
97
+ "vite": "latest"
98
+ }
99
+ };
100
+ node_fs.writeFileSync(
101
+ node_path.resolve(workspaceDir, "package.json"),
102
+ `${JSON.stringify(packageJson, null, 2)}
103
+ `
104
+ );
105
+ const bglConfig = `import { defineWorkspace } from '@bagelink/workspace'
106
+
107
+ export default defineWorkspace({
108
+ localhost: {
109
+ host: 'http://localhost:8000',
110
+ proxy: '/api',
111
+ openapi_url: 'http://localhost:8000/openapi.json',
112
+ },
113
+ development: {
114
+ host: 'https://${projectId}.bagel.to',
115
+ proxy: '/api',
116
+ openapi_url: 'https://${projectId}.bagel.to/openapi.json',
117
+ },
118
+ production: {
119
+ host: 'https://${projectId}.bagel.to',
120
+ proxy: '/api',
121
+ openapi_url: 'https://${projectId}.bagel.to/openapi.json',
122
+ },
123
+ })
124
+ `;
125
+ node_fs.writeFileSync(node_path.resolve(workspaceDir, "bgl.config.ts"), bglConfig);
126
+ const tsConfig = {
127
+ compilerOptions: {
128
+ target: "ES2020",
129
+ useDefineForClassFields: true,
130
+ module: "ESNext",
131
+ lib: ["ES2020", "DOM", "DOM.Iterable"],
132
+ skipLibCheck: true,
133
+ moduleResolution: "bundler",
134
+ allowImportingTsExtensions: true,
135
+ resolveJsonModule: true,
136
+ isolatedModules: true,
137
+ noEmit: true,
138
+ jsx: "preserve",
139
+ strict: true,
140
+ noUnusedLocals: true,
141
+ noUnusedParameters: true,
142
+ noFallthroughCasesInSwitch: true,
143
+ baseUrl: ".",
144
+ paths: {
145
+ "shared/*": ["./shared/*"]
146
+ }
147
+ }
148
+ };
149
+ node_fs.writeFileSync(
150
+ node_path.resolve(workspaceDir, "tsconfig.json"),
151
+ `${JSON.stringify(tsConfig, null, 2)}
152
+ `
153
+ );
154
+ const gitignore = `node_modules
155
+ dist
156
+ .DS_Store
157
+ *.local
158
+ .env.local
159
+ .vite
160
+ `;
161
+ node_fs.writeFileSync(node_path.resolve(workspaceDir, ".gitignore"), gitignore);
162
+ const scriptsDir = node_path.resolve(workspaceDir, "scripts");
163
+ node_fs.mkdirSync(scriptsDir, { recursive: true });
164
+ const devRunnerContent = `#!/usr/bin/env bun
165
+ import { spawn } from 'bun'
166
+ import { readdir } from 'fs/promises'
167
+ import { resolve } from 'path'
168
+
169
+ const projectsRoot = process.cwd()
170
+ const projects = (await readdir(projectsRoot, { withFileTypes: true }))
171
+ .filter(
172
+ item =>
173
+ item.isDirectory()
174
+ && item.name !== 'node_modules'
175
+ && item.name !== 'shared'
176
+ && item.name !== 'scripts'
177
+ && item.name !== '.git'
178
+ && !item.name.startsWith('.'),
179
+ )
180
+ .map(item => item.name)
181
+
182
+ console.log(\`\\n\u{1F680} Starting \${projects.length} project\${projects.length > 1 ? 's' : ''}...\\n\`)
183
+
184
+ const urlPattern = /Local:\\s+(http:\\/\\/localhost:\\d+)/
185
+
186
+ projects.forEach((project) => {
187
+ const proc = spawn({
188
+ cmd: ['bun', 'run', 'dev'],
189
+ cwd: resolve(projectsRoot, project),
190
+ stdout: 'pipe',
191
+ stderr: 'pipe',
192
+ })
193
+
194
+ const decoder = new TextDecoder()
195
+
196
+ proc.stdout.pipeTo(
197
+ new WritableStream({
198
+ write(chunk) {
199
+ const text = decoder.decode(chunk)
200
+ const match = text.match(urlPattern)
201
+ if (match) {
202
+ console.log(\` \u2713 \${project.padEnd(15)} \u2192 \${match[1]}\`)
203
+ }
204
+ },
205
+ }),
206
+ )
207
+
208
+ proc.stderr.pipeTo(
209
+ new WritableStream({
210
+ write(chunk) {
211
+ const text = decoder.decode(chunk)
212
+ if (text.includes('error') || text.includes('Error')) {
213
+ console.error(\` \u2717 \${project}: \${text.trim()}\`)
214
+ }
215
+ },
216
+ }),
217
+ )
218
+ })
219
+
220
+ console.log('\\n\u{1F4A1} Press Ctrl+C to stop all servers\\n')
221
+
222
+ process.on('SIGINT', () => {
223
+ console.log('\\n\\n\u{1F44B} Stopping all servers...\\n')
224
+ process.exit()
225
+ })
226
+ `;
227
+ node_fs.writeFileSync(node_path.resolve(scriptsDir, "dev.ts"), devRunnerContent);
228
+ console.log(`\u2705 Created workspace: ${name}`);
229
+ }
230
+ function createSharedPackage(root) {
231
+ const sharedDir = node_path.resolve(root, "shared");
232
+ node_fs.mkdirSync(sharedDir, { recursive: true });
233
+ const packageJson = {
234
+ name: "shared",
235
+ version: "1.0.0",
236
+ type: "module",
237
+ exports: {
238
+ ".": "./index.ts",
239
+ "./utils": "./utils/index.ts",
240
+ "./types": "./types/index.ts"
241
+ }
242
+ };
243
+ node_fs.writeFileSync(
244
+ node_path.resolve(sharedDir, "package.json"),
245
+ `${JSON.stringify(packageJson, null, 2)}
246
+ `
247
+ );
248
+ node_fs.writeFileSync(
249
+ node_path.resolve(sharedDir, "index.ts"),
250
+ "// Shared utilities and exports\nexport * from './utils'\n"
251
+ );
252
+ node_fs.mkdirSync(node_path.resolve(sharedDir, "utils"), { recursive: true });
253
+ node_fs.writeFileSync(
254
+ node_path.resolve(sharedDir, "utils", "index.ts"),
255
+ "// Shared utility functions\nexport function formatDate(date: Date): string {\n return date.toISOString()\n}\n"
256
+ );
257
+ node_fs.mkdirSync(node_path.resolve(sharedDir, "types"), { recursive: true });
258
+ node_fs.writeFileSync(
259
+ node_path.resolve(sharedDir, "types", "index.ts"),
260
+ "// Shared types\nexport interface User {\n id: string\n name: string\n}\n"
261
+ );
262
+ console.log("\u2705 Created shared package");
263
+ }
264
+ async function addProject(name, root = process__default.cwd()) {
265
+ const projectDir = node_path.resolve(root, name);
266
+ if (node_fs.existsSync(projectDir)) {
267
+ console.error(`\u274C Project ${name} already exists`);
268
+ process__default.exit(1);
269
+ }
270
+ console.log(`
271
+ \u{1F4E6} Creating project: ${name}
272
+ `);
273
+ node_fs.mkdirSync(projectDir, { recursive: true });
274
+ const isWorkspace = node_fs.existsSync(node_path.resolve(root, "bgl.config.ts"));
275
+ const packageJson = {
276
+ name,
277
+ type: "module",
278
+ scripts: {
279
+ dev: "vite",
280
+ build: "vite build",
281
+ preview: "vite preview"
282
+ },
283
+ dependencies: {},
284
+ devDependencies: {
285
+ "@vitejs/plugin-vue": "latest",
286
+ "vite": "latest",
287
+ "vue": "latest"
288
+ }
289
+ };
290
+ if (isWorkspace) {
291
+ packageJson.dependencies.shared = "workspace:*";
292
+ }
293
+ node_fs.writeFileSync(
294
+ node_path.resolve(projectDir, "package.json"),
295
+ `${JSON.stringify(packageJson, null, 2)}
296
+ `
297
+ );
298
+ const bglConfigContent = isWorkspace ? `import { defineWorkspace } from '@bagelink/workspace'
299
+ import rootWorkspace from '../bgl.config'
300
+
301
+ export default defineWorkspace({
302
+ localhost: rootWorkspace('localhost'),
303
+ development: rootWorkspace('development'),
304
+ production: rootWorkspace('production'),
305
+ })
306
+ ` : `import { defineWorkspace } from '@bagelink/workspace'
307
+
308
+ export default defineWorkspace({
309
+ localhost: {
310
+ host: 'http://localhost:8000',
311
+ proxy: '/api',
312
+ },
313
+ development: {
314
+ host: 'https://my-project.bagel.to',
315
+ proxy: '/api',
316
+ },
317
+ production: {
318
+ host: 'https://my-project.bagel.to',
319
+ proxy: '/api',
320
+ },
321
+ })
322
+ `;
323
+ node_fs.writeFileSync(node_path.resolve(projectDir, "bgl.config.ts"), bglConfigContent);
324
+ const viteConfig = `import { defineConfig } from 'vite'
325
+ import vue from '@vitejs/plugin-vue'
326
+ import { bagelink } from '@bagelink/workspace/vite'
327
+ import workspace from './bgl.config'
328
+
329
+ export default defineConfig({
330
+ plugins: [
331
+ vue(),
332
+ bagelink({ workspace }),
333
+ ],
334
+ })
335
+ `;
336
+ node_fs.writeFileSync(node_path.resolve(projectDir, "vite.config.ts"), viteConfig);
337
+ const srcDir = node_path.resolve(projectDir, "src");
338
+ node_fs.mkdirSync(srcDir, { recursive: true });
339
+ const indexHtml = `<!DOCTYPE html>
340
+ <html lang="en">
341
+ <head>
342
+ <meta charset="UTF-8">
343
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
344
+ <title>${name}</title>
345
+ </head>
346
+ <body>
347
+ <div id="app"></div>
348
+ <script type="module" src="/src/main.ts"><\/script>
349
+ </body>
350
+ </html>
351
+ `;
352
+ node_fs.writeFileSync(node_path.resolve(projectDir, "index.html"), indexHtml);
353
+ const mainTs = `import { createApp } from 'vue'
354
+ import App from './App.vue'
355
+
356
+ createApp(App).mount('#app')
357
+ `;
358
+ node_fs.writeFileSync(node_path.resolve(srcDir, "main.ts"), mainTs);
359
+ const appVue = `<script setup lang="ts">
360
+ import { ref } from 'vue'
361
+ ${isWorkspace ? "import { formatDate } from 'shared/utils'\n" : ""}
362
+ const count = ref(0)
363
+ <\/script>
364
+
365
+ <template>
366
+ <div>
367
+ <h1>${name}</h1>
368
+ <button @click="count++">Count: {{ count }}</button>
369
+ ${isWorkspace ? "<p>{{ formatDate(new Date()) }}</p>" : ""}
370
+ </div>
371
+ </template>
372
+ `;
373
+ node_fs.writeFileSync(node_path.resolve(srcDir, "App.vue"), appVue);
374
+ console.log(`\u2705 Created project: ${name}`);
375
+ if (isWorkspace) {
376
+ updateWorkspaceScripts(root, name);
377
+ }
378
+ console.log("\nNext steps:");
379
+ console.log(` cd ${name}`);
380
+ console.log(" bun install");
381
+ console.log(" bun run dev");
382
+ console.log("");
383
+ }
384
+ function updateWorkspaceScripts(root, projectName) {
385
+ const packageJsonPath = node_path.resolve(root, "package.json");
386
+ if (!node_fs.existsSync(packageJsonPath)) return;
387
+ try {
388
+ const packageJson = JSON.parse(
389
+ node_fs.readFileSync(packageJsonPath, "utf-8")
390
+ );
391
+ if (!packageJson.scripts) {
392
+ packageJson.scripts = {};
393
+ }
394
+ packageJson.scripts[`dev:${projectName}`] = `bun --filter ${projectName} dev`;
395
+ packageJson.scripts[`build:${projectName}`] = `bun --filter ${projectName} build`;
396
+ node_fs.writeFileSync(
397
+ packageJsonPath,
398
+ `${JSON.stringify(packageJson, null, 2)}
399
+ `
400
+ );
401
+ console.log(`\u2705 Added scripts: dev:${projectName}, build:${projectName}`);
402
+ } catch (error) {
403
+ console.warn("\u26A0\uFE0F Could not update workspace scripts");
404
+ }
405
+ }
406
+ function listProjects(root = process__default.cwd()) {
407
+ try {
408
+ const items = node_fs.readdirSync(root, { withFileTypes: true });
409
+ return items.filter(
410
+ (item) => item.isDirectory() && item.name !== "node_modules" && item.name !== "shared" && item.name !== "scripts" && item.name !== ".git" && !item.name.startsWith(".")
411
+ ).map((item) => item.name).sort();
412
+ } catch {
413
+ return [];
414
+ }
415
+ }
416
+
417
+ function generateNetlifyRedirect(config) {
418
+ const redirect = `# API Proxy Configuration
419
+ # Environment variables are set in Netlify UI or netlify.toml [build.environment] section
420
+
421
+ [[redirects]]
422
+ from = "${config.proxy}/*"
423
+ to = "${config.host}/:splat"
424
+ status = 200
425
+ force = true
426
+ headers = {X-From = "Netlify"}
427
+ `;
428
+ return redirect;
429
+ }
430
+ function generateNetlifyConfigTemplate() {
431
+ return `# Standard Netlify configuration for Bagelink projects
432
+ # Uses environment variables for proxy configuration
433
+
434
+ [build.environment]
435
+ # Set these in Netlify UI or override here
436
+ # BGL_PROXY_PATH = "/api"
437
+ # BGL_API_HOST = "https://your-project.bagel.to"
438
+
439
+ [[redirects]]
440
+ # Proxy API requests to backend
441
+ # Uses BGL_PROXY_PATH and BGL_API_HOST from environment
442
+ from = "/api/*"
443
+ to = "https://your-project.bagel.to/:splat"
444
+ status = 200
445
+ force = true
446
+ headers = {X-From = "Netlify"}
447
+
448
+ # Example: Multiple API backends
449
+ # [[redirects]]
450
+ # from = "/api/v2/*"
451
+ # to = "https://api-v2.example.com/:splat"
452
+ # status = 200
453
+ # force = true
454
+ `;
455
+ }
456
+ function generateNetlifyConfig(config, additionalConfig, useTemplate = false) {
457
+ if (useTemplate) {
458
+ return generateNetlifyConfigTemplate();
459
+ }
460
+ const redirect = generateNetlifyRedirect(config);
461
+ if (additionalConfig !== void 0 && additionalConfig !== "") {
462
+ return `${redirect}
463
+ ${additionalConfig}`;
464
+ }
465
+ return redirect;
466
+ }
467
+ function writeNetlifyConfig(config, outPath = "./netlify.toml", additionalConfig, useTemplate = false) {
468
+ const content = generateNetlifyConfig(config, additionalConfig, useTemplate);
469
+ const resolvedPath = node_path.resolve(outPath);
470
+ node_fs.writeFileSync(resolvedPath, content, "utf-8");
471
+ console.log(`\u2713 Generated netlify.toml at ${resolvedPath}`);
472
+ if (!useTemplate) {
473
+ console.log("\n\u{1F4A1} Tip: For environment-based config, set these in Netlify UI:");
474
+ console.log(` BGL_PROXY_PATH = "${config.proxy}"`);
475
+ console.log(` BGL_API_HOST = "${config.host}"`);
476
+ if (config.openapi_url) {
477
+ console.log(` BGL_OPENAPI_URL = "${config.openapi_url}"`);
478
+ }
479
+ console.log("");
480
+ }
481
+ }
482
+ function setBuildEnvVars(config) {
483
+ process__default.env.BGL_PROXY_PATH = config.proxy;
484
+ process__default.env.BGL_API_HOST = config.host;
485
+ if (config.openapi_url !== void 0 && config.openapi_url !== "") {
486
+ process__default.env.BGL_OPENAPI_URL = config.openapi_url;
487
+ }
488
+ }
489
+
490
+ exports.addProject = addProject;
491
+ exports.generateNetlifyConfig = generateNetlifyConfig;
492
+ exports.initWorkspace = initWorkspace;
493
+ exports.listProjects = listProjects;
494
+ exports.setBuildEnvVars = setBuildEnvVars;
495
+ exports.writeNetlifyConfig = writeNetlifyConfig;