@sealcode/sealgen 0.12.9 → 0.12.11

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.
@@ -1,4 +1,5 @@
1
- export namespace remove_named_imports {
1
+ export function removeNamedImports(content: any): any;
2
+ export namespace remove_named_imports_plugin {
2
3
  const name: string;
3
4
  function setup(build: any): void;
4
5
  }
package/build.js CHANGED
@@ -1,12 +1,13 @@
1
1
  import * as esbuild from "esbuild";
2
2
  import { default as glob } from "tiny-glob";
3
- import { remove_named_imports } from "./remove-named-imports.js";
3
+ // commented out as it seemingly works without that
4
+ // import { remove_named_imports } from "./remove-named-imports.js";
4
5
 
5
6
  const entryPoints = (await glob("./src/**/*.{js,ts,tsx}")).filter(
6
7
  (path) => !path.includes(".#")
7
8
  );
8
9
 
9
- await esbuild.build({
10
+ const args = {
10
11
  entryPoints,
11
12
  sourcemap: true,
12
13
  bundle: false,
@@ -16,4 +17,11 @@ await esbuild.build({
16
17
  target: "es2022",
17
18
  format: "esm",
18
19
  // plugins: [remove_named_imports],
19
- });
20
+ };
21
+
22
+ if (process.argv.includes("--watch")) {
23
+ const context = await esbuild.context(args);
24
+ context.watch();
25
+ } else {
26
+ esbuild.build(args);
27
+ }
@@ -4,18 +4,18 @@ import { promises as fs, existsSync } from "fs";
4
4
  import { question } from "./utils/question.js";
5
5
  import { collectionTemplate } from "./templates/collection.js";
6
6
  import { generateCollections } from "./generate-collections.js";
7
+ import { toKebabCase, toPascalCase } from "js-convert-case";
7
8
  const target_locreq = _locreq(process.cwd());
8
9
  async function addCollection() {
9
- const regex_pattern = /^([A-Z_$][a-zA-Z0-9_$]*)$/;
10
- const collection_name = await question(
11
- `What's the name of the collection class (e.g. "SecretDocuments", must start with a capital letter): `,
12
- (s) => s.length > 3 && regex_pattern.test(s)
10
+ const collection_name = toPascalCase(
11
+ await question(
12
+ "What's the name of the collection class: ",
13
+ (s) => s.length > 3
14
+ )
13
15
  );
14
- const url = await question(
15
- "Enter the url-friendly name for the collection (e.g. secret-documents): ",
16
- (s) => !s.includes("/") && !s.includes(" ")
16
+ const file_path = target_locreq.resolve(
17
+ `src/back/collections/${toKebabCase(collection_name)}.ts`
17
18
  );
18
- const file_path = target_locreq.resolve(`src/back/collections/${url}.ts`);
19
19
  if (existsSync(file_path)) {
20
20
  console.error(`ERROR: File ${file_path} already exists.`);
21
21
  return;
package/dist/add-route.js CHANGED
@@ -6,6 +6,7 @@ import { testTemplate } from "./templates/route-test.js";
6
6
  import { escape_url_params } from "./utils/escape-url-params.js";
7
7
  import prompts from "prompts";
8
8
  import { Templates } from "./templates/templates.js";
9
+ import { toKebabCase, toPascalCase } from "js-convert-case";
9
10
  async function addRoute(params, app_directory = process.cwd()) {
10
11
  const target_locreq = _locreq(app_directory);
11
12
  prompts.override(params);
@@ -14,13 +15,19 @@ async function addRoute(params, app_directory = process.cwd()) {
14
15
  type: "text",
15
16
  name: "action",
16
17
  message: `What's the name of the action (e.g. "AddUser"): `,
17
- validate: (s) => s.length > 3 ? true : "Should be at least 3 characters long"
18
+ validate: (s) => s.length > 3 ? true : "Should be at least 3 characters long",
19
+ format: function(action2) {
20
+ return toPascalCase(action2);
21
+ }
18
22
  },
19
23
  {
20
24
  type: "text",
21
25
  name: "url",
22
26
  message: "Enter a full absolute path for the new route (for example: /admin/users/:id/edit): ",
23
- validate: (s) => s.trim()[0] == "/" ? true : "Should start with a '/'"
27
+ validate: (s) => s.trim()[0] == "/" ? true : "Should start with a '/'",
28
+ initial: function(_, { action: action2 }) {
29
+ return "/" + toKebabCase(action2);
30
+ }
24
31
  },
25
32
  {
26
33
  type: "select",
@@ -56,7 +63,9 @@ async function addRoute(params, app_directory = process.cwd()) {
56
63
  }
57
64
  await fs.mkdir(resolve(file_path, "../"), { recursive: true });
58
65
  await fs.writeFile(file_path, await template(action, file_path));
59
- await fs.writeFile(test_file_path, testTemplate(action, file_path));
66
+ if (mode !== "lpr") {
67
+ await fs.writeFile(test_file_path, testTemplate(action, file_path));
68
+ }
60
69
  console.log(`${file_path} created`);
61
70
  console.log(`${test_file_path} created`);
62
71
  await generateRoutes();
package/dist/build.js CHANGED
@@ -9,8 +9,11 @@ import { generateRoutes } from "./generate-routes.js";
9
9
  import { generateComponents } from "./generate-components.js";
10
10
  import { make_notifier } from "./notifier.js";
11
11
  import getPort from "get-port";
12
- import { remove_named_imports } from "../remove-named-imports.js";
12
+ import { removeNamedImports } from "../remove-named-imports.js";
13
+ import md5 from "md5";
13
14
  import _locreq from "locreq";
15
+ import path, { basename, extname } from "path";
16
+ import { copyFile } from "fs/promises";
14
17
  const target_locreq = _locreq(process.cwd());
15
18
  async function get_notifier_port() {
16
19
  return getPort({ port: 4e3 });
@@ -25,15 +28,30 @@ async function write_notifier_config(watch, port) {
25
28
  JSON.stringify(config)
26
29
  );
27
30
  }
31
+ function addSuffix(filename, suffix) {
32
+ return filename.replace(/(\.[a-zA-Z0-9]+)?$/, suffix + "$1");
33
+ }
34
+ async function makeResourceURL(file_path) {
35
+ const hash_base = file_path + (await fs.stat(file_path)).mtimeMs;
36
+ const hash = md5(hash_base);
37
+ const public_url = "dist/" + addSuffix(basename(file_path), "-" + hash.slice(0, 8));
38
+ const public_dir = "public";
39
+ await copyFile(
40
+ file_path,
41
+ target_locreq.resolve(path.resolve(public_dir, public_url))
42
+ );
43
+ return "/" + public_url;
44
+ }
28
45
  async function build_ts() {
29
46
  await Promise.all([
30
47
  generateCollections(),
31
48
  generateRoutes(),
32
49
  generateComponents()
33
50
  ]);
34
- const entryPoints = (await glob("./src/back/**/*.{ts,tsx}")).filter(
35
- (path) => !path.includes(".#")
36
- );
51
+ const embeddable_file_extensions = ["svg", "png", "jpg", "jpeg", "webp"];
52
+ const entryPoints = (await glob(
53
+ `./src/back/**/*.{ts,tsx,${embeddable_file_extensions.join(",")}}`
54
+ )).filter((path2) => !path2.includes(".#"));
37
55
  try {
38
56
  await build({
39
57
  entryPoints,
@@ -45,7 +63,72 @@ async function build_ts() {
45
63
  platform: "node",
46
64
  target: "es2022",
47
65
  format: "esm",
48
- plugins: [remove_named_imports]
66
+ loader: Object.fromEntries(
67
+ embeddable_file_extensions.map((ext) => ["." + ext, "js"])
68
+ ),
69
+ plugins: [
70
+ {
71
+ name: "sealgen-rewrite-asset-imports",
72
+ setup(build2) {
73
+ build2.onLoad(
74
+ { filter: /\.tsx?$/ },
75
+ async (args) => {
76
+ let contents = await fs.readFile(
77
+ args.path,
78
+ "utf8"
79
+ );
80
+ for (const ext of embeddable_file_extensions) {
81
+ contents = contents.replaceAll(
82
+ new RegExp(
83
+ `^import (w+|{[^}]+}) from "([^"]+.${ext})";`,
84
+ "gm"
85
+ ),
86
+ (line) => line.replace(`.${ext}"`, '.js"')
87
+ );
88
+ }
89
+ contents = removeNamedImports(contents);
90
+ return {
91
+ contents,
92
+ loader: extname(args.path) === ".tsx" ? "tsx" : "ts"
93
+ };
94
+ }
95
+ );
96
+ }
97
+ },
98
+ {
99
+ name: "sealgen-load-assets",
100
+ setup(build2) {
101
+ build2.onLoad(
102
+ {
103
+ filter: new RegExp(
104
+ `\\.(${embeddable_file_extensions.join(
105
+ "|"
106
+ )})$`
107
+ )
108
+ },
109
+ async (args) => {
110
+ const mode = "url";
111
+ let contents = `export const url = "${await makeResourceURL(
112
+ args.path
113
+ )}";
114
+
115
+ import fs from "fs";
116
+ let content_promise = null;
117
+
118
+ export const content = function(){
119
+ if(content_promise) return content_promise;
120
+ content_promise = fs.promises.readFile("${args.path}", "utf-8");
121
+ return content_promise;
122
+ }
123
+ `;
124
+ return {
125
+ contents
126
+ };
127
+ }
128
+ );
129
+ }
130
+ }
131
+ ]
49
132
  });
50
133
  } catch (e) {
51
134
  console.error(e.message);
@@ -74,12 +157,12 @@ async function complex_build(watch) {
74
157
  const port = await get_notifier_port();
75
158
  const notifier = make_notifier(port);
76
159
  await write_notifier_config(watch, port);
77
- watcher.on("all", async (_, path) => {
160
+ watcher.on("all", async (_, path2) => {
78
161
  if (!css_build)
79
162
  return;
80
- if (path.includes(".#"))
163
+ if (path2.includes(".#"))
81
164
  return;
82
- if (path.endsWith(".css") && !path.endsWith("/includes.css")) {
165
+ if (path2.endsWith(".css") && !path2.endsWith("/includes.css")) {
83
166
  if (ongoing_css) {
84
167
  return;
85
168
  }
@@ -87,7 +170,7 @@ async function complex_build(watch) {
87
170
  await generate_css_includes();
88
171
  try {
89
172
  await css_build?.rebuild?.();
90
- console.log(`Built main.css [on ${path}]`);
173
+ console.log(`Built main.css [on ${path2}]`);
91
174
  } catch (e) {
92
175
  console.error(e.message);
93
176
  await sleep(200);
@@ -99,7 +182,7 @@ async function complex_build(watch) {
99
182
  notifier("css");
100
183
  ongoing_css = false;
101
184
  }
102
- if ((path.endsWith(".ts") || path.endsWith(".tsx")) && !path.endsWith("src/back/collections/collections.ts") && !path.endsWith("src/back/routes/routes.ts") && !path.endsWith("src/back/routes/urls.ts")) {
185
+ if ((path2.endsWith(".ts") || path2.endsWith(".tsx")) && !path2.endsWith("src/back/collections/collections.ts") && !path2.endsWith("src/back/routes/routes.ts") && !path2.endsWith("src/back/routes/urls.ts")) {
103
186
  if (ongoing_ts) {
104
187
  return;
105
188
  }
@@ -108,7 +191,7 @@ async function complex_build(watch) {
108
191
  await ongoing_ts_promise;
109
192
  notifier("ts");
110
193
  ongoing_ts_promise = null;
111
- console.log(`Finished TS build [on ${path}]`);
194
+ console.log(`Finished TS build [on ${path2}]`);
112
195
  ongoing_ts = false;
113
196
  }
114
197
  });
@@ -2,7 +2,14 @@ import { curryImportPath } from "../utils/import-path.js";
2
2
  async function formTemplate(action_name, newfilefullpath) {
3
3
  const rel = curryImportPath(newfilefullpath);
4
4
  return `import { Context } from "koa";
5
- import { Form, FormData, FormDataValue, Fields, Controls } from "@sealcode/sealgen";
5
+ import {
6
+ Form,
7
+ FormData,
8
+ FormDataValue,
9
+ Fields,
10
+ Controls,
11
+ fieldsToShape,
12
+ } from "@sealcode/sealgen";
6
13
  import html from "${rel("src/back/html.js")}";
7
14
  import { Users } from "${rel("src/back/collections/collections.js")}";
8
15
 
@@ -28,10 +35,10 @@ export default new (class ${action_name}Form extends Form<typeof fields, void> {
28
35
  ctx: Context,
29
36
  data: Record<string, FormDataValue>
30
37
  ): Promise<{ valid: boolean; error: string }> {
31
- // just an example
38
+ // just a silly example, please remove this with better logic
32
39
  const { parsed: email } = await this.fields.email.getValue(ctx, data);
33
40
  const { parsed: password } = await this.fields.password.getValue(ctx, data);
34
- if ((password || "").length > (email || "").length) {
41
+ if ((password || "").length > ((email as string) || "").length) {
35
42
  return { valid: false, error: "Password cannot be longer than email" };
36
43
  } else {
37
44
  return { valid: true, error: "" };
@@ -75,7 +75,11 @@ ${collection_fields.map((field) => {
75
75
  }
76
76
  return ` { field: "${field.name}", label: "${field.name}" }`;
77
77
  }).join(",\n")}
78
- ];
78
+ ] as {
79
+ field: string;
80
+ label: string;
81
+ format?: (value: unknown) => FlatTemplatable;
82
+ }[];
79
83
 
80
84
  export default new (class ${action_name}Page extends SealiousItemListPage<
81
85
  typeof ${uppercase_collection},
@@ -94,8 +98,8 @@ export default new (class ${action_name}Page extends SealiousItemListPage<
94
98
  }
95
99
  return <input
96
100
  type="hidden"
97
- name="\${key}"
98
- value="\${value}"
101
+ name={key}
102
+ value={value}
99
103
  />;
100
104
  })}
101
105
  {filterFields.map(({ field, render }) => {
@@ -1,3 +1,4 @@
1
+ import { toSentenceCase } from "js-convert-case";
1
2
  import { curryImportPath } from "../utils/import-path.js";
2
3
  async function LongRunningProcessTemplate(action_name, newfilefullpath) {
3
4
  const rel = curryImportPath(newfilefullpath);
@@ -20,38 +21,34 @@ export default new (class PatroniteAutoImportStatusPage extends Page {
20
21
  async render(ctx: Context) {
21
22
  const lpr_id = ctx.params.id;
22
23
  const lpr_data = LongRunningProcess.getByID(ctx.$context, lpr_id);
23
- const render_script = lpr_data.state !== "error" && lpr_data.state !== "finished";
24
- const script = /* HTML */ \`<script>
25
- setTimeout(() => {
26
- document.location = document.location;
27
- }, \${this.interval});
28
- </script>\`;
29
24
 
30
25
  return html(
31
26
  ctx,
32
- "PatroniteAutoImportStatus",
33
- <div>
34
- {lpr_data.then((lpr_data) => {
35
- return (
36
- <div>
37
- <div>status: {lpr_data.state}</div>
38
- <div style="height: 20px; width: 100%">
39
- <div
40
- style="height: 100%; background-color: green; width: {Math.round(
41
- lpr_data.progress * 100
42
- )}%"
43
- ></div>
44
- </div>
45
- <div>
46
- {lpr_data.events.map((e) => (
47
- <div>{e.message}</div>
48
- ))}
49
- </div>
50
- {render_script ? { script } : ""}
51
- </div>
52
- );
53
- })}
54
- </div>
27
+ "${toSentenceCase(action_name)}",
28
+ lpr_data.then((lpr_data) => (
29
+ <div>
30
+ <div>status: {lpr_data.state}</div>
31
+ <div style="height: 20px; width: 100%">
32
+ <div
33
+ style={\`height: 100%; background-color: green; width: \${Math.round(
34
+ lpr_data.progress * 100
35
+ )}%\`}
36
+ ></div>
37
+ </div>
38
+ <div>
39
+ {lpr_data.events.map((e) => (
40
+ /* HTML */ <div>{e.message}</div>
41
+ ))}
42
+ </div>
43
+ {lpr_data.state !== "error" && lpr_data.state !== "finished"
44
+ ? /* HTML */ \`<script>
45
+ setTimeout(() => {
46
+ document.location = document.location;
47
+ }, \${this.interval});
48
+ </script>\`
49
+ : ""}
50
+ </div>
51
+ ))
55
52
  );
56
53
  }
57
54
  })();
@@ -13,7 +13,7 @@ const fields1 = {
13
13
  password: new Fields.SimpleFormField(true),
14
14
  };
15
15
 
16
- const form1 = new (class extends Form<typeof fields1> {
16
+ const form1 = new (class extends Form<typeof fields1, unknown> {
17
17
  defaultSuccessMessage = "Form1 done!";
18
18
  controls = [
19
19
  new Controls.FormHeader("form1"),
@@ -30,7 +30,7 @@ const fields2 = {
30
30
  surname: new Fields.SimpleFormField(true),
31
31
  };
32
32
 
33
- const form2 = new (class extends Form<Record<never, unknown>> {
33
+ const form2 = new (class extends Form<typeof fields2, unknown> {
34
34
  defaultSuccessMessage = "Form2 done!";
35
35
  controls = [new Controls.FormHeader("form2"), new Controls.SimpleInput(fields2.name)];
36
36
  fields = fields2;
@@ -47,7 +47,11 @@ export default new (class extends Multiform {
47
47
  messages: FormMessage[],
48
48
  prerenderedForms?: Record<string, FlatTemplatable | undefined>
49
49
  ): Promise<FlatTemplatable> {
50
- return html(ctx, "${action_name}", await super.render(ctx, messages, prerenderedForms));
50
+ return html(
51
+ ctx,
52
+ "${action_name}",
53
+ await super.render(ctx, messages, prerenderedForms, false)
54
+ );
51
55
  }
52
56
  })();
53
57
  `;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sealcode/sealgen",
3
- "version": "0.12.9",
3
+ "version": "0.12.11",
4
4
  "description": "Module to automate adding routes and collections to a sealious application",
5
5
  "main": "dist/index.js",
6
6
  "type": "module",
@@ -24,6 +24,7 @@
24
24
  "devDependencies": {
25
25
  "@playwright/test": "^1.30.0",
26
26
  "@types/koa__router": "^12.0.4",
27
+ "@types/md5": "^2.3.5",
27
28
  "@types/node": "^20.8.4",
28
29
  "@types/prettier": "^2.7.0",
29
30
  "@types/prompts": "^2.0.14",
@@ -56,6 +57,7 @@
56
57
  "esbuild": "^0.20.0",
57
58
  "js-convert-case": "^4.2.0",
58
59
  "locreq": "^3.0.0",
60
+ "md5": "^2.3.0",
59
61
  "merge": "^2.1.1",
60
62
  "prettier": "^2.7.1",
61
63
  "prompts": "^2.4.2",
@@ -10,54 +10,57 @@ const generate_names = (function* generate_names() {
10
10
  }
11
11
  })();
12
12
 
13
- export const remove_named_imports = {
13
+ export function removeNamedImports(content) {
14
+ const named_and_default_regex =
15
+ /^import\s+((\S+),\s+)?({\s*[^}]+})\s+from\s+("[^"]+");\s*$/gm;
16
+ return content.replace(
17
+ named_and_default_regex,
18
+ (_, default_import_name, __, all_named, module_path) => {
19
+ /* eslint-disable */
20
+ const new_name = generate_names.next().value;
21
+ const result =
22
+ `import * as ${new_name} from ${module_path}${
23
+ default_import_name
24
+ ? `; const ${default_import_name.replace(
25
+ ",",
26
+ ""
27
+ )} = ${new_name}.default || ${new_name};`
28
+ : ""
29
+ };` +
30
+ all_named
31
+ .match(/[a-zA-Z_$][^,}]+/g)
32
+ .map((importname) => {
33
+ if (importname.startsWith("default as")) {
34
+ return `const ${importname.replace(
35
+ "default as ",
36
+ ""
37
+ )} = ${new_name}?.default || ${new_name};`;
38
+ }
39
+ if (importname.match(/([^{]*)\sas\s([^}]*)/)) {
40
+ // is "import {asdfas as somethong_else}
41
+ const [_, original, named] =
42
+ importname.match(/([^{]*)\sas\s([^}]*)/);
43
+ return `const ${named} = ${new_name}?.default?.${original} || ${new_name}?.${original}`;
44
+ }
45
+ return `const ${importname} = ${new_name}?.default?.${importname} || ${new_name}?.${importname};`;
46
+ })
47
+ .join("; ");
48
+ return result;
49
+ /* eslint-enable */
50
+ }
51
+ );
52
+ }
53
+
54
+ export const remove_named_imports_plugin = {
14
55
  name: "remove-named-imports", // named imports sometime cause some esm incompatibilities, like the "is a CommonJS module, which may not support all module.exports as named exports." error
15
56
  setup(build) {
16
- build.onLoad({ filter: /.*/ }, async ({ path }) => {
17
- const named_and_default_regex =
18
- /^import\s+((\S+),\s+)?({\s*[^}]+})\s+from\s+("[^"]+");\s*$/gm;
19
-
20
- const old_content = await fs.readFile(path, "utf-8");
21
- const contents = old_content.replace(
22
- named_and_default_regex,
23
- (_, default_import_name, __, all_named, module_path) => {
24
- /* eslint-disable */
25
- const new_name = generate_names.next().value;
26
- const result =
27
- `import * as ${new_name} from ${module_path}${
28
- default_import_name
29
- ? `; const ${default_import_name.replace(
30
- ",",
31
- ""
32
- )} = ${new_name}.default || ${new_name};`
33
- : ""
34
- };` +
35
- all_named
36
- .match(/[a-zA-Z_$][^,}]+/g)
37
- .map((importname) => {
38
- if (importname.startsWith("default as")) {
39
- return `const ${importname.replace(
40
- "default as ",
41
- ""
42
- )} = ${new_name}?.default || ${new_name};`;
43
- }
44
- if (importname.match(/([^{]*)\sas\s([^}]*)/)) {
45
- // is "import {asdfas as somethong_else}
46
- const [_, original, named] =
47
- importname.match(
48
- /([^{]*)\sas\s([^}]*)/
49
- );
50
- return `const ${named} = ${new_name}?.default.${original} || ${new_name}?.${original}`;
51
- }
52
- return `const ${importname} = ${new_name}?.default?.${importname} || ${new_name}?.${importname};`;
53
- })
54
- .join("; ");
55
- return result;
56
- /* eslint-enable */
57
- }
58
- );
57
+ build.onLoad({ filter: /\.[t]sx?$/ }, async ({ path }) => {
58
+ const content = await fs.readFile(path, "utf-8");
59
+ const contents = removeNamedImports(content);
59
60
  return {
60
- contents,
61
+ pluginData: {
62
+ contents,
63
+ },
61
64
  loader: extname(path) === ".tsx" ? "tsx" : "ts",
62
65
  };
63
66
  });
@@ -4,19 +4,20 @@ import { promises as fs, existsSync } from "fs";
4
4
  import { question } from "./utils/question.js";
5
5
  import { collectionTemplate } from "./templates/collection.js";
6
6
  import { generateCollections } from "./generate-collections.js";
7
+ import { toKebabCase, toPascalCase } from "js-convert-case";
7
8
  const target_locreq = _locreq(process.cwd());
8
9
 
9
10
  export async function addCollection(): Promise<void> {
10
- const regex_pattern = /^([A-Z_$][a-zA-Z0-9_$]*)$/;
11
- const collection_name = await question(
12
- 'What\'s the name of the collection class (e.g. "SecretDocuments", must start with a capital letter): ',
13
- (s: string) => s.length > 3 && regex_pattern.test(s)
11
+ const collection_name = toPascalCase(
12
+ await question(
13
+ "What's the name of the collection class: ",
14
+ (s: string) => s.length > 3
15
+ )
14
16
  );
15
- const url = await question(
16
- "Enter the url-friendly name for the collection (e.g. secret-documents): ",
17
- (s: string) => !s.includes("/") && !s.includes(" ")
17
+
18
+ const file_path = target_locreq.resolve(
19
+ `src/back/collections/${toKebabCase(collection_name)}.ts`
18
20
  );
19
- const file_path = target_locreq.resolve(`src/back/collections/${url}.ts`);
20
21
 
21
22
  if (existsSync(file_path)) {
22
23
  // eslint-disable-next-line no-console
package/src/add-route.ts CHANGED
@@ -6,6 +6,7 @@ import { testTemplate } from "./templates/route-test.js";
6
6
  import { escape_url_params } from "./utils/escape-url-params.js";
7
7
  import prompts from "prompts";
8
8
  import { Templates } from "./templates/templates.js";
9
+ import { toKebabCase, toPascalCase } from "js-convert-case";
9
10
 
10
11
  export async function addRoute(
11
12
  params: Partial<{ [key in "action" | "url" | "mode"]: string }>,
@@ -20,6 +21,9 @@ export async function addRoute(
20
21
  message: 'What\'s the name of the action (e.g. "AddUser"): ',
21
22
  validate: (s: string) =>
22
23
  s.length > 3 ? true : "Should be at least 3 characters long",
24
+ format: function (action) {
25
+ return toPascalCase(action);
26
+ },
23
27
  },
24
28
  {
25
29
  type: "text",
@@ -28,6 +32,9 @@ export async function addRoute(
28
32
  "Enter a full absolute path for the new route (for example: /admin/users/:id/edit): ",
29
33
  validate: (s: string) =>
30
34
  s.trim()[0] == "/" ? true : "Should start with a '/'",
35
+ initial: function (_, { action }) {
36
+ return "/" + toKebabCase(action);
37
+ },
31
38
  },
32
39
  {
33
40
  type: "select",
@@ -70,7 +77,9 @@ export async function addRoute(
70
77
  }
71
78
  await fs.mkdir(resolve(file_path, "../"), { recursive: true });
72
79
  await fs.writeFile(file_path, await template(action, file_path));
73
- await fs.writeFile(test_file_path, testTemplate(action, file_path));
80
+ if (mode !== "lpr") {
81
+ await fs.writeFile(test_file_path, testTemplate(action, file_path));
82
+ }
74
83
  // eslint-disable-next-line no-console
75
84
  console.log(`${file_path} created`);
76
85
  // eslint-disable-next-line no-console
package/src/build.ts CHANGED
@@ -9,9 +9,12 @@ import { generateRoutes } from "./generate-routes.js";
9
9
  import { generateComponents } from "./generate-components.js";
10
10
  import { make_notifier } from "./notifier.js";
11
11
  import getPort from "get-port";
12
- import { remove_named_imports } from "../remove-named-imports.js";
12
+ import { removeNamedImports } from "../remove-named-imports.js";
13
+ import md5 from "md5";
13
14
 
14
15
  import _locreq from "locreq";
16
+ import path, { basename, extname } from "path";
17
+ import { copyFile, writeFile } from "fs/promises";
15
18
  const target_locreq = _locreq(process.cwd());
16
19
 
17
20
  async function get_notifier_port() {
@@ -29,15 +32,35 @@ async function write_notifier_config(watch: boolean, port?: number) {
29
32
  );
30
33
  }
31
34
 
35
+ function addSuffix(filename: string, suffix: string) {
36
+ return filename.replace(/(\.[a-zA-Z0-9]+)?$/, suffix + "$1");
37
+ }
38
+
39
+ async function makeResourceURL(file_path: string) {
40
+ const hash_base = file_path + (await fs.stat(file_path)).mtimeMs;
41
+ const hash = md5(hash_base);
42
+ const public_url =
43
+ "dist/" + addSuffix(basename(file_path), "-" + hash.slice(0, 8));
44
+ const public_dir = "public";
45
+ await copyFile(
46
+ file_path,
47
+ target_locreq.resolve(path.resolve(public_dir, public_url))
48
+ );
49
+ return "/" + public_url;
50
+ }
51
+
32
52
  async function build_ts() {
33
53
  await Promise.all([
34
54
  generateCollections(),
35
55
  generateRoutes(),
36
56
  generateComponents(),
37
57
  ]);
38
- const entryPoints = (await glob("./src/back/**/*.{ts,tsx}")).filter(
39
- (path) => !path.includes(".#")
40
- );
58
+ const embeddable_file_extensions = ["svg", "png", "jpg", "jpeg", "webp"];
59
+ const entryPoints = (
60
+ await glob(
61
+ `./src/back/**/*.{ts,tsx,${embeddable_file_extensions.join(",")}}`
62
+ )
63
+ ).filter((path) => !path.includes(".#"));
41
64
  try {
42
65
  await build({
43
66
  entryPoints,
@@ -49,7 +72,78 @@ async function build_ts() {
49
72
  platform: "node",
50
73
  target: "es2022",
51
74
  format: "esm",
52
- plugins: [remove_named_imports],
75
+ loader: Object.fromEntries(
76
+ embeddable_file_extensions.map((ext) => ["." + ext, "js"])
77
+ ),
78
+ plugins: [
79
+ {
80
+ name: "sealgen-rewrite-asset-imports",
81
+ setup(build) {
82
+ build.onLoad(
83
+ { filter: /\.tsx?$/ },
84
+ async (args: any) => {
85
+ let contents = await fs.readFile(
86
+ args.path,
87
+ "utf8"
88
+ );
89
+ for (const ext of embeddable_file_extensions) {
90
+ contents = contents.replaceAll(
91
+ new RegExp(
92
+ `^import (\w+|{[^}]+}) from "([^"]+.${ext})";`,
93
+ "gm"
94
+ ),
95
+ (line) =>
96
+ line.replace(`.${ext}"`, '.js"')
97
+ );
98
+ }
99
+
100
+ contents = removeNamedImports(contents);
101
+
102
+ return {
103
+ contents,
104
+ loader:
105
+ extname(args.path) === ".tsx"
106
+ ? "tsx"
107
+ : "ts",
108
+ };
109
+ }
110
+ );
111
+ },
112
+ },
113
+ {
114
+ name: "sealgen-load-assets",
115
+ setup(build) {
116
+ build.onLoad(
117
+ {
118
+ filter: new RegExp(
119
+ `\\.(${embeddable_file_extensions.join(
120
+ "|"
121
+ )})$`
122
+ ),
123
+ },
124
+ async (args: any) => {
125
+ const mode = "url";
126
+ let contents = `export const url = "${await makeResourceURL(
127
+ args.path
128
+ )}";
129
+
130
+ import fs from "fs";
131
+ let content_promise = null;
132
+
133
+ export const content = function(){
134
+ if(content_promise) return content_promise;
135
+ content_promise = fs.promises.readFile("${args.path}", "utf-8");
136
+ return content_promise;
137
+ }
138
+ `;
139
+ return {
140
+ contents,
141
+ };
142
+ }
143
+ );
144
+ },
145
+ },
146
+ ],
53
147
  });
54
148
  } catch (e) {
55
149
  // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
@@ -6,7 +6,14 @@ export async function formTemplate(
6
6
  ): Promise<string> {
7
7
  const rel = curryImportPath(newfilefullpath);
8
8
  return `import { Context } from "koa";
9
- import { Form, FormData, FormDataValue, Fields, Controls } from "@sealcode/sealgen";
9
+ import {
10
+ Form,
11
+ FormData,
12
+ FormDataValue,
13
+ Fields,
14
+ Controls,
15
+ fieldsToShape,
16
+ } from "@sealcode/sealgen";
10
17
  import html from "${rel("src/back/html.js")}";
11
18
  import { Users } from "${rel("src/back/collections/collections.js")}";
12
19
 
@@ -32,10 +39,10 @@ export default new (class ${action_name}Form extends Form<typeof fields, void> {
32
39
  ctx: Context,
33
40
  data: Record<string, FormDataValue>
34
41
  ): Promise<{ valid: boolean; error: string }> {
35
- // just an example
42
+ // just a silly example, please remove this with better logic
36
43
  const { parsed: email } = await this.fields.email.getValue(ctx, data);
37
44
  const { parsed: password } = await this.fields.password.getValue(ctx, data);
38
- if ((password || "").length > (email || "").length) {
45
+ if ((password || "").length > ((email as string) || "").length) {
39
46
  return { valid: false, error: "Password cannot be longer than email" };
40
47
  } else {
41
48
  return { valid: true, error: "" };
@@ -90,7 +90,11 @@ ${collection_fields
90
90
  return ` { field: "${field.name}", label: "${field.name}" }`;
91
91
  })
92
92
  .join(",\n")}
93
- ];
93
+ ] as {
94
+ field: string;
95
+ label: string;
96
+ format?: (value: unknown) => FlatTemplatable;
97
+ }[];
94
98
 
95
99
  export default new (class ${action_name}Page extends SealiousItemListPage<
96
100
  typeof ${uppercase_collection},
@@ -109,8 +113,8 @@ export default new (class ${action_name}Page extends SealiousItemListPage<
109
113
  }
110
114
  return <input
111
115
  type="hidden"
112
- name="\${key}"
113
- value="\${value}"
116
+ name={key}
117
+ value={value}
114
118
  />;
115
119
  })}
116
120
  {filterFields.map(({ field, render }) => {
@@ -1,3 +1,4 @@
1
+ import { toSentenceCase } from "js-convert-case";
1
2
  import { curryImportPath } from "../utils/import-path.js";
2
3
 
3
4
  export async function LongRunningProcessTemplate(
@@ -24,38 +25,34 @@ export default new (class PatroniteAutoImportStatusPage extends Page {
24
25
  async render(ctx: Context) {
25
26
  const lpr_id = ctx.params.id;
26
27
  const lpr_data = LongRunningProcess.getByID(ctx.$context, lpr_id);
27
- const render_script = lpr_data.state !== "error" && lpr_data.state !== "finished";
28
- const script = /* HTML */ \`<script>
29
- setTimeout(() => {
30
- document.location = document.location;
31
- }, \${this.interval});
32
- </script>\`;
33
28
 
34
29
  return html(
35
30
  ctx,
36
- "PatroniteAutoImportStatus",
37
- <div>
38
- {lpr_data.then((lpr_data) => {
39
- return (
40
- <div>
41
- <div>status: {lpr_data.state}</div>
42
- <div style="height: 20px; width: 100%">
43
- <div
44
- style="height: 100%; background-color: green; width: {Math.round(
45
- lpr_data.progress * 100
46
- )}%"
47
- ></div>
48
- </div>
49
- <div>
50
- {lpr_data.events.map((e) => (
51
- <div>{e.message}</div>
52
- ))}
53
- </div>
54
- {render_script ? { script } : ""}
55
- </div>
56
- );
57
- })}
58
- </div>
31
+ "${toSentenceCase(action_name)}",
32
+ lpr_data.then((lpr_data) => (
33
+ <div>
34
+ <div>status: {lpr_data.state}</div>
35
+ <div style="height: 20px; width: 100%">
36
+ <div
37
+ style={\`height: 100%; background-color: green; width: \${Math.round(
38
+ lpr_data.progress * 100
39
+ )}%\`}
40
+ ></div>
41
+ </div>
42
+ <div>
43
+ {lpr_data.events.map((e) => (
44
+ /* HTML */ <div>{e.message}</div>
45
+ ))}
46
+ </div>
47
+ {lpr_data.state !== "error" && lpr_data.state !== "finished"
48
+ ? /* HTML */ \`<script>
49
+ setTimeout(() => {
50
+ document.location = document.location;
51
+ }, \${this.interval});
52
+ </script>\`
53
+ : ""}
54
+ </div>
55
+ ))
59
56
  );
60
57
  }
61
58
  })();
@@ -17,7 +17,7 @@ const fields1 = {
17
17
  password: new Fields.SimpleFormField(true),
18
18
  };
19
19
 
20
- const form1 = new (class extends Form<typeof fields1> {
20
+ const form1 = new (class extends Form<typeof fields1, unknown> {
21
21
  defaultSuccessMessage = "Form1 done!";
22
22
  controls = [
23
23
  new Controls.FormHeader("form1"),
@@ -34,7 +34,7 @@ const fields2 = {
34
34
  surname: new Fields.SimpleFormField(true),
35
35
  };
36
36
 
37
- const form2 = new (class extends Form<Record<never, unknown>> {
37
+ const form2 = new (class extends Form<typeof fields2, unknown> {
38
38
  defaultSuccessMessage = "Form2 done!";
39
39
  controls = [new Controls.FormHeader("form2"), new Controls.SimpleInput(fields2.name)];
40
40
  fields = fields2;
@@ -51,7 +51,11 @@ export default new (class extends Multiform {
51
51
  messages: FormMessage[],
52
52
  prerenderedForms?: Record<string, FlatTemplatable | undefined>
53
53
  ): Promise<FlatTemplatable> {
54
- return html(ctx, "${action_name}", await super.render(ctx, messages, prerenderedForms));
54
+ return html(
55
+ ctx,
56
+ "${action_name}",
57
+ await super.render(ctx, messages, prerenderedForms, false)
58
+ );
55
59
  }
56
60
  })();
57
61
  `;