@canonical/summon-application 0.29.0 → 0.31.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (126) hide show
  1. package/README.md +75 -13
  2. package/dist/esm/application/react/index.js +347 -0
  3. package/dist/esm/application/react/index.js.map +1 -0
  4. package/dist/esm/application/react/templates/.browserslistrc +2 -0
  5. package/dist/esm/application/react/templates/.storybook/main.ts.ejs +10 -0
  6. package/{src → dist/esm}/application/react/templates/README.md.ejs +54 -0
  7. package/dist/esm/application/react/templates/biome.json.ejs +6 -0
  8. package/dist/esm/application/react/templates/gitignore +25 -0
  9. package/{src → dist/esm}/application/react/templates/package.json.ejs +36 -2
  10. package/dist/esm/application/react/templates/patches/react-relay@18.2.0.patch +52 -0
  11. package/dist/esm/application/react/templates/patches/relay-runtime-network@0.1.0.patch +46 -0
  12. package/dist/esm/application/react/templates/relay.config.json +8 -0
  13. package/{src/application/react/templates/src/client/entry.tsx → dist/esm/application/react/templates/src/client/entry.tsx.ejs} +23 -0
  14. package/dist/esm/application/react/templates/src/domains/catalog/CatalogPage.tsx +50 -0
  15. package/dist/esm/application/react/templates/src/domains/catalog/ErrorBoundary.tests.tsx +56 -0
  16. package/dist/esm/application/react/templates/src/domains/catalog/ErrorBoundary.tsx +37 -0
  17. package/dist/esm/application/react/templates/src/domains/catalog/ProductCard.tsx +49 -0
  18. package/dist/esm/application/react/templates/src/domains/catalog/ProductList.stories.tsx +103 -0
  19. package/dist/esm/application/react/templates/src/domains/catalog/ProductList.tests.tsx +80 -0
  20. package/dist/esm/application/react/templates/src/domains/catalog/ProductList.tsx +59 -0
  21. package/dist/esm/application/react/templates/src/domains/catalog/routes.ts +11 -0
  22. package/dist/esm/application/react/templates/src/lib/ClientOnly/ClientOnly.tests.tsx +35 -0
  23. package/dist/esm/application/react/templates/src/lib/ClientOnly/ClientOnly.tsx +31 -0
  24. package/dist/esm/application/react/templates/src/lib/ClientOnly/index.ts +1 -0
  25. package/{src → dist/esm}/application/react/templates/src/lib/Navigation/Navigation.tsx.ejs +3 -0
  26. package/{src/application/react/templates/src/lib/index.ts → dist/esm/application/react/templates/src/lib/index.ts.ejs} +3 -0
  27. package/dist/esm/application/react/templates/src/relay/__generated__/ProductCard_product.graphql.ts +82 -0
  28. package/dist/esm/application/react/templates/src/relay/__generated__/ProductListQuery.graphql.ts +272 -0
  29. package/dist/esm/application/react/templates/src/relay/environment.tests.ts +87 -0
  30. package/dist/esm/application/react/templates/src/relay/environment.ts +119 -0
  31. package/dist/esm/application/react/templates/src/relay/schema.graphql +111 -0
  32. package/dist/esm/application/react/templates/src/relay/schema.tests.ts +137 -0
  33. package/dist/esm/application/react/templates/src/relay/schema.ts +205 -0
  34. package/{src → dist/esm}/application/react/templates/src/routes.tsx.ejs +10 -0
  35. package/{src/application/react/templates/src/server/entry.tsx → dist/esm/application/react/templates/src/server/entry.tsx.ejs} +36 -0
  36. package/{src → dist/esm}/application/react/templates/src/sitemap/getSitemapItems.ts.ejs +3 -0
  37. package/{src/application/react/templates/tsconfig.json → dist/esm/application/react/templates/tsconfig.json.ejs} +3 -0
  38. package/dist/esm/application/react/templates/vite.config.ts.ejs +92 -0
  39. package/dist/esm/application/react/templates/vitest.setup.ts.ejs +22 -0
  40. package/dist/esm/domain/index.js +89 -0
  41. package/dist/esm/domain/index.js.map +1 -0
  42. package/{src/index.ts → dist/esm/index.js} +6 -8
  43. package/dist/esm/index.js.map +1 -0
  44. package/dist/esm/route/index.js +115 -0
  45. package/dist/esm/route/index.js.map +1 -0
  46. package/dist/esm/route/insertRoute.js +178 -0
  47. package/dist/esm/route/insertRoute.js.map +1 -0
  48. package/dist/esm/shared/casing.js +15 -0
  49. package/dist/esm/shared/casing.js.map +1 -0
  50. package/dist/esm/shared/packageManager.js +38 -0
  51. package/dist/esm/shared/packageManager.js.map +1 -0
  52. package/dist/esm/shared/versions.js +88 -0
  53. package/dist/esm/shared/versions.js.map +1 -0
  54. package/dist/esm/wrapper/index.js +72 -0
  55. package/dist/esm/wrapper/index.js.map +1 -0
  56. package/dist/types/application/react/index.d.ts +12 -0
  57. package/dist/types/application/react/index.d.ts.map +1 -0
  58. package/dist/types/domain/index.d.ts +7 -0
  59. package/dist/types/domain/index.d.ts.map +1 -0
  60. package/dist/types/index.d.ts +8 -0
  61. package/dist/types/index.d.ts.map +1 -0
  62. package/dist/types/route/index.d.ts +7 -0
  63. package/dist/types/route/index.d.ts.map +1 -0
  64. package/dist/types/route/insertRoute.d.ts +34 -0
  65. package/dist/types/route/insertRoute.d.ts.map +1 -0
  66. package/{src/shared/casing.ts → dist/types/shared/casing.d.ts} +2 -7
  67. package/dist/types/shared/casing.d.ts.map +1 -0
  68. package/dist/types/shared/packageManager.d.ts +19 -0
  69. package/dist/types/shared/packageManager.d.ts.map +1 -0
  70. package/dist/types/shared/versions.d.ts +15 -0
  71. package/dist/types/shared/versions.d.ts.map +1 -0
  72. package/dist/types/wrapper/index.d.ts +7 -0
  73. package/dist/types/wrapper/index.d.ts.map +1 -0
  74. package/package.json +16 -15
  75. package/src/application/react/index.ts +0 -294
  76. package/src/application/react/templates/.storybook/main.ts +0 -5
  77. package/src/application/react/templates/biome.json.ejs +0 -6
  78. package/src/application/react/templates/vite.config.ts +0 -45
  79. package/src/application/react/templates/vitest.setup.ts +0 -9
  80. package/src/domain/index.ts +0 -119
  81. package/src/index.test.ts +0 -398
  82. package/src/route/index.ts +0 -154
  83. package/src/route/insertRoute.test.ts +0 -98
  84. package/src/route/insertRoute.ts +0 -236
  85. package/src/shared/versions.ts +0 -48
  86. package/src/wrapper/index.ts +0 -100
  87. /package/{src → dist/esm}/application/react/templates/.storybook/decorators/index.ts +0 -0
  88. /package/{src → dist/esm}/application/react/templates/.storybook/decorators/withRouter.tsx +0 -0
  89. /package/{src → dist/esm}/application/react/templates/.storybook/preview.ts +0 -0
  90. /package/{src → dist/esm}/application/react/templates/index.html.ejs +0 -0
  91. /package/{src → dist/esm}/application/react/templates/public/.gitkeep +0 -0
  92. /package/{src → dist/esm}/application/react/templates/public/robots.txt +0 -0
  93. /package/{src → dist/esm}/application/react/templates/src/assets/.gitkeep +0 -0
  94. /package/{src → dist/esm}/application/react/templates/src/domains/account/AccountPage.tsx +0 -0
  95. /package/{src → dist/esm}/application/react/templates/src/domains/account/LoginPage.tsx +0 -0
  96. /package/{src → dist/esm}/application/react/templates/src/domains/account/routes.ts +0 -0
  97. /package/{src → dist/esm}/application/react/templates/src/domains/contact/ContactPage.tsx +0 -0
  98. /package/{src → dist/esm}/application/react/templates/src/domains/contact/routes.ts +0 -0
  99. /package/{src → dist/esm}/application/react/templates/src/domains/marketing/GuidePage.tsx +0 -0
  100. /package/{src → dist/esm}/application/react/templates/src/domains/marketing/HomePage.tsx +0 -0
  101. /package/{src → dist/esm}/application/react/templates/src/domains/marketing/routes.ts +0 -0
  102. /package/{src → dist/esm}/application/react/templates/src/lib/ExampleComponent/ExampleComponent.stories.tsx +0 -0
  103. /package/{src → dist/esm}/application/react/templates/src/lib/ExampleComponent/ExampleComponent.tests.tsx +0 -0
  104. /package/{src → dist/esm}/application/react/templates/src/lib/ExampleComponent/ExampleComponent.tsx +0 -0
  105. /package/{src → dist/esm}/application/react/templates/src/lib/ExampleComponent/index.ts +0 -0
  106. /package/{src → dist/esm}/application/react/templates/src/lib/ExampleComponent/styles.css +0 -0
  107. /package/{src → dist/esm}/application/react/templates/src/lib/ExampleComponent/types.ts +0 -0
  108. /package/{src → dist/esm}/application/react/templates/src/lib/LazyComponent/LazyComponent.stories.tsx +0 -0
  109. /package/{src → dist/esm}/application/react/templates/src/lib/LazyComponent/LazyComponent.tsx +0 -0
  110. /package/{src → dist/esm}/application/react/templates/src/lib/LazyComponent/index.ts +0 -0
  111. /package/{src → dist/esm}/application/react/templates/src/lib/Navigation/index.ts +0 -0
  112. /package/{src → dist/esm}/application/react/templates/src/lib/ThemeSelector/ThemeSelector.tsx +0 -0
  113. /package/{src → dist/esm}/application/react/templates/src/lib/ThemeSelector/index.ts +0 -0
  114. /package/{src → dist/esm}/application/react/templates/src/server/preview.bun.ts +0 -0
  115. /package/{src → dist/esm}/application/react/templates/src/server/preview.express.ts +0 -0
  116. /package/{src → dist/esm}/application/react/templates/src/server/renderer.tsx +0 -0
  117. /package/{src → dist/esm}/application/react/templates/src/server/server.bun.ts +0 -0
  118. /package/{src → dist/esm}/application/react/templates/src/server/server.express.ts +0 -0
  119. /package/{src → dist/esm}/application/react/templates/src/sitemap/renderer.ts +0 -0
  120. /package/{src → dist/esm}/application/react/templates/src/styles/app.css +0 -0
  121. /package/{src → dist/esm}/application/react/templates/src/styles/index.css.ejs +0 -0
  122. /package/{src → dist/esm}/application/react/templates/src/vite-env.d.ts +0 -0
  123. /package/{src → dist/esm}/application/react/templates/test/e2e/serverHarness.ts +0 -0
  124. /package/{src → dist/esm}/application/react/templates/test/e2e/servers.e2e.ts +0 -0
  125. /package/{src → dist/esm}/application/react/templates/vitest.config.ts +0 -0
  126. /package/{src → dist/esm}/application/react/templates/vitest.e2e.config.ts +0 -0
