@stacksjs/actions 0.70.258 → 0.70.259

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 (140) hide show
  1. package/dist/action.js +1 -80
  2. package/dist/actions.js +1 -2
  3. package/dist/add.js +1 -20
  4. package/dist/ai/request-model-access.js +1 -10
  5. package/dist/auth/client.js +2 -44
  6. package/dist/auth/prune.js +1 -35
  7. package/dist/auth/setup.js +33 -153
  8. package/dist/auth/token.js +1 -10
  9. package/dist/blog-admin.js +3 -151
  10. package/dist/blog.js +33 -271
  11. package/dist/build/cli.js +1 -6
  12. package/dist/build/component-library.js +1 -36
  13. package/dist/build/component-libs.js +1 -2
  14. package/dist/build/core.js +1 -55
  15. package/dist/build/desktop.js +4 -61
  16. package/dist/build/dmg.js +4 -68
  17. package/dist/build/docs.js +1 -5
  18. package/dist/build/frontend-static.js +6 -122
  19. package/dist/build/server.js +1 -6
  20. package/dist/build/stacks.js +1 -8
  21. package/dist/build/views.js +1 -16
  22. package/dist/build-web-component-lib.js +1 -2
  23. package/dist/build.js +1 -57
  24. package/dist/bump.js +9 -210
  25. package/dist/changelog.js +1 -27
  26. package/dist/check/ports.js +1 -16
  27. package/dist/clean.js +1 -4
  28. package/dist/commit.js +1 -12
  29. package/dist/copy-types.js +1 -9
  30. package/dist/database/seed.js +1 -26
  31. package/dist/deploy/create-receipt-rule.js +1 -36
  32. package/dist/deploy/index.js +29 -1306
  33. package/dist/dev/api.js +3 -94
  34. package/dist/dev/components.js +1 -7
  35. package/dist/dev/csrf.js +1 -28
  36. package/dist/dev/dashboard-request-routing.js +1 -10
  37. package/dist/dev/dashboard-utils.js +1 -380
  38. package/dist/dev/dashboard.js +7 -422
  39. package/dist/dev/desktop.js +1 -1
  40. package/dist/dev/docs.js +1 -24
  41. package/dist/dev/exit-with-parent.d.ts +6 -0
  42. package/dist/dev/exit-with-parent.js +1 -0
  43. package/dist/dev/index.js +1 -29
  44. package/dist/dev/migrate-watcher.js +1 -74
  45. package/dist/dev/system-tray.js +2 -172
  46. package/dist/dev/views.js +1 -169
  47. package/dist/discover-packages.js +1 -32
  48. package/dist/domains/add.js +1 -61
  49. package/dist/domains/purchase.js +1 -66
  50. package/dist/domains/remove.js +1 -24
  51. package/dist/examples.js +1 -34
  52. package/dist/find-projects.js +1 -16
  53. package/dist/fresh.js +1 -17
  54. package/dist/generate/action-types.js +3 -9
  55. package/dist/generate/component-meta.js +1 -9
  56. package/dist/generate/custom-cli-file.js +2 -20
  57. package/dist/generate/env-files.js +5 -46
  58. package/dist/generate/ide-helpers.js +1 -8
  59. package/dist/generate/images.js +1 -26
  60. package/dist/generate/index.js +1 -166
  61. package/dist/generate/lib-entries.js +1 -16
  62. package/dist/generate/pantry-file.js +1 -46
  63. package/dist/generate/symlink-core.js +1 -2
  64. package/dist/generate/types.js +1 -3
  65. package/dist/generate/vschema.js +2 -47
  66. package/dist/generate/vscode-custom-data.js +1 -9
  67. package/dist/helpers/api-host.js +1 -7
  68. package/dist/helpers/component-meta.js +5 -295
  69. package/dist/helpers/index.js +1 -1
  70. package/dist/helpers/lib-entries.js +3 -73
  71. package/dist/helpers/package-json.js +2 -34
  72. package/dist/helpers/utils.js +1 -130
  73. package/dist/helpers/vscode-custom-data.js +3 -57
  74. package/dist/index.js +1 -51
  75. package/dist/key-generate.js +1 -24
  76. package/dist/lint/fix.js +1 -4
  77. package/dist/lint/index.js +1 -4
  78. package/dist/lint/lint.js +1 -34
  79. package/dist/lint/stx-gate.js +3 -175
  80. package/dist/make-command.js +4 -55
  81. package/dist/make-job.js +3 -29
  82. package/dist/make-policy.js +4 -53
  83. package/dist/make-resource.js +3 -33
  84. package/dist/make.js +7 -323
  85. package/dist/migrate/database.js +1 -16
  86. package/dist/migrate/fresh.js +1 -36
  87. package/dist/prepublish.js +1 -16
  88. package/dist/queue/clear.js +1 -42
  89. package/dist/queue/dlq-purge.js +1 -28
  90. package/dist/queue/dlq-retry.js +1 -35
  91. package/dist/queue/dlq.js +4 -55
  92. package/dist/queue/failed.js +4 -69
  93. package/dist/queue/flush.js +2 -49
  94. package/dist/queue/inspect.js +7 -154
  95. package/dist/queue/list.js +4 -69
  96. package/dist/queue/monitor.js +5 -94
  97. package/dist/queue/pause.js +1 -28
  98. package/dist/queue/quarantine.js +2 -42
  99. package/dist/queue/resume.js +1 -27
  100. package/dist/queue/retry.js +1 -41
  101. package/dist/queue/schedule-list.js +4 -33
  102. package/dist/queue/schedule.js +1 -12
  103. package/dist/queue/status.js +4 -68
  104. package/dist/queue/table.js +1 -10
  105. package/dist/queue/unquarantine.js +1 -27
  106. package/dist/queue/work.js +1 -57
  107. package/dist/release-preflight.js +3 -61
  108. package/dist/release.js +1 -29
  109. package/dist/route/list.js +2 -78
  110. package/dist/run-action.js +1 -1
  111. package/dist/saas/setup.js +1 -9
  112. package/dist/scaffold-crud.js +12 -137
  113. package/dist/schedule/run.js +1 -7
  114. package/dist/search/flush.js +1 -10
  115. package/dist/search/import.js +1 -10
  116. package/dist/search/settings-list.js +1 -10
  117. package/dist/search/settings.js +1 -9
  118. package/dist/serve/api.js +1 -37
  119. package/dist/setup/index.js +1 -1
  120. package/dist/setup/ssl.js +2 -268
  121. package/dist/stacks.js +1 -316
  122. package/dist/templates.js +20 -40
  123. package/dist/test/feature.js +1 -2
  124. package/dist/test/index.js +1 -2
  125. package/dist/test/runner.js +1 -38
  126. package/dist/test/runner.test.js +1 -29
  127. package/dist/test/ui.js +1 -2
  128. package/dist/test/unit.js +1 -2
  129. package/dist/typecheck.js +1 -4
  130. package/dist/types.js +1 -16
  131. package/dist/upgrade/binary.js +1 -29
  132. package/dist/upgrade/framework-hooks.js +1 -40
  133. package/dist/upgrade/framework-utils.js +2 -259
  134. package/dist/upgrade/framework.js +11 -484
  135. package/dist/upgrade/index.js +1 -17
  136. package/dist/upgrade/package-project.js +1 -150
  137. package/dist/upgrade/packages.js +17 -243
  138. package/dist/upgrade/shell.js +3 -40
  139. package/dist/upgrade.js +1 -38
  140. package/package.json +18 -18
package/dist/index.js CHANGED
@@ -1,51 +1 @@
1
- export * from "./action";
2
- export { add as runAdd } from "./add";
3
- export {
4
- BlogAdminError,
5
- deleteBlogPost,
6
- getBlogPost,
7
- listBlogPosts,
8
- saveBlogPost,
9
- slugify as blogSlugify
10
- } from "./blog-admin";
11
- export { commit as runCommit } from "./commit";
12
- export * from "./dev";
13
- export * from "./generate";
14
- export * from "./helpers";
15
- export { formatProject, lintFix, lintProject } from "./lint/lint";
16
- export { DEFAULT_STX_LINT_CONFIG, loadStxLintConfig, runStxLint } from "./lint/stx-gate";
17
- export * from "./setup";
18
- export {
19
- createComponent,
20
- createDatabase,
21
- createFactory,
22
- createFunction,
23
- createLanguage,
24
- createMiddleware,
25
- createMigration,
26
- createModel,
27
- createMail,
28
- createNotification,
29
- createPage,
30
- isDryRunActive,
31
- makeAction,
32
- makeCertificate,
33
- makeComponent,
34
- makeDatabase,
35
- makeFunction,
36
- makeLanguage,
37
- makeMail,
38
- makeNotification,
39
- makePage,
40
- makeQueueTable,
41
- makeStack,
42
- make as runMake,
43
- setDryRun
44
- } from "./make";
45
- export { discoverPackages } from "./discover-packages";
46
- export { parseFields, scaffoldCrud } from "./scaffold-crud";
47
- export { installStack, uninstallStack, listStacks } from "./stacks";
48
- export { makeJob } from "./make-job";
49
- export { makeCommand } from "./make-command";
50
- export { makePolicy } from "./make-policy";
51
- export { makeResource } from "./make-resource";
1
+ export*from"./action";export{add as runAdd}from"./add";export{BlogAdminError,deleteBlogPost,getBlogPost,listBlogPosts,saveBlogPost,slugify as blogSlugify}from"./blog-admin";export{commit as runCommit}from"./commit";export*from"./dev";export*from"./generate";export*from"./helpers";export{formatProject,lintFix,lintProject}from"./lint/lint";export{DEFAULT_STX_LINT_CONFIG,loadStxLintConfig,runStxLint}from"./lint/stx-gate";export*from"./setup";export{createComponent,createDatabase,createFactory,createFunction,createLanguage,createMiddleware,createMigration,createModel,createMail,createNotification,createPage,isDryRunActive,makeAction,makeCertificate,makeComponent,makeDatabase,makeFunction,makeLanguage,makeMail,makeNotification,makePage,makeQueueTable,makeStack,make as runMake,setDryRun}from"./make";export{discoverPackages}from"./discover-packages";export{parseFields,scaffoldCrud}from"./scaffold-crud";export{installStack,uninstallStack,listStacks}from"./stacks";export{makeJob}from"./make-job";export{makeCommand}from"./make-command";export{makePolicy}from"./make-policy";export{makeResource}from"./make-resource";
@@ -1,24 +1 @@
1
- import { readFileSync } from "node:fs";
2
- import { runCommand } from "@stacksjs/cli";
3
- import { generateKeypair } from "@stacksjs/env";
4
- import { projectPath } from "@stacksjs/path";
5
- import { generateAppKey } from "@stacksjs/security";
6
- import { existsSync } from "@stacksjs/storage";
7
- import { setEnvValue } from "@stacksjs/utils";
8
- if (!existsSync(".env"))
9
- await runCommand("cp .env.example .env", { cwd: projectPath() });
10
- await setEnvValue("APP_KEY", generateAppKey());
11
- const envText = (() => {
12
- try {
13
- return readFileSync(projectPath(".env"), "utf-8");
14
- } catch {
15
- return "";
16
- }
17
- })(), hasPublic = /^DOTENV_PUBLIC_KEY=.+$/m.test(envText), hasPrivate = /^DOTENV_PRIVATE_KEY=.+$/m.test(envText);
18
- if (!hasPublic || !hasPrivate) {
19
- const { publicKey, privateKey } = generateKeypair();
20
- if (!hasPublic)
21
- await setEnvValue("DOTENV_PUBLIC_KEY", publicKey);
22
- if (!hasPrivate)
23
- await setEnvValue("DOTENV_PRIVATE_KEY", privateKey);
24
- }
1
+ import{readFileSync}from"node:fs";import{runCommand}from"@stacksjs/cli";import{generateKeypair}from"@stacksjs/env";import{projectPath}from"@stacksjs/path";import{generateAppKey}from"@stacksjs/security";import{existsSync}from"@stacksjs/storage";import{setEnvValue}from"@stacksjs/utils";if(!existsSync(".env"))await runCommand("cp .env.example .env",{cwd:projectPath()});await setEnvValue("APP_KEY",generateAppKey());const envText=(()=>{try{return readFileSync(projectPath(".env"),"utf-8")}catch{return""}})(),hasPublic=/^DOTENV_PUBLIC_KEY=.+$/m.test(envText),hasPrivate=/^DOTENV_PRIVATE_KEY=.+$/m.test(envText);if(!hasPublic||!hasPrivate){const{publicKey,privateKey}=generateKeypair();if(!hasPublic)await setEnvValue("DOTENV_PUBLIC_KEY",publicKey);if(!hasPrivate)await setEnvValue("DOTENV_PRIVATE_KEY",privateKey)}
package/dist/lint/fix.js CHANGED
@@ -1,4 +1 @@
1
- import process from "node:process";
2
- import { lintFix } from "./lint";
3
- const { ok } = await lintFix();
4
- process.exit(ok ? 0 : 1);
1
+ import process from"node:process";import{lintFix}from"./lint";const{ok}=await lintFix();process.exit(ok?0:1);
@@ -1,4 +1 @@
1
- import process from "node:process";
2
- import { lintProject } from "./lint";
3
- const { ok } = await lintProject();
4
- process.exit(ok ? 0 : 1);
1
+ import process from"node:process";import{lintProject}from"./lint";const{ok}=await lintProject();process.exit(ok?0:1);
package/dist/lint/lint.js CHANGED
@@ -1,34 +1 @@
1
- import process from "node:process";
2
- import { log } from "@stacksjs/cli";
3
- import { execSync } from "node:child_process";
4
- import { runFormat, runLint } from "pickier";
5
- const lintableFile = /\.(?:ts|js|json|md|yaml|yml)$/i, ignoredPath = /(?:^|\/)(?:node_modules|dist|pantry|storage\/framework\/cache|\.git|\.stx|\.stx-serve)(?:\/|$)/;
6
- function trackedFiles(cwd) {
7
- try {
8
- return execSync("git ls-files -z", { cwd, encoding: "utf8" }).split("\x00").filter((file) => lintableFile.test(file) && !ignoredPath.test(file));
9
- } catch {
10
- return [];
11
- }
12
- }
13
- export async function lintProject(options = {}) {
14
- const cwd = options.cwd ?? process.cwd();
15
- log.info(options.fix ? "Ensuring Code Style..." : "Checking Code Style...");
16
- const files = trackedFiles(cwd);
17
- if (!files.length) {
18
- log.success("Linted");
19
- return { ok: !0 };
20
- }
21
- const ok = await runLint(files, { maxWarnings: 9999, fix: options.fix }) === 0;
22
- if (ok)
23
- log.success("Linted");
24
- return { ok };
25
- }
26
- export function lintFix(options = {}) {
27
- return lintProject({ ...options, fix: !0 });
28
- }
29
- export async function formatProject(options = {}) {
30
- const cwd = options.cwd ?? process.cwd(), files = trackedFiles(cwd);
31
- if (!files.length)
32
- return { ok: !0 };
33
- return { ok: await runFormat(files, { write: options.write, check: options.check }) === 0 };
34
- }
1
+ import process from"node:process";import{log}from"@stacksjs/cli";import{execSync}from"node:child_process";import{runFormat,runLint}from"pickier";const lintableFile=/\.(?:ts|js|json|md|yaml|yml)$/i,ignoredPath=/(?:^|\/)(?:node_modules|dist|pantry|storage\/framework\/cache|\.git|\.stx|\.stx-serve)(?:\/|$)/;function trackedFiles(cwd){try{return execSync("git ls-files -z",{cwd,encoding:"utf8"}).split("\x00").filter((file)=>lintableFile.test(file)&&!ignoredPath.test(file))}catch{return[]}}export async function lintProject(options={}){const cwd=options.cwd??process.cwd();log.info(options.fix?"Ensuring Code Style...":"Checking Code Style...");const files=trackedFiles(cwd);if(!files.length){log.success("Linted");return{ok:!0}}const ok=await runLint(files,{maxWarnings:9999,fix:options.fix})===0;if(ok)log.success("Linted");return{ok}}export function lintFix(options={}){return lintProject({...options,fix:!0})}export async function formatProject(options={}){const cwd=options.cwd??process.cwd(),files=trackedFiles(cwd);if(!files.length)return{ok:!0};return{ok:await runFormat(files,{write:options.write,check:options.check})===0}}
@@ -1,175 +1,3 @@
1
- import { existsSync } from "node:fs";
2
- import { join } from "node:path";
3
- import process from "node:process";
4
- import { Glob } from "bun";
5
- export const DEFAULT_STX_LINT_CONFIG = {
6
- stxGlob: "resources/**/*.stx",
7
- distGlob: "dist/**/*.html",
8
- baselines: {},
9
- doctypeExempt: [],
10
- styleExempt: ["resources/emails/"],
11
- staleRules: {}
12
- };
13
- const REQUIRED_STX_CONFIG_KEYS = [
14
- ["strict", "DOM guard (ch. 12.1) - without it script-validation discards every finding"],
15
- ["root", "pins project topology; absent, resolveStxRoot sniffs it and double-prefixes dirs"],
16
- ["pagesDir", 'must accompany root - resolveStxRoot falls back to a non-existent "pages"']
17
- ];
18
- export async function loadStxLintConfig(root) {
19
- const found = ["config/lint.ts", "config/lint.js"].find((c) => existsSync(join(root, c)));
20
- if (!found)
21
- return { ...DEFAULT_STX_LINT_CONFIG };
22
- try {
23
- const stx = (await import(join(root, found))).default?.stx ?? {};
24
- return {
25
- ...DEFAULT_STX_LINT_CONFIG,
26
- ...stx,
27
- baselines: { ...stx.baselines },
28
- styleExempt: stx.styleExempt ?? DEFAULT_STX_LINT_CONFIG.styleExempt,
29
- doctypeExempt: stx.doctypeExempt ?? [],
30
- staleRules: stx.staleRules ?? {}
31
- };
32
- } catch (error) {
33
- throw Error(`Could not read ${found}: ${error.message}`);
34
- }
35
- }
36
- async function scanGlob(pattern, root) {
37
- const out = [];
38
- try {
39
- for await (const f of new Glob(pattern).scan(root))
40
- out.push(f);
41
- } catch {}
42
- return out.sort();
43
- }
44
- const ROUTED_ANCHOR = /\bdata-stx-link\b|\bdata-no-router\b/;
45
- async function grepLines(re, files, root, ignore) {
46
- const hits = [];
47
- for (const f of files) {
48
- let src = "";
49
- try {
50
- src = await Bun.file(join(root, f)).text();
51
- } catch {
52
- continue;
53
- }
54
- src.split(`
55
- `).forEach((line, i) => {
56
- re.lastIndex = 0;
57
- if (!re.test(line))
58
- return;
59
- if (ignore) {
60
- ignore.lastIndex = 0;
61
- if (ignore.test(line))
62
- return;
63
- }
64
- hits.push(`${f}:${i + 1} ${line.trim().slice(0, 90)}`);
65
- });
66
- }
67
- return hits;
68
- }
69
- async function scanSources(files, root, config) {
70
- const { lintStxStrict } = await import("@stacksjs/stx"), { PROHIBITED_DOM_PATTERNS } = await import("@stacksjs/stx/script-validation"), { scanScriptTags } = await import("@stacksjs/stx/signal-processing"), domPatterns = PROHIBITED_DOM_PATTERNS, scan = { domGuard: [], strictLint: [], balance: [], commentLandmine: [], doctype: [] };
71
- for (const f of files) {
72
- let src = "";
73
- try {
74
- src = await Bun.file(join(root, f)).text();
75
- } catch {
76
- continue;
77
- }
78
- for (const d of lintStxStrict(src, { filePath: f, rules: config.staleRules }) ?? [])
79
- scan.strictLint.push(`${f}:${d.line}:${d.column} ${d.ruleId} ${d.message}`);
80
- for (const s of scanScriptTags(src, { skipAttrs: /\bserver\b|\bsrc\s*=/ }))
81
- for (const { pattern, message, suggestion } of domPatterns) {
82
- pattern.lastIndex = 0;
83
- const m = s.body.match(pattern);
84
- if (m)
85
- scan.domGuard.push(`${f} ${message} x${m.length} -> ${suggestion}`);
86
- }
87
- const open = (src.match(/<script\b/gi) ?? []).length, close = (src.match(/<\/script\s*>/gi) ?? []).length;
88
- if (open !== close)
89
- scan.balance.push(`${f} ${open} <script> vs ${close} </script> - a "</script" sits inside a script body`);
90
- for (const m of src.matchAll(/<!--([\s\S]*?)-->/g))
91
- if (/<\/?html\b|<!DOCTYPE\b|<\/?script\b/i.test(m[1] ?? "")) {
92
- const line = src.slice(0, m.index).split(`
93
- `).length;
94
- scan.commentLandmine.push(`${f}:${line} banned token inside <!-- -->`);
95
- }
96
- const exempt = config.doctypeExempt.some((p) => f.startsWith(p) || f === p);
97
- if (/<!DOCTYPE\s/i.test(src) && !/@nolayout\b/.test(src) && !exempt)
98
- scan.doctype.push(`${f} <!DOCTYPE> with no @nolayout - layout resolution is silently skipped`);
99
- }
100
- return scan;
101
- }
102
- async function missingStxConfigKeys(root) {
103
- const found = ["config/ui.ts", "config/ui.js"].find((c) => existsSync(join(root, c)));
104
- if (!found)
105
- return [];
106
- let ui;
107
- try {
108
- ui = (await import(join(root, found))).default ?? {};
109
- } catch {
110
- return [];
111
- }
112
- return REQUIRED_STX_CONFIG_KEYS.filter(([key]) => ui[key] == null).map(([key, why]) => `${found} is missing "${key}" - ${why}`);
113
- }
114
- export async function runStxLint(options = {}) {
115
- const root = options.root ?? process.cwd(), config = options.config ?? await loadStxLintConfig(root), stxAll = await scanGlob(config.stxGlob, root), dist = await scanGlob(config.distGlob, root), styled = stxAll.filter((f) => !config.styleExempt.some((p) => f.startsWith(p))), scan = await scanSources(stxAll, root, config), configErrors = await missingStxConfigKeys(root), definitions = [
116
- {
117
- id: "stx-config-keys",
118
- label: "stx config sets every key the standards require",
119
- why: "pinning root/pagesDir changes topology resolution, so it is a deliberate move",
120
- detail: () => configErrors
121
- },
122
- { id: "style-block", label: "no <style> block in a .stx file (rule 11.1)", detail: () => grepLines(/<style/, stxAll, root) },
123
- { id: "doctype-no-nolayout", label: "no <!DOCTYPE> outside the exempt list (rule 2.2)", detail: () => scan.doctype },
124
- { id: "script-tag-balance", label: 'no "</script" inside a script body', detail: () => scan.balance },
125
- { id: "comment-landmine", label: "no html/DOCTYPE/script token inside an HTML comment", detail: () => scan.commentLandmine },
126
- { id: "strict-lint", label: "stx's own strict linter", detail: () => scan.strictLint },
127
- {
128
- id: "dom-guard",
129
- label: "prohibited DOM access in client scripts",
130
- why: "imperative views clear these as they move to signals",
131
- detail: () => scan.domGuard
132
- },
133
- {
134
- id: "inline-style-attr",
135
- label: 'no style="" attribute (rule 11.5)',
136
- why: "pre-hydration display:none; the sanctioned form is a :class with literal branches",
137
- detail: () => grepLines(/style="/, styled, root)
138
- },
139
- {
140
- id: "plain-internal-anchor",
141
- label: 'no unrouted internal <a href="/"> (rule 9 - use StxLink)',
142
- why: "converting marketing pages is usually its own pass",
143
- detail: () => grepLines(/<a [^>]*href="\//, styled, root, ROUTED_ANCHOR)
144
- },
145
- {
146
- id: "unmanaged-timer",
147
- label: "no bare setTimeout/setInterval (rule 6.7)",
148
- why: "useTimeout()/useDebounce() unsubscribe on destroy; bare timers outlive the SPA swap",
149
- detail: () => grepLines(/(^|[^.\w])(setTimeout|setInterval)\s*\(/, stxAll, root)
150
- },
151
- { id: "dist-component-error", label: "no unresolved component in built HTML", detail: () => grepLines(/Error loading component/, dist, root) },
152
- { id: "dist-path-leak", label: "no absolute filesystem path in built HTML", detail: () => grepLines(/\/(Users|home)\/[a-z]/i, dist, root) },
153
- { id: "dist-layout-published", label: "no layout emitted as a public page", detail: () => dist.filter((f) => f.startsWith("layouts/") || f.includes("/layouts/")) }
154
- ], results = [];
155
- for (const def of definitions) {
156
- const detail = await def.detail(), count = detail.length, baseline = config.baselines[def.id] ?? 0;
157
- results.push({
158
- id: def.id,
159
- label: def.label,
160
- why: def.why,
161
- count,
162
- baseline,
163
- detail,
164
- status: count > baseline ? "fail" : count < baseline ? "loosened" : "pass"
165
- });
166
- }
167
- return {
168
- root,
169
- results,
170
- distMissing: dist.length === 0,
171
- failed: results.filter((r) => r.status === "fail").length,
172
- loosened: results.filter((r) => r.status === "loosened").length,
173
- counts: Object.fromEntries(results.map((r) => [r.id, r.count]))
174
- };
175
- }
1
+ import{existsSync}from"node:fs";import{join}from"node:path";import process from"node:process";import{Glob}from"bun";export const DEFAULT_STX_LINT_CONFIG={stxGlob:"resources/**/*.stx",distGlob:"dist/**/*.html",baselines:{},doctypeExempt:[],styleExempt:["resources/emails/"],staleRules:{}};const REQUIRED_STX_CONFIG_KEYS=[["strict","DOM guard (ch. 12.1) - without it script-validation discards every finding"],["root","pins project topology; absent, resolveStxRoot sniffs it and double-prefixes dirs"],["pagesDir",'must accompany root - resolveStxRoot falls back to a non-existent "pages"']];export async function loadStxLintConfig(root){const found=["config/lint.ts","config/lint.js"].find((c)=>existsSync(join(root,c)));if(!found)return{...DEFAULT_STX_LINT_CONFIG};try{const stx=(await import(join(root,found))).default?.stx??{};return{...DEFAULT_STX_LINT_CONFIG,...stx,baselines:{...stx.baselines},styleExempt:stx.styleExempt??DEFAULT_STX_LINT_CONFIG.styleExempt,doctypeExempt:stx.doctypeExempt??[],staleRules:stx.staleRules??{}}}catch(error){throw Error(`Could not read ${found}: ${error.message}`)}}async function scanGlob(pattern,root){const out=[];try{for await(const f of new Glob(pattern).scan(root))out.push(f)}catch{}return out.sort()}const ROUTED_ANCHOR=/\bdata-stx-link\b|\bdata-no-router\b/;async function grepLines(re,files,root,ignore){const hits=[];for(const f of files){let src="";try{src=await Bun.file(join(root,f)).text()}catch{continue}src.split(`
2
+ `).forEach((line,i)=>{re.lastIndex=0;if(!re.test(line))return;if(ignore){ignore.lastIndex=0;if(ignore.test(line))return}hits.push(`${f}:${i+1} ${line.trim().slice(0,90)}`)})}return hits}async function scanSources(files,root,config){const{lintStxStrict}=await import("@stacksjs/stx"),{PROHIBITED_DOM_PATTERNS}=await import("@stacksjs/stx/script-validation"),{scanScriptTags}=await import("@stacksjs/stx/signal-processing"),domPatterns=PROHIBITED_DOM_PATTERNS,scan={domGuard:[],strictLint:[],balance:[],commentLandmine:[],doctype:[]};for(const f of files){let src="";try{src=await Bun.file(join(root,f)).text()}catch{continue}for(const d of lintStxStrict(src,{filePath:f,rules:config.staleRules})??[])scan.strictLint.push(`${f}:${d.line}:${d.column} ${d.ruleId} ${d.message}`);for(const s of scanScriptTags(src,{skipAttrs:/\bserver\b|\bsrc\s*=/}))for(const{pattern,message,suggestion}of domPatterns){pattern.lastIndex=0;const m=s.body.match(pattern);if(m)scan.domGuard.push(`${f} ${message} x${m.length} -> ${suggestion}`)}const open=(src.match(/<script\b/gi)??[]).length,close=(src.match(/<\/script\s*>/gi)??[]).length;if(open!==close)scan.balance.push(`${f} ${open} <script> vs ${close} </script> - a "</script" sits inside a script body`);for(const m of src.matchAll(/<!--([\s\S]*?)-->/g))if(/<\/?html\b|<!DOCTYPE\b|<\/?script\b/i.test(m[1]??"")){const line=src.slice(0,m.index).split(`
3
+ `).length;scan.commentLandmine.push(`${f}:${line} banned token inside <!-- -->`)}const exempt=config.doctypeExempt.some((p)=>f.startsWith(p)||f===p);if(/<!DOCTYPE\s/i.test(src)&&!/@nolayout\b/.test(src)&&!exempt)scan.doctype.push(`${f} <!DOCTYPE> with no @nolayout - layout resolution is silently skipped`)}return scan}async function missingStxConfigKeys(root){const found=["config/ui.ts","config/ui.js"].find((c)=>existsSync(join(root,c)));if(!found)return[];let ui;try{ui=(await import(join(root,found))).default??{}}catch{return[]}return REQUIRED_STX_CONFIG_KEYS.filter(([key])=>ui[key]==null).map(([key,why])=>`${found} is missing "${key}" - ${why}`)}export async function runStxLint(options={}){const root=options.root??process.cwd(),config=options.config??await loadStxLintConfig(root),stxAll=await scanGlob(config.stxGlob,root),dist=await scanGlob(config.distGlob,root),styled=stxAll.filter((f)=>!config.styleExempt.some((p)=>f.startsWith(p))),scan=await scanSources(stxAll,root,config),configErrors=await missingStxConfigKeys(root),definitions=[{id:"stx-config-keys",label:"stx config sets every key the standards require",why:"pinning root/pagesDir changes topology resolution, so it is a deliberate move",detail:()=>configErrors},{id:"style-block",label:"no <style> block in a .stx file (rule 11.1)",detail:()=>grepLines(/<style/,stxAll,root)},{id:"doctype-no-nolayout",label:"no <!DOCTYPE> outside the exempt list (rule 2.2)",detail:()=>scan.doctype},{id:"script-tag-balance",label:'no "</script" inside a script body',detail:()=>scan.balance},{id:"comment-landmine",label:"no html/DOCTYPE/script token inside an HTML comment",detail:()=>scan.commentLandmine},{id:"strict-lint",label:"stx's own strict linter",detail:()=>scan.strictLint},{id:"dom-guard",label:"prohibited DOM access in client scripts",why:"imperative views clear these as they move to signals",detail:()=>scan.domGuard},{id:"inline-style-attr",label:'no style="" attribute (rule 11.5)',why:"pre-hydration display:none; the sanctioned form is a :class with literal branches",detail:()=>grepLines(/style="/,styled,root)},{id:"plain-internal-anchor",label:'no unrouted internal <a href="/"> (rule 9 - use StxLink)',why:"converting marketing pages is usually its own pass",detail:()=>grepLines(/<a [^>]*href="\//,styled,root,ROUTED_ANCHOR)},{id:"unmanaged-timer",label:"no bare setTimeout/setInterval (rule 6.7)",why:"useTimeout()/useDebounce() unsubscribe on destroy; bare timers outlive the SPA swap",detail:()=>grepLines(/(^|[^.\w])(setTimeout|setInterval)\s*\(/,stxAll,root)},{id:"dist-component-error",label:"no unresolved component in built HTML",detail:()=>grepLines(/Error loading component/,dist,root)},{id:"dist-path-leak",label:"no absolute filesystem path in built HTML",detail:()=>grepLines(/\/(Users|home)\/[a-z]/i,dist,root)},{id:"dist-layout-published",label:"no layout emitted as a public page",detail:()=>dist.filter((f)=>f.startsWith("layouts/")||f.includes("/layouts/"))}],results=[];for(const def of definitions){const detail=await def.detail(),count=detail.length,baseline=config.baselines[def.id]??0;results.push({id:def.id,label:def.label,why:def.why,count,baseline,detail,status:count>baseline?"fail":count<baseline?"loosened":"pass"})}return{root,results,distMissing:dist.length===0,failed:results.filter((r)=>r.status==="fail").length,loosened:results.filter((r)=>r.status==="loosened").length,counts:Object.fromEntries(results.map((r)=>[r.id,r.count]))}}
@@ -1,27 +1,4 @@
1
- import { log } from "@stacksjs/logging";
2
- import * as p from "@stacksjs/path";
3
- import { get, writeFile } from "@stacksjs/storage";
4
- export async function makeCommand(options) {
5
- const name = options.name;
6
- if (!name) {
7
- log.error("Command name is required");
8
- return !1;
9
- }
10
- const commandName = toPascalCase(name), content = generateCommandContent(commandName, options), filePath = p.commandsPath(`${commandName}.ts`);
11
- try {
12
- await writeFile(filePath, content);
13
- log.success(`Created command: ${filePath}`);
14
- if (options.register !== !1)
15
- await registerCommand(commandName, options.signature || toKebabCase(name));
16
- return !0;
17
- } catch (error) {
18
- log.error(`Failed to create command: ${error.message}`);
19
- return !1;
20
- }
21
- }
22
- function generateCommandContent(name, options) {
23
- const signature = options.signature || toKebabCase(name), description = options.description || `The ${signature} command`;
24
- return `import type { CLI } from '@stacksjs/types'
1
+ import{log}from"@stacksjs/logging";import*as p from"@stacksjs/path";import{get,writeFile}from"@stacksjs/storage";export async function makeCommand(options){const name=options.name;if(!name){log.error("Command name is required");return!1}const commandName=toPascalCase(name),content=generateCommandContent(commandName,options),filePath=p.commandsPath(`${commandName}.ts`);try{await writeFile(filePath,content);log.success(`Created command: ${filePath}`);if(options.register!==!1)await registerCommand(commandName,options.signature||toKebabCase(name));return!0}catch(error){log.error(`Failed to create command: ${error.message}`);return!1}}function generateCommandContent(name,options){const signature=options.signature||toKebabCase(name),description=options.description||`The ${signature} command`;return`import type { CLI } from '@stacksjs/types'
25
2
  import { log } from '@stacksjs/cli'
26
3
 
27
4
  /**
@@ -62,34 +39,6 @@ export default function (cli: CLI) {
62
39
  log.error('Invalid command: %s\\nSee --help for a list of available commands.', cli.args.join(' '))
63
40
  })
64
41
  }
65
- `;
66
- }
67
- async function registerCommand(name, signature) {
68
- const commandsPath = p.appPath("Commands.ts");
69
- try {
70
- let content = await get(commandsPath);
71
- const exportMatch = content.match(/export default \{([\s\S]*)\} satisfies/);
72
- if (exportMatch) {
73
- const existingCommands = exportMatch[1] ?? "";
74
- if (existingCommands.includes(`'${signature}'`)) {
75
- log.info(`Command '${signature}' already registered in Commands.ts`);
76
- return;
77
- }
78
- const newCommand = ` '${signature}': '${name}',
79
- `, updatedCommands = `${existingCommands.trimEnd()}
80
- ${newCommand}`;
81
- content = content.replace(/export default \{[\s\S]*\} satisfies/, `export default {${updatedCommands}} satisfies`);
82
- await writeFile(commandsPath, content);
83
- log.success(`Registered command '${signature}' in Commands.ts`);
84
- }
85
- } catch (error) {
86
- log.warn(`Could not register command in Commands.ts: ${error.message}`);
87
- log.info("You may need to manually add it to app/Commands.ts");
88
- }
89
- }
90
- function toPascalCase(str) {
91
- return str.replace(/[-_](.)/g, (_, char) => char.toUpperCase()).replace(/^(.)/, (_, char) => char.toUpperCase());
92
- }
93
- function toKebabCase(str) {
94
- return str.replace(/([a-z])([A-Z])/g, "$1-$2").replace(/[_\s]+/g, "-").toLowerCase();
95
- }
42
+ `}async function registerCommand(name,signature){const commandsPath=p.appPath("Commands.ts");try{let content=await get(commandsPath);const exportMatch=content.match(/export default \{([\s\S]*)\} satisfies/);if(exportMatch){const existingCommands=exportMatch[1]??"";if(existingCommands.includes(`'${signature}'`)){log.info(`Command '${signature}' already registered in Commands.ts`);return}const newCommand=` '${signature}': '${name}',
43
+ `,updatedCommands=`${existingCommands.trimEnd()}
44
+ ${newCommand}`;content=content.replace(/export default \{[\s\S]*\} satisfies/,`export default {${updatedCommands}} satisfies`);await writeFile(commandsPath,content);log.success(`Registered command '${signature}' in Commands.ts`)}}catch(error){log.warn(`Could not register command in Commands.ts: ${error.message}`);log.info("You may need to manually add it to app/Commands.ts")}}function toPascalCase(str){return str.replace(/[-_](.)/g,(_,char)=>char.toUpperCase()).replace(/^(.)/,(_,char)=>char.toUpperCase())}function toKebabCase(str){return str.replace(/([a-z])([A-Z])/g,"$1-$2").replace(/[_\s]+/g,"-").toLowerCase()}
package/dist/make-job.js CHANGED
@@ -1,25 +1,4 @@
1
- import { log } from "@stacksjs/logging";
2
- import * as p from "@stacksjs/path";
3
- import { writeFile } from "@stacksjs/storage";
4
- export async function makeJob(options) {
5
- const jobOptions = options, name = options.name;
6
- if (!name) {
7
- log.error("Job name is required");
8
- return !1;
9
- }
10
- const jobName = name.endsWith("Job") ? name : `${name}Job`, content = jobOptions.class ?? !1 ? generateClassBasedJob(jobName, jobOptions) : generateFunctionBasedJob(jobName, jobOptions), filePath = p.userJobsPath(`${jobName}.ts`);
11
- try {
12
- await writeFile(filePath, content);
13
- log.success(`Created job: ${filePath}`);
14
- return !0;
15
- } catch (error) {
16
- log.error(`Failed to create job: ${error.message}`);
17
- return !1;
18
- }
19
- }
20
- function generateFunctionBasedJob(name, options) {
21
- const queue = options.queue ?? "default", tries = options.tries ?? 3, backoff = options.backoff ?? 3;
22
- return `import { Job } from '@stacksjs/queue'
1
+ import{log}from"@stacksjs/logging";import*as p from"@stacksjs/path";import{writeFile}from"@stacksjs/storage";export async function makeJob(options){const jobOptions=options,name=options.name;if(!name){log.error("Job name is required");return!1}const jobName=name.endsWith("Job")?name:`${name}Job`,content=jobOptions.class??!1?generateClassBasedJob(jobName,jobOptions):generateFunctionBasedJob(jobName,jobOptions),filePath=p.userJobsPath(`${jobName}.ts`);try{await writeFile(filePath,content);log.success(`Created job: ${filePath}`);return!0}catch(error){log.error(`Failed to create job: ${error.message}`);return!1}}function generateFunctionBasedJob(name,options){const queue=options.queue??"default",tries=options.tries??3,backoff=options.backoff??3;return`import { Job } from '@stacksjs/queue'
23
2
 
24
3
  export default new Job({
25
4
  /**
@@ -78,11 +57,7 @@ export default new Job({
78
57
  return { success: true }
79
58
  },
80
59
  })
81
- `;
82
- }
83
- function generateClassBasedJob(name, options) {
84
- const queue = options.queue ?? "default", tries = options.tries ?? 3;
85
- return `import { log } from '@stacksjs/logging'
60
+ `}function generateClassBasedJob(name,options){const queue=options.queue??"default",tries=options.tries??3;return`import { log } from '@stacksjs/logging'
86
61
 
87
62
  /**
88
63
  * ${name}
@@ -150,5 +125,4 @@ export default class ${name} {
150
125
  }
151
126
  }
152
127
  }
153
- `;
154
- }
128
+ `}
@@ -1,31 +1,4 @@
1
- import { log } from "@stacksjs/logging";
2
- import * as p from "@stacksjs/path";
3
- import { doesExist, get, writeFile } from "@stacksjs/storage";
4
- export async function makePolicy(options) {
5
- const name = options.name;
6
- if (!name) {
7
- log.error("Policy name is required");
8
- return !1;
9
- }
10
- const policyName = name.endsWith("Policy") ? name : `${name}Policy`, modelName = options.model || policyName.replace("Policy", ""), content = generatePolicyContent(policyName, modelName), filePath = p.appPath(`Policies/${policyName}.ts`);
11
- try {
12
- const policiesDir = p.appPath("Policies");
13
- if (!doesExist(policiesDir)) {
14
- const { mkdirSync } = await import("@stacksjs/storage");
15
- mkdirSync(policiesDir, { recursive: !0 });
16
- }
17
- await writeFile(filePath, content);
18
- log.success(`Created policy: ${filePath}`);
19
- if (options.register !== !1)
20
- await registerPolicy(modelName, policyName);
21
- return !0;
22
- } catch (error) {
23
- log.error(`Failed to create policy: ${error.message}`);
24
- return !1;
25
- }
26
- }
27
- function generatePolicyContent(policyName, modelName) {
28
- return `import type _User from '../models/User'
1
+ import{log}from"@stacksjs/logging";import*as p from"@stacksjs/path";import{doesExist,get,writeFile}from"@stacksjs/storage";export async function makePolicy(options){const name=options.name;if(!name){log.error("Policy name is required");return!1}const policyName=name.endsWith("Policy")?name:`${name}Policy`,modelName=options.model||policyName.replace("Policy",""),content=generatePolicyContent(policyName,modelName),filePath=p.appPath(`Policies/${policyName}.ts`);try{const policiesDir=p.appPath("Policies");if(!doesExist(policiesDir)){const{mkdirSync}=await import("@stacksjs/storage");mkdirSync(policiesDir,{recursive:!0})}await writeFile(filePath,content);log.success(`Created policy: ${filePath}`);if(options.register!==!1)await registerPolicy(modelName,policyName);return!0}catch(error){log.error(`Failed to create policy: ${error.message}`);return!1}}function generatePolicyContent(policyName,modelName){return`import type _User from '../models/User'
29
2
  import { BasePolicy } from '@stacksjs/auth'
30
3
 
31
4
  type UserModel = _User
@@ -115,28 +88,6 @@ export default class ${policyName} extends BasePolicy<${modelName}> {
115
88
  return user?.id === model.user_id
116
89
  }
117
90
  }
118
- `;
119
- }
120
- async function registerPolicy(modelName, policyName) {
121
- const gatesPath = p.appPath("Gates.ts");
122
- try {
123
- let content = await get(gatesPath);
124
- const policiesMatch = content.match(/export const policies[^{]*\{([^}]*)\}/);
125
- if (policiesMatch) {
126
- const existingPolicies = policiesMatch[1] ?? "";
127
- if (existingPolicies.includes(`'${modelName}'`)) {
128
- log.info(`Policy for '${modelName}' already registered in Gates.ts`);
129
- return;
130
- }
131
- const newPolicy = ` '${modelName}': '${policyName}',
132
- `, updatedPolicies = `${existingPolicies.trimEnd()}
133
- ${newPolicy}`;
134
- content = content.replace(/export const policies[^{]*\{([^}]*)\}/, `export const policies: Record<string, string | { policy: string, model?: string }> = {${updatedPolicies}}`);
135
- await writeFile(gatesPath, content);
136
- log.success(`Registered policy '${policyName}' for '${modelName}' in Gates.ts`);
137
- }
138
- } catch (error) {
139
- log.warn(`Could not register policy in Gates.ts: ${error.message}`);
140
- log.info("You may need to manually add it to app/Gates.ts");
141
- }
142
- }
91
+ `}async function registerPolicy(modelName,policyName){const gatesPath=p.appPath("Gates.ts");try{let content=await get(gatesPath);const policiesMatch=content.match(/export const policies[^{]*\{([^}]*)\}/);if(policiesMatch){const existingPolicies=policiesMatch[1]??"";if(existingPolicies.includes(`'${modelName}'`)){log.info(`Policy for '${modelName}' already registered in Gates.ts`);return}const newPolicy=` '${modelName}': '${policyName}',
92
+ `,updatedPolicies=`${existingPolicies.trimEnd()}
93
+ ${newPolicy}`;content=content.replace(/export const policies[^{]*\{([^}]*)\}/,`export const policies: Record<string, string | { policy: string, model?: string }> = {${updatedPolicies}}`);await writeFile(gatesPath,content);log.success(`Registered policy '${policyName}' for '${modelName}' in Gates.ts`)}}catch(error){log.warn(`Could not register policy in Gates.ts: ${error.message}`);log.info("You may need to manually add it to app/Gates.ts")}}
@@ -1,29 +1,4 @@
1
- import { log } from "@stacksjs/logging";
2
- import * as p from "@stacksjs/path";
3
- import { doesExist, writeFile } from "@stacksjs/storage";
4
- export async function makeResource(options) {
5
- const name = options.name;
6
- if (!name) {
7
- log.error("Resource name is required");
8
- return !1;
9
- }
10
- const resourceName = name.endsWith("Resource") ? name : `${name}Resource`, modelName = options.model || resourceName.replace("Resource", ""), content = options.collection ? generateCollectionResourceContent(resourceName, modelName) : generateResourceContent(resourceName, modelName), resourcesDir = p.appPath("Resources");
11
- if (!doesExist(resourcesDir)) {
12
- const { mkdirSync } = await import("@stacksjs/storage");
13
- mkdirSync(resourcesDir, { recursive: !0 });
14
- }
15
- const filePath = p.appPath(`Resources/${resourceName}.ts`);
16
- try {
17
- await writeFile(filePath, content);
18
- log.success(`Created resource: ${filePath}`);
19
- return !0;
20
- } catch (error) {
21
- log.error(`Failed to create resource: ${error.message}`);
22
- return !1;
23
- }
24
- }
25
- function generateResourceContent(resourceName, modelName) {
26
- return `import type { Request } from '@stacksjs/router'
1
+ import{log}from"@stacksjs/logging";import*as p from"@stacksjs/path";import{doesExist,writeFile}from"@stacksjs/storage";export async function makeResource(options){const name=options.name;if(!name){log.error("Resource name is required");return!1}const resourceName=name.endsWith("Resource")?name:`${name}Resource`,modelName=options.model||resourceName.replace("Resource",""),content=options.collection?generateCollectionResourceContent(resourceName,modelName):generateResourceContent(resourceName,modelName),resourcesDir=p.appPath("Resources");if(!doesExist(resourcesDir)){const{mkdirSync}=await import("@stacksjs/storage");mkdirSync(resourcesDir,{recursive:!0})}const filePath=p.appPath(`Resources/${resourceName}.ts`);try{await writeFile(filePath,content);log.success(`Created resource: ${filePath}`);return!0}catch(error){log.error(`Failed to create resource: ${error.message}`);return!1}}function generateResourceContent(resourceName,modelName){return`import type { Request } from '@stacksjs/router'
27
2
  import { JsonResource } from '@stacksjs/api'
28
3
 
29
4
  /**
@@ -79,11 +54,7 @@ export default class ${resourceName} extends JsonResource<${modelName}> {
79
54
  }
80
55
  }
81
56
  }
82
- `;
83
- }
84
- function generateCollectionResourceContent(resourceName, modelName) {
85
- const baseResourceName = resourceName.replace("Collection", "");
86
- return `import type { Request } from '@stacksjs/router'
57
+ `}function generateCollectionResourceContent(resourceName,modelName){const baseResourceName=resourceName.replace("Collection","");return`import type { Request } from '@stacksjs/router'
87
58
  import { JsonResource, ResourceCollection } from '@stacksjs/api'
88
59
 
89
60
  /**
@@ -138,5 +109,4 @@ export default class ${resourceName} extends ResourceCollection<${modelName}, ${
138
109
  }
139
110
  }
140
111
  }
141
- `;
142
- }
112
+ `}