@@ -1,154 +0,0 @@
1
- import * as path from "node:path";
2
- import type {
3
- GeneratorDefinition,
4
- PromptDefinition,
5
- } from "@canonical/summon-core";
6
- import {
7
- exists,
8
- fail,
9
- flatMap,
10
- info,
11
- sequence_,
12
- transformFile,
13
- writeFile,
14
- } from "@canonical/task";
15
- import { toCamelCase, toPascalCase, toTitleCase } from "@canonical/utils";
16
- import { normalizeCommandPath } from "../shared/casing.js";
17
- import { insertRoute, removeRoute } from "./insertRoute.js";
18
-
19
- interface RouteAnswers {
20
- readonly routePath: string;
21
- }
22
-
23
- const prompts: PromptDefinition[] = [
24
- {
25
- name: "routePath",
26
- type: "text",
27
- message: "Route path (for example account/settings):",
28
- default: "example/page",
29
- positional: true,
30
- group: "Route",
31
- },
32
- ];
33
-
34
- function buildPage(routeName: string): string {
35
- const pageName = `${toPascalCase(routeName)}Page`;
36
- const title = toTitleCase(routeName);
37
- const slugId = toCamelCase(routeName);
38
-
39
- return `import { useHead } from "@canonical/react-head";
40
- import type { ReactElement } from "react";
41
-
42
- export default function ${pageName}(): ReactElement {
43
- useHead({ title: "${title}" });
44
-
45
- return (
46
- <section aria-labelledby="${slugId}-title">
47
- <h1 id="${slugId}-title">${title}</h1>
48
- </section>
49
- );
50
- }
51
- `;
52
- }
53
-
54
- export const generator: GeneratorDefinition<RouteAnswers> = {
55
- meta: {
56
- name: "route",
57
- displayName: "@canonical/summon-application:route",
58
- description: "Add a route page to an existing domain",
59
- version: "0.1.0",
60
- help: `Creates a page component inside an existing domain directory.
61
-
62
- Given a path like "account/settings":
63
- - Domain = first segment ("account")
64
- - Route = last segment ("settings")
65
-
66
- Creates:
67
- - src/domains/<domain>/<RouteName>Page.tsx
68
- - Inserts the import + route entry into src/domains/<domain>/routes.ts
69
-
70
- Refuses to overwrite an existing page file.
71
-
72
- Create the domain first with: summon domain <name>
73
-
74
- Note on --undo: undo removes the route entry and import it added. It assumes the
75
- route was newly created — running --undo after an insert that was a no-op (the
76
- route key already existed) would remove a route you already had.`,
77
- examples: [
78
- "summon route account/settings",
79
- "summon route billing/invoices",
80
- "summon route --dry-run user/profile",
81
- ],
82
- },
83
-
84
- prompts,
85
-
86
- generate: (answers) => {
87
- const normalized = normalizeCommandPath(answers.routePath);
88
- const segments = normalized.split("/");
89
-
90
- if (segments.length < 2) {
91
- throw new Error(
92
- `Route path must include a domain and route name (e.g. "account/settings"), got "${normalized}"`,
93
- );
94
- }
95
-
96
- const domainName = segments[0];
97
- const routeName = segments[segments.length - 1];
98
- const pageName = `${toPascalCase(routeName)}Page`;
99
- const domainDir = path.join("src", "domains", domainName);
100
- const pageFile = path.join(domainDir, `${pageName}.tsx`);
101
- const routesFile = path.join(domainDir, "routes.ts");
102
- const url = `/${normalized}`;
103
- const routeKey = toCamelCase(routeName);
104
-
105
- const scaffold = sequence_([
106
- info(`Adding route "${routeName}" to domain "${domainName}"...`),
107
- // No mkdir: this generator targets an *existing* domain (guarded below).
108
- // mkdir's default undo is DeleteDirectory, which on `--undo` could remove
109
- // a pre-existing domain folder.
110
- writeFile(pageFile, buildPage(routeName)),
111
- // Insert the import + route entry into the domain's routes object via a
112
- // pure AST-located transform (no manual edit needed afterwards). Undo
113
- // removes exactly the lines we added, rather than restoring a snapshot.
114
- transformFile(
115
- routesFile,
116
- (source) =>
117
- insertRoute(source, {
118
- pageName,
119
- importPath: `./${pageName}.js`,
120
- routeKey,
121
- url,
122
- }),
123
- {
124
- undo: transformFile(routesFile, (source) =>
125
- removeRoute(source, { pageName, routeKey }),
126
- ),
127
- },
128
- ),
129
- info(`Route "${routeName}" wired into ${routesFile}.`),
130
- ]);
131
-
132
- // Guard before touching anything:
133
- // - the domain must exist (this generator adds to an existing domain);
134
- // - the page must NOT exist (its write's undo is a delete, so overwriting a
135
- // hand-authored page then `--undo` would destroy the original).
136
- return flatMap(exists(routesFile), (domainPresent) =>
137
- !domainPresent
138
- ? fail({
139
- code: "ROUTE_DOMAIN_MISSING",
140
- message: `Domain "${domainName}" not found (${routesFile} missing). Create it first with: summon domain ${domainName}`,
141
- })
142
- : flatMap(exists(pageFile), (pagePresent) =>
143
- pagePresent
144
- ? fail({
145
- code: "ROUTE_PAGE_EXISTS",
146
- message: `Page "${pageFile}" already exists. Choose a different route name or remove the file first.`,
147
- })
148
- : scaffold,
149
- ),
150
- );
151
- },
152
- };
153
-
154
- export default generator;
@@ -1,98 +0,0 @@
1
- import ts from "typescript";
2
- import { describe, expect, it } from "vitest";
3
- import { insertRoute, removeRoute } from "./insertRoute.js";
4
-
5
- const BASE = `import { route } from "@canonical/router-core";
6
- import MainPage from "./MainPage.js";
7
-
8
- const routes = {
9
- billing: route({
10
- url: "/billing",
11
- content: MainPage,
12
- }),
13
- } as const;
14
-
15
- export default routes;
16
- `;
17
-
18
- const INS = {
19
- pageName: "InvoicesPage",
20
- importPath: "./InvoicesPage.js",
21
- routeKey: "invoices",
22
- url: "/billing/invoices",
23
- } as const;
24
-
25
- describe("insertRoute", () => {
26
- it("adds the import and the route entry", () => {
27
- const out = insertRoute(BASE, INS);
28
- expect(out).toContain('import InvoicesPage from "./InvoicesPage.js";');
29
- expect(out).toContain("invoices: route({");
30
- expect(out).toContain('url: "/billing/invoices",');
31
- expect(out).toContain("content: InvoicesPage,");
32
- // existing entry untouched
33
- expect(out).toContain("billing: route({");
34
- });
35
-
36
- it("is idempotent — re-inserting the same route is a no-op", () => {
37
- const once = insertRoute(BASE, INS);
38
- expect(insertRoute(once, INS)).toBe(once);
39
- });
40
-
41
- it("throws when there is no routes object literal", () => {
42
- expect(() => insertRoute("export const x = 1;\n", INS)).toThrow(/routes/);
43
- });
44
-
45
- // Bug fixes from the adversarial review: the entry must be spliced using the
46
- // object literal's own AST bounds (not a brace text-scan), and a separating
47
- // comma added when the previous property lacks one — so non-canonical routes
48
- // shapes still produce parseable output.
49
- it.each([
50
- [
51
- "single-line object",
52
- `const routes = { billing: route({ url: "/billing", content: MainPage }) } as const;\n`,
53
- ],
54
- [
55
- "no trailing comma",
56
- `const routes = {\n billing: route({ url: "/billing", content: MainPage })\n} as const;\n`,
57
- ],
58
- ["empty object", "const routes = {} as const;\n"],
59
- ])("produces parseable output for a %s", (_label, src) => {
60
- const out = insertRoute(src, INS);
61
- const sf = ts.createSourceFile("r.ts", out, ts.ScriptTarget.Latest, true);
62
- // @ts-expect-error parseDiagnostics is internal but reliable for this check
63
- expect(sf.parseDiagnostics).toHaveLength(0);
64
- expect(out).toContain("invoices: route({");
65
- });
66
- });
67
-
68
- describe("removeRoute", () => {
69
- it("is the exact inverse of insertRoute (round-trip)", () => {
70
- const added = insertRoute(BASE, INS);
71
- expect(removeRoute(added, INS)).toBe(BASE);
72
- });
73
-
74
- it("is idempotent — removing an absent route is a no-op", () => {
75
- expect(removeRoute(BASE, INS)).toBe(BASE);
76
- });
77
-
78
- it("leaves other routes and imports intact", () => {
79
- const added = insertRoute(BASE, INS);
80
- const back = removeRoute(added, INS);
81
- expect(back).toContain("billing: route({");
82
- expect(back).toContain('import MainPage from "./MainPage.js";');
83
- expect(back).not.toContain("InvoicesPage");
84
- });
85
-
86
- it("does NOT delete a merged import that has named bindings", () => {
87
- // A user may have merged named bindings into the generated import. removing
88
- // the whole line would discard them, so removeRoute leaves it alone.
89
- const merged = insertRoute(BASE, INS).replace(
90
- 'import InvoicesPage from "./InvoicesPage.js";',
91
- 'import InvoicesPage, { helper } from "./InvoicesPage.js";',
92
- );
93
- const back = removeRoute(merged, INS);
94
- expect(back).toContain("{ helper }");
95
- // the route entry is still removed
96
- expect(back).not.toContain("invoices: route({");
97
- });
98
- });
@@ -1,236 +0,0 @@
1
- import ts from "typescript";
2
-
3
- /**
4
- * Peel `as const` / type assertions / parentheses off an initializer to reach
5
- * the underlying object literal (e.g. `{ ... } as const`), if any.
6
- */
7
- function unwrapObjectLiteral(
8
- expr: ts.Expression,
9
- ): ts.ObjectLiteralExpression | undefined {
10
- let node: ts.Expression = expr;
11
- while (
12
- ts.isAsExpression(node) ||
13
- ts.isParenthesizedExpression(node) ||
14
- ts.isTypeAssertionExpression(node) ||
15
- ts.isSatisfiesExpression(node)
16
- ) {
17
- node = node.expression;
18
- }
19
- return ts.isObjectLiteralExpression(node) ? node : undefined;
20
- }
21
-
22
- export interface RouteInsertion {
23
- /** Imported page component, e.g. "InvoicesPage". */
24
- readonly pageName: string;
25
- /** Import specifier, e.g. "./InvoicesPage.js". */
26
- readonly importPath: string;
27
- /** Route key in the routes object, e.g. "invoices". */
28
- readonly routeKey: string;
29
- /** Route URL, e.g. "/billing/invoices". */
30
- readonly url: string;
31
- }
32
-
33
- /**
34
- * Insert a route into a domain `routes.ts` source.
35
- *
36
- * Uses the TypeScript compiler API only to *locate* the insertion points (the
37
- * last import declaration and the `routes` object literal), then splices text
38
- * at those offsets. Locating with the AST is robust to formatting; editing by
39
- * string keeps the rest of the file byte-for-byte unchanged (no full re-print,
40
- * so it doesn't fight the formatter).
41
- *
42
- * Idempotent: if `routeKey` already exists in the routes object, the source is
43
- * returned unchanged. Throws if the `routes` object literal cannot be found.
44
- */
45
- export function insertRoute(source: string, ins: RouteInsertion): string {
46
- const sf = ts.createSourceFile(
47
- "routes.ts",
48
- source,
49
- ts.ScriptTarget.Latest,
50
- /* setParentNodes */ true,
51
- );
52
-
53
- // Locate the `routes` object literal and the last import declaration.
54
- let routesObject: ts.ObjectLiteralExpression | undefined;
55
- let lastImportEnd: number | undefined;
56
-
57
- for (const stmt of sf.statements) {
58
- if (ts.isImportDeclaration(stmt)) {
59
- lastImportEnd = stmt.end;
60
- continue;
61
- }
62
- if (ts.isVariableStatement(stmt)) {
63
- for (const decl of stmt.declarationList.declarations) {
64
- if (
65
- ts.isIdentifier(decl.name) &&
66
- decl.name.text === "routes" &&
67
- decl.initializer
68
- ) {
69
- const obj = unwrapObjectLiteral(decl.initializer);
70
- if (obj) routesObject = obj;
71
- }
72
- }
73
- }
74
- }
75
-
76
- if (!routesObject) {
77
- throw new Error(
78
- "insertRoute: could not find a `const routes = { ... }` object literal",
79
- );
80
- }
81
-
82
- // Idempotency: skip if the key is already present.
83
- const exists = routesObject.properties.some(
84
- (p) =>
85
- p.name &&
86
- (ts.isIdentifier(p.name) || ts.isStringLiteral(p.name)) &&
87
- p.name.text === ins.routeKey,
88
- );
89
- if (exists) return source;
90
-
91
- // Indentation of the existing properties (fall back to two spaces).
92
- const indent = detectIndent(source, routesObject) ?? " ";
93
-
94
- const importLine = `import ${ins.pageName} from "${ins.importPath}";\n`;
95
- const entry =
96
- `${indent}${ins.routeKey}: route({\n` +
97
- `${indent}${indent}url: "${ins.url}",\n` +
98
- `${indent}${indent}content: ${ins.pageName},\n` +
99
- `${indent}}),\n`;
100
-
101
- // Insert after the last existing property, or — for an empty object — just
102
- // inside the braces. Use AST node bounds, never a brace text-scan (which can
103
- // match a nested `route({ ... })` brace on a single-line object).
104
- const props = routesObject.properties;
105
- let out: string;
106
- if (props.length > 0) {
107
- const last = props[props.length - 1];
108
- // Find the insertion point: just after the last property, including its
109
- // trailing comma if it has one (so the existing comma stays attached to the
110
- // existing property). If there's no trailing comma, add one.
111
- let at = last.end;
112
- let prefix = ",\n";
113
- if (source[at] === ",") {
114
- at += 1; // step past the existing comma
115
- prefix = "\n";
116
- }
117
- out = `${source.slice(0, at)}${prefix}${entry.replace(/\n$/, "")}${source.slice(at)}`;
118
- } else {
119
- // Empty object: insert between the braces.
120
- const openBrace =
121
- routesObject.getStart(sf) +
122
- source.slice(routesObject.getStart(sf)).indexOf("{") +
123
- 1;
124
- out = `${source.slice(0, openBrace)}\n${entry}${source.slice(openBrace)}`;
125
- }
126
-
127
- // Insert the import after the last existing import (offsets in the original
128
- // source are still valid because the route entry was added later in the file).
129
- if (lastImportEnd !== undefined) {
130
- out =
131
- out.slice(0, lastImportEnd) +
132
- `\n${importLine.trimEnd()}` +
133
- out.slice(lastImportEnd);
134
- } else {
135
- out = importLine + out;
136
- }
137
-
138
- return out;
139
- }
140
-
141
- /**
142
- * Inverse of {@link insertRoute}: remove the route entry and its import.
143
- *
144
- * Used as the route generator's undo. Rather than restoring a stored copy of
145
- * the file, it deletes exactly the lines that {@link insertRoute} added — the
146
- * `routeKey` property in the `routes` object and the `import <pageName> ...`
147
- * line. Idempotent: returns the source unchanged if neither is present, and
148
- * leaves any other content (including manual edits) intact.
149
- */
150
- export function removeRoute(
151
- source: string,
152
- ins: Pick<RouteInsertion, "pageName" | "routeKey">,
153
- ): string {
154
- const sf = ts.createSourceFile(
155
- "routes.ts",
156
- source,
157
- ts.ScriptTarget.Latest,
158
- /* setParentNodes */ true,
159
- );
160
-
161
- let result = source;
162
-
163
- // 1. Remove the route entry (the property whose name === routeKey).
164
- for (const stmt of sf.statements) {
165
- if (!ts.isVariableStatement(stmt)) continue;
166
- for (const decl of stmt.declarationList.declarations) {
167
- if (
168
- !ts.isIdentifier(decl.name) ||
169
- decl.name.text !== "routes" ||
170
- !decl.initializer
171
- ) {
172
- continue;
173
- }
174
- const obj = unwrapObjectLiteral(decl.initializer);
175
- if (!obj) continue;
176
- const prop = obj.properties.find(
177
- (p) =>
178
- p.name &&
179
- (ts.isIdentifier(p.name) || ts.isStringLiteral(p.name)) &&
180
- p.name.text === ins.routeKey,
181
- );
182
- if (prop) {
183
- result = removeFullLines(result, prop.getStart(sf), prop.end);
184
- }
185
- }
186
- }
187
-
188
- // 2. Remove the import line for the page component.
189
- // Re-parse because offsets shifted after the entry removal.
190
- const sf2 = ts.createSourceFile(
191
- "routes.ts",
192
- result,
193
- ts.ScriptTarget.Latest,
194
- true,
195
- );
196
- for (const stmt of sf2.statements) {
197
- if (
198
- ts.isImportDeclaration(stmt) &&
199
- stmt.importClause?.name?.text === ins.pageName &&
200
- // Only remove a pure default import (`import Page from "..."`), which is
201
- // exactly what insertRoute creates. If a user merged named bindings into
202
- // it (`import Page, { x } from "..."`), leave it — removing the whole line
203
- // would discard their bindings.
204
- !stmt.importClause.namedBindings
205
- ) {
206
- result = removeFullLines(result, stmt.getStart(sf2), stmt.end);
207
- break;
208
- }
209
- }
210
-
211
- return result;
212
- }
213
-
214
- /**
215
- * Remove the whole-line span covering [start, end), including the node's
216
- * leading indentation and its trailing newline, so no blank line is left behind.
217
- */
218
- function removeFullLines(source: string, start: number, end: number): string {
219
- const lineStart = source.lastIndexOf("\n", start - 1) + 1;
220
- let lineEnd = source.indexOf("\n", end);
221
- if (lineEnd === -1) lineEnd = source.length;
222
- else lineEnd += 1; // include the newline
223
- return source.slice(0, lineStart) + source.slice(lineEnd);
224
- }
225
-
226
- /** Detect the indentation used by the first property of the object literal. */
227
- function detectIndent(
228
- source: string,
229
- obj: ts.ObjectLiteralExpression,
230
- ): string | undefined {
231
- const first = obj.properties[0];
232
- if (!first) return undefined;
233
- const lineStart = source.lastIndexOf("\n", first.getStart()) + 1;
234
- const ws = source.slice(lineStart, first.getStart());
235
- return /^\s+$/.test(ws) ? ws : undefined;
236
- }
@@ -1,48 +0,0 @@
1
- import { createRequire } from "node:module";
2
- import type { Task } from "@canonical/task";
3
- import { info } from "@canonical/task";
4
-
5
- /**
6
- * Version range for the pragma workspace packages a generated app depends on
7
- * directly — react-ds-global(-form), react-head, react-hooks, react-ssr,
8
- * router-core, router-react, styles, storybook-config, biome-config,
9
- * typescript-config-react. These share one lerna-managed release line.
10
- *
11
- * Scope notes:
12
- * - Third-party deps (react, express, vite…) keep their own ranges.
13
- * - `@canonical/design-tokens` is versioned SEPARATELY and is NOT pinned here —
14
- * it reaches the app transitively via `@canonical/styles`, which owns its range.
15
- *
16
- * A single hand-maintained constant — NOT read from a package.json at runtime,
17
- * because the generator ships as a compiled binary where such a read would
18
- * resolve to "unknown". Bump in lockstep with the lerna release.
19
- *
20
- * Open question: inject this at binary-build time once the compile pipeline
21
- * supports it, so it cannot drift from the release. See README "Open questions".
22
- */
23
- export const PRAGMA_WORKSPACE_VERSION = "^0.27.1-experimental.0";
24
-
25
- const require = createRequire(import.meta.url);
26
-
27
- function readVersion(packageName: string): string {
28
- try {
29
- const pkg = require(`${packageName}/package.json`);
30
-
31
- return pkg.version ?? "unknown";
32
- } catch {
33
- return "unknown";
34
- }
35
- }
36
-
37
- const coreVersion = readVersion("@canonical/summon-core");
38
- const appVersion = readVersion("@canonical/summon-application");
39
-
40
- /**
41
- * Print a version table for the current generator run.
42
- */
43
- export function printVersions(generatorName: string): Task<void> {
44
- return info(
45
- `@canonical/summon-core ${coreVersion}\n` +
46
- `@canonical/summon-application ${appVersion} (${generatorName})`,
47
- );
48
- }
@@ -1,100 +0,0 @@
1
- import * as path from "node:path";
2
- import type {
3
- GeneratorDefinition,
4
- PromptDefinition,
5
- } from "@canonical/summon-core";
6
- import {
7
- exists,
8
- fail,
9
- flatMap,
10
- info,
11
- mkdir,
12
- sequence_,
13
- writeFile,
14
- } from "@canonical/task";
15
- import { toKebabCase, toPascalCase } from "@canonical/utils";
16
- import { normalizeCommandPath } from "../shared/casing.js";
17
-
18
- interface WrapperAnswers {
19
- readonly wrapperName: string;
20
- }
21
-
22
- const prompts: PromptDefinition[] = [
23
- {
24
- name: "wrapperName",
25
- type: "text",
26
- message: "Wrapper name (for example settings):",
27
- default: "example",
28
- positional: true,
29
- group: "Wrapper",
30
- },
31
- ];
32
-
33
- function buildLayout(wrapperName: string): string {
34
- const layoutName = `${toPascalCase(wrapperName)}Layout`;
35
- const className = `${toKebabCase(wrapperName)}-layout`;
36
-
37
- return `import type { ReactNode, ReactElement } from "react";
38
-
39
- export default function ${layoutName}({
40
- children,
41
- }: { children: ReactNode }): ReactElement {
42
- return <div className="${className}">{children}</div>;
43
- }
44
- `;
45
- }
46
-
47
- function buildBarrel(wrapperName: string): string {
48
- const layoutName = `${toPascalCase(wrapperName)}Layout`;
49
-
50
- return `export { default } from "./${layoutName}.js";
51
- `;
52
- }
53
-
54
- export const generator: GeneratorDefinition<WrapperAnswers> = {
55
- meta: {
56
- name: "wrapper",
57
- displayName: "@canonical/summon-application:wrapper",
58
- description: "Create a layout wrapper component",
59
- version: "0.1.0",
60
- help: `Creates a layout wrapper component under src/lib/.
61
-
62
- Given a name like "settings", creates:
63
- - src/lib/SettingsLayout/SettingsLayout.tsx
64
- - src/lib/SettingsLayout/index.ts (barrel export)`,
65
- examples: [
66
- "summon wrapper settings",
67
- "summon wrapper sidebar",
68
- "summon wrapper --dry-run dashboard",
69
- ],
70
- },
71
-
72
- prompts,
73
-
74
- generate: (answers) => {
75
- const name = normalizeCommandPath(answers.wrapperName);
76
- const layoutName = `${toPascalCase(name)}Layout`;
77
- const layoutDir = path.join("src", "lib", layoutName);
78
-
79
- const scaffold = sequence_([
80
- info(`Creating wrapper "${layoutName}"...`),
81
- mkdir(layoutDir),
82
- writeFile(path.join(layoutDir, `${layoutName}.tsx`), buildLayout(name)),
83
- writeFile(path.join(layoutDir, "index.ts"), buildBarrel(name)),
84
- info(`Wrapper "${layoutName}" created at ${layoutDir}.`),
85
- ]);
86
-
87
- // Refuse to run when the layout already exists — mkdir/writeFile undos are
88
- // destructive, so overwriting then `--undo` could delete a pre-existing one.
89
- return flatMap(exists(layoutDir), (present) =>
90
- present
91
- ? fail({
92
- code: "WRAPPER_EXISTS",
93
- message: `Wrapper "${layoutDir}" already exists. Choose a different name or remove it first.`,
94
- })
95
- : scaffold,
96
- );
97
- },
98
- };
99
-
100
- export default generator;