praxo-cli 0.0.0-stage → 0.1.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 (82) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +159 -2
  3. package/dist/app.js +75 -0
  4. package/dist/bin.js +21 -0
  5. package/dist/cli/commands/ai.command.js +189 -0
  6. package/dist/cli/commands/cmd.command.js +265 -0
  7. package/dist/cli/commands/completion.command.js +334 -0
  8. package/dist/cli/commands/config.command.js +27 -0
  9. package/dist/cli/commands/decision.command.js +287 -0
  10. package/dist/cli/commands/doctor.command.js +45 -0
  11. package/dist/cli/commands/project.command.js +24 -0
  12. package/dist/cli/commands/search.command.js +59 -0
  13. package/dist/cli/commands/sync.command.js +122 -0
  14. package/dist/cli/commands/transfer.command.js +148 -0
  15. package/dist/cli/index.js +156 -0
  16. package/dist/cli/output.js +133 -0
  17. package/dist/cli/prompts.js +68 -0
  18. package/dist/features/ai/client.js +238 -0
  19. package/dist/features/ai/output.js +7 -0
  20. package/dist/features/ai/providers.js +52 -0
  21. package/dist/features/ai/schemas.js +43 -0
  22. package/dist/features/ai/service.js +183 -0
  23. package/dist/features/commands/executor.js +54 -0
  24. package/dist/features/commands/repository.js +61 -0
  25. package/dist/features/commands/safety.js +154 -0
  26. package/dist/features/commands/service.js +254 -0
  27. package/dist/features/commands/template.js +153 -0
  28. package/dist/features/decisions/repository.js +53 -0
  29. package/dist/features/decisions/service.js +209 -0
  30. package/dist/features/decisions/stats.js +84 -0
  31. package/dist/features/decisions/status.js +7 -0
  32. package/dist/features/projects/repository.js +51 -0
  33. package/dist/features/projects/service.js +74 -0
  34. package/dist/features/sync/git.js +207 -0
  35. package/dist/features/sync/merge.js +194 -0
  36. package/dist/features/sync/repository.js +151 -0
  37. package/dist/features/sync/sanitizer.js +21 -0
  38. package/dist/features/sync/service.js +199 -0
  39. package/dist/features/sync/snapshot.js +230 -0
  40. package/dist/infrastructure/credentials/store.js +105 -0
  41. package/dist/infrastructure/database/client.js +41 -0
  42. package/dist/infrastructure/database/migrate.js +102 -0
  43. package/dist/infrastructure/database/schema.js +138 -0
  44. package/dist/infrastructure/git/detector.js +48 -0
  45. package/dist/shared/clipboard.js +19 -0
  46. package/dist/shared/config.js +163 -0
  47. package/dist/shared/doctor.js +47 -0
  48. package/dist/shared/errors.js +19 -0
  49. package/dist/shared/global-search.js +51 -0
  50. package/dist/shared/input.js +37 -0
  51. package/dist/shared/links.js +48 -0
  52. package/dist/shared/paths.js +14 -0
  53. package/dist/shared/query.js +10 -0
  54. package/dist/shared/redaction.js +54 -0
  55. package/dist/shared/search.js +39 -0
  56. package/dist/shared/sync-metadata.js +7 -0
  57. package/dist/shared/tags.js +91 -0
  58. package/dist/shared/transfer/archive.js +197 -0
  59. package/dist/shared/transfer/markdown.js +53 -0
  60. package/dist/shared/transfer/service.js +278 -0
  61. package/dist/tui/Workspace.js +121 -0
  62. package/dist/tui/components/AiPanel.js +200 -0
  63. package/dist/tui/components/Catalog.js +47 -0
  64. package/dist/tui/components/Confirm.js +28 -0
  65. package/dist/tui/components/Form.js +113 -0
  66. package/dist/tui/components/HelpModal.js +44 -0
  67. package/dist/tui/components/Inspection.js +28 -0
  68. package/dist/tui/components/KeyHints.js +7 -0
  69. package/dist/tui/components/SearchInput.js +31 -0
  70. package/dist/tui/components/SyncPanel.js +93 -0
  71. package/dist/tui/index.js +18 -0
  72. package/dist/tui/screens/Commands.js +383 -0
  73. package/dist/tui/screens/DecisionForms.js +117 -0
  74. package/dist/tui/screens/Decisions.js +260 -0
  75. package/dist/tui/screens/Lookup.js +96 -0
  76. package/dist/tui/theme.js +47 -0
  77. package/drizzle/0000_initial.sql +105 -0
  78. package/drizzle/0001_v11_sync.sql +117 -0
  79. package/drizzle/meta/0000_snapshot.json +735 -0
  80. package/drizzle/meta/0001_snapshot.json +867 -0
  81. package/drizzle/meta/_journal.json +20 -0
  82. package/package.json +77 -4
@@ -0,0 +1,154 @@
1
+ import { win32 } from 'node:path';
2
+ import { tokenize } from './template.js';
3
+ const parentShell = new Set([
4
+ 'cd',
5
+ 'chdir',
6
+ 'pushd',
7
+ 'popd',
8
+ 'export',
9
+ 'unset',
10
+ 'set',
11
+ 'setenv',
12
+ 'alias',
13
+ 'unalias',
14
+ 'source',
15
+ '.',
16
+ 'set-location',
17
+ 'push-location',
18
+ 'pop-location',
19
+ 'set-alias',
20
+ 'new-alias',
21
+ 'set-variable',
22
+ 'remove-variable',
23
+ ]);
24
+ const shells = new Set([
25
+ 'sh',
26
+ 'bash',
27
+ 'zsh',
28
+ 'fish',
29
+ 'dash',
30
+ 'ksh',
31
+ 'ash',
32
+ 'cmd',
33
+ 'powershell',
34
+ 'pwsh',
35
+ 'eval',
36
+ 'exec',
37
+ 'command',
38
+ 'env',
39
+ 'xargs',
40
+ 'wsl',
41
+ 'wsl.exe',
42
+ ]);
43
+ const destructive = new Set([
44
+ 'rm',
45
+ 'rmdir',
46
+ 'del',
47
+ 'erase',
48
+ 'rd',
49
+ 'remove-item',
50
+ 'mkfs',
51
+ 'format',
52
+ 'diskpart',
53
+ 'dd',
54
+ 'shutdown',
55
+ 'reboot',
56
+ 'systemctl',
57
+ 'kill',
58
+ 'killall',
59
+ 'taskkill',
60
+ 'stop-process',
61
+ 'sudo',
62
+ 'doas',
63
+ 'chown',
64
+ 'chmod',
65
+ 'icacls',
66
+ 'takeown',
67
+ 'bcdedit',
68
+ 'reg',
69
+ ]);
70
+ const interpreters = new Set([
71
+ 'node',
72
+ 'nodejs',
73
+ 'python',
74
+ 'python3',
75
+ 'py',
76
+ 'ruby',
77
+ 'perl',
78
+ 'php',
79
+ 'deno',
80
+ 'bun',
81
+ ]);
82
+ /** 保守标记已知危险操作,并拒绝依赖 Shell 或解释器内联求值的执行。 */
83
+ export function assessRisk(template, values, manuallyDangerous) {
84
+ const parsed = tokenize(template, values);
85
+ const [program, ...arguments_] = parsed.args;
86
+ const name = program
87
+ ? win32
88
+ .basename(program.value)
89
+ .toLowerCase()
90
+ .replace(/\.exe$/u, '')
91
+ : '';
92
+ if (program && !program.hasVariable && parentShell.has(name)) {
93
+ return {
94
+ kind: 'parent-shell',
95
+ reason: 'This command changes the current shell. Praxo can copy it for you.',
96
+ };
97
+ }
98
+ if (parsed.unsupported)
99
+ return { kind: 'copy-only', reason: parsed.unsupported + '. Use pxo command copy.' };
100
+ if (!program?.value || program.hasVariable || program.value.startsWith('-')) {
101
+ return {
102
+ kind: 'copy-only',
103
+ reason: 'Execution requires a fixed executable name. Use pxo command copy.',
104
+ };
105
+ }
106
+ let flagsEnded = false;
107
+ for (const arg of arguments_) {
108
+ if (!arg.hasVariable && arg.value === '--')
109
+ flagsEnded = true;
110
+ if (!flagsEnded && arg.variablePrefix && arg.value.startsWith('-')) {
111
+ return {
112
+ kind: 'copy-only',
113
+ reason: 'A variable cannot become an option. Use a fixed option or a literal -- before it.',
114
+ };
115
+ }
116
+ }
117
+ const args = arguments_.map(({ value }) => value);
118
+ const words = args.map((argument) => argument.toLowerCase());
119
+ if (/\.(cmd|bat|ps1)$/iu.test(program.value) ||
120
+ shells.has(name) ||
121
+ (interpreters.has(name) &&
122
+ words.some((word) => /^--(?:eval|print|command)(?:=|$)|^-[a-z]*[ecpr]/u.test(word) || word === 'eval')) ||
123
+ (name === 'git' && words.some((word) => word === '-c' || word.startsWith('--config-env')))) {
124
+ return {
125
+ kind: 'copy-only',
126
+ reason: 'This command delegates parsing or evaluation to an interpreter. Use pxo command copy.',
127
+ };
128
+ }
129
+ const dangerousGit = name === 'git' &&
130
+ (words.includes('clean') ||
131
+ words.includes('reset') ||
132
+ words.includes('restore') ||
133
+ (words.includes('push') &&
134
+ words.some((word) => word.startsWith('--force') || word === '-f' || word.startsWith('+'))) ||
135
+ (words.includes('branch') &&
136
+ args.some((word) => word === '-d' || word === '-D' || word === '--delete')));
137
+ const destructiveVerb = ['docker', 'kubectl', 'podman', 'terraform', 'npm', 'pnpm', 'pip'].includes(name) &&
138
+ words.some((word) => ['rm', 'rmi', 'prune', 'delete', 'destroy', 'uninstall', 'down'].includes(word));
139
+ const high = manuallyDangerous ||
140
+ destructive.has(name) ||
141
+ /^mkfs\./u.test(name) ||
142
+ dangerousGit ||
143
+ destructiveVerb;
144
+ return {
145
+ kind: high ? 'high' : 'ordinary',
146
+ reason: manuallyDangerous
147
+ ? 'This command is marked dangerous.'
148
+ : high
149
+ ? 'Potentially destructive operation.'
150
+ : 'Direct program execution.',
151
+ executable: program.value,
152
+ args,
153
+ };
154
+ }
@@ -0,0 +1,254 @@
1
+ import { z } from 'zod';
2
+ import { withoutSyncMetadata } from '../../shared/sync-metadata.js';
3
+ import { AppError } from '../../shared/errors.js';
4
+ import { defaultLimit, newId, nonempty, normalize, scope, tier, validate, } from '../../shared/input.js';
5
+ import { search } from '../../shared/search.js';
6
+ import { matchesTags } from '../../shared/tags.js';
7
+ import { assessRisk } from './safety.js';
8
+ import { parseTemplate, renderTemplate, resolveTemplate } from './template.js';
9
+ const fields = z.object({
10
+ name: nonempty.optional(),
11
+ template: z.string(),
12
+ note: z.string(),
13
+ type: nonempty,
14
+ tier,
15
+ sos: z.boolean(),
16
+ danger: z.boolean(),
17
+ project: nonempty.optional(),
18
+ });
19
+ const createSchema = fields.extend({
20
+ note: z.string().default(''),
21
+ type: nonempty.default('custom'),
22
+ tier: tier.default('normal'),
23
+ sos: z.boolean().default(false),
24
+ danger: z.boolean().default(false),
25
+ scope: scope.default('auto'),
26
+ tags: z.array(nonempty).default([]),
27
+ });
28
+ const editSchema = fields.partial().extend({ scope: z.enum(['global', 'project']).optional() });
29
+ const querySchema = z.object({
30
+ project: nonempty.optional(),
31
+ type: nonempty.optional(),
32
+ tier: tier.optional(),
33
+ sos: z.boolean().optional(),
34
+ scope: z.enum(['global', 'project', 'all']).optional(),
35
+ tags: z.array(nonempty).optional(),
36
+ sort: z.enum(['smart', 'recent', 'used', 'name']).default('smart'),
37
+ limit: z.number().int().positive().optional(),
38
+ });
39
+ export function commandFields(item) {
40
+ return {
41
+ title: item.name,
42
+ body: [item.template, item.note, item.type].join(' '),
43
+ tags: item.tags,
44
+ project: item.projectName ?? '',
45
+ };
46
+ }
47
+ export function commandService({ repository, projects, tags, write, now, copy, execute, cwd, }) {
48
+ function load(id) {
49
+ const command = repository.byId(id);
50
+ if (!command)
51
+ throw new AppError(3, 'Command ' + id + ' was not found. Run pxo command list.');
52
+ return command;
53
+ }
54
+ function summary(row, names) {
55
+ return {
56
+ ...withoutSyncMetadata(row.command),
57
+ projectName: row.projectName,
58
+ tags: names,
59
+ count: row.count ?? 0,
60
+ copyCount: row.copyCount ?? 0,
61
+ runCount: row.runCount ?? 0,
62
+ lastUsedAt: row.lastUsedAt ?? null,
63
+ };
64
+ }
65
+ function show(id) {
66
+ const row = repository.detail(id);
67
+ if (!row)
68
+ throw new AppError(3, 'Command ' + id + ' was not found. Run pxo command list.');
69
+ return summary(row, tags.forEntity('command', id));
70
+ }
71
+ function candidates(input = {}, keyword) {
72
+ const filter = validate(querySchema, input);
73
+ const projectId = projects.resolve(filter.project)?.id ?? null;
74
+ const names = tags.tagMap('command');
75
+ const rows = repository
76
+ .list(projectId, { ...filter, type: filter.type && normalize(filter.type) })
77
+ .map((row) => summary(row, names.get(row.command.id) ?? []))
78
+ .filter((item) => matchesTags(item.tags, filter.tags));
79
+ const ranked = keyword === undefined
80
+ ? rows.map((item) => ({ item, score: 0 }))
81
+ : search(rows, keyword, commandFields);
82
+ const compareName = (a, b) => a.name.localeCompare(b.name);
83
+ const compareRecent = (a, b) => (b.lastUsedAt ?? '').localeCompare(a.lastUsedAt ?? '') ||
84
+ b.createdAt.localeCompare(a.createdAt);
85
+ return ranked
86
+ .sort((left, right) => {
87
+ const a = left.item, b = right.item;
88
+ const id = a.id.localeCompare(b.id);
89
+ if (filter.sort === 'name')
90
+ return compareName(a, b) || id;
91
+ if (filter.sort === 'used')
92
+ return b.count - a.count || compareRecent(a, b) || id;
93
+ if (filter.sort === 'recent')
94
+ return compareRecent(a, b) || id;
95
+ return (Number(b.projectId === projectId) - Number(a.projectId === projectId) ||
96
+ left.score - right.score ||
97
+ Number(b.tier === 'hot') - Number(a.tier === 'hot') ||
98
+ (b.lastUsedAt ?? '').localeCompare(a.lastUsedAt ?? '') ||
99
+ b.count - a.count ||
100
+ compareName(a, b) ||
101
+ id);
102
+ })
103
+ .map(({ item }) => item);
104
+ }
105
+ function list(input = {}, keyword) {
106
+ return candidates(input, keyword).slice(0, input.limit ?? defaultLimit);
107
+ }
108
+ function match(idOrQuery) {
109
+ if (repository.byId(idOrQuery))
110
+ return [show(idOrQuery)];
111
+ const matches = candidates({}, idOrQuery);
112
+ if (!matches.length)
113
+ throw new AppError(3, 'No command matches that ID or query. Run pxo command search.');
114
+ return matches;
115
+ }
116
+ function create(input) {
117
+ const data = validate(createSchema, input);
118
+ parseTemplate(data.template);
119
+ const id = newId();
120
+ const date = now().toISOString();
121
+ const projectId = projects.scopeProject(data.scope, data.project);
122
+ write(() => {
123
+ repository.insert({
124
+ id,
125
+ name: data.name ?? data.template.trim().split(/\s+/u).slice(0, 3).join(' ').slice(0, 80),
126
+ template: data.template,
127
+ note: data.note,
128
+ type: normalize(data.type),
129
+ tier: data.tier,
130
+ sos: data.sos,
131
+ danger: data.danger,
132
+ projectId,
133
+ createdAt: date,
134
+ updatedAt: date,
135
+ });
136
+ for (const tag of data.tags)
137
+ tags.attach('command', id, tag);
138
+ });
139
+ return show(id);
140
+ }
141
+ function edit(id, input) {
142
+ const { scope, project, type, ...patch } = validate(editSchema, input);
143
+ if (patch.template !== undefined)
144
+ parseTemplate(patch.template);
145
+ const projectId = scope || project ? projects.scopeProject(scope ?? 'project', project) : undefined;
146
+ write(() => {
147
+ load(id);
148
+ repository.update(id, {
149
+ ...patch,
150
+ type: type === undefined ? undefined : normalize(type),
151
+ projectId,
152
+ updatedAt: now().toISOString(),
153
+ });
154
+ });
155
+ return show(id);
156
+ }
157
+ function remove(id) {
158
+ write(() => {
159
+ load(id);
160
+ repository.remove(id, now().toISOString());
161
+ });
162
+ }
163
+ function tag(id, action, name) {
164
+ write(() => {
165
+ load(id);
166
+ if (action === 'add')
167
+ tags.attach('command', id, name);
168
+ else
169
+ tags.detach('command', id, name);
170
+ });
171
+ return show(id);
172
+ }
173
+ function variables(id, inputs) {
174
+ const template = parseTemplate(load(id).template);
175
+ return resolveTemplate(template, inputs).missing;
176
+ }
177
+ function render(id, values) {
178
+ return renderTemplate(parseTemplate(load(id).template), values).text;
179
+ }
180
+ function prepare(id, values) {
181
+ const command = load(id);
182
+ const template = parseTemplate(command.template);
183
+ const rendered = renderTemplate(template, values);
184
+ return { text: rendered.text, risk: assessRisk(template, rendered.values, command.danger) };
185
+ }
186
+ function record(id, kind, outcome, code) {
187
+ try {
188
+ repository.use({
189
+ id: newId(),
190
+ commandId: id,
191
+ kind,
192
+ usedAt: now().toISOString(),
193
+ outcome,
194
+ exitCode: code,
195
+ });
196
+ }
197
+ catch (error) {
198
+ throw new AppError(5, (kind === 'copy' ? 'Command copied' : 'Command already ran') +
199
+ ', but its usage could not be saved.', { cause: error });
200
+ }
201
+ }
202
+ async function copyText(id, text) {
203
+ await copy(text);
204
+ record(id, 'copy', 'success', null);
205
+ }
206
+ async function copyCommand(id, values) {
207
+ await copyText(id, render(id, values));
208
+ }
209
+ /** 执行前重新生成计划,确认针对的文本和风险必须与当前记录一致。 */
210
+ async function run(id, values, approval, reviewed, captured) {
211
+ const plan = prepare(id, values);
212
+ if (plan.text !== reviewed.text ||
213
+ JSON.stringify(plan.risk) !== JSON.stringify(reviewed.risk)) {
214
+ throw new AppError(4, 'The command changed during confirmation. Preview it again.');
215
+ }
216
+ const risk = plan.risk;
217
+ if (risk.kind === 'copy-only')
218
+ throw new AppError(4, risk.reason);
219
+ if (risk.kind === 'parent-shell') {
220
+ await copyText(id, plan.text);
221
+ return { kind: 'copied', reason: risk.reason };
222
+ }
223
+ if (risk.kind === 'high' && approval !== 'typed') {
224
+ throw new AppError(4, 'High-risk commands require interactive confirmation.');
225
+ }
226
+ if (!('executable' in risk))
227
+ throw new AppError(4, risk.reason);
228
+ const result = await (captured
229
+ ? execute(risk.executable, risk.args, cwd, captured)
230
+ : execute(risk.executable, risk.args, cwd));
231
+ record(id, 'run', result.outcome, result.exitCode);
232
+ if (result.outcome === 'interrupted')
233
+ throw new AppError(130, 'Command interrupted.');
234
+ if (result.outcome === 'failed') {
235
+ throw new AppError(6, 'Command failed (child exit code: ' + (result.exitCode ?? 'terminated by signal') + ').');
236
+ }
237
+ return { kind: 'ran', exitCode: result.exitCode };
238
+ }
239
+ return {
240
+ list,
241
+ candidates,
242
+ show,
243
+ match,
244
+ create,
245
+ edit,
246
+ remove,
247
+ tag,
248
+ variables,
249
+ render,
250
+ prepare,
251
+ copy: copyCommand,
252
+ run,
253
+ };
254
+ }
@@ -0,0 +1,153 @@
1
+ import { AppError } from '../../shared/errors.js';
2
+ /** 将占位符与字面文本拆开,先在模板层统一验证默认值和变量名。 */
3
+ export function parseTemplate(source) {
4
+ if (!source.trim())
5
+ throw new AppError(2, 'Command template must not be empty.');
6
+ if (source.includes('\0') || source.includes('\x1b')) {
7
+ throw new AppError(2, 'Command template contains a control character.');
8
+ }
9
+ const parts = [];
10
+ const variables = new Map();
11
+ const expression = /\{\{([A-Za-z_][A-Za-z0-9_]*)(?::([^{}\r\n]*))?\}\}/gu;
12
+ const appendLiteral = (literal) => {
13
+ if (literal.includes('{{') || literal.includes('}}')) {
14
+ throw new AppError(2, 'Invalid template variable. Use {{name}} or {{name:default}}.');
15
+ }
16
+ if (literal)
17
+ parts.push(literal);
18
+ };
19
+ let offset = 0;
20
+ for (const match of source.matchAll(expression)) {
21
+ appendLiteral(source.slice(offset, match.index));
22
+ const name = match[1];
23
+ const fallback = match[2];
24
+ if (fallback !== undefined)
25
+ checkValue(name, fallback);
26
+ const previous = variables.get(name);
27
+ if (previous?.fallback !== undefined &&
28
+ fallback !== undefined &&
29
+ previous.fallback !== fallback) {
30
+ throw new AppError(2, 'Conflicting defaults for variable ' + name + '.');
31
+ }
32
+ const entry = { name, fallback: fallback ?? previous?.fallback };
33
+ variables.set(name, entry);
34
+ parts.push(entry);
35
+ offset = match.index + match[0].length;
36
+ }
37
+ appendLiteral(source.slice(offset));
38
+ return { parts, variables: [...variables.values()] };
39
+ }
40
+ function checkValue(name, value) {
41
+ if ([...value].some((char) => char.charCodeAt(0) < 32 || char.charCodeAt(0) === 127)) {
42
+ throw new AppError(2, 'Variable ' + name + ' must not contain control characters.');
43
+ }
44
+ }
45
+ export function parseAssignments(entries = []) {
46
+ const values = new Map();
47
+ for (const entry of entries) {
48
+ const separator = entry.indexOf('=');
49
+ const name = entry.slice(0, separator);
50
+ if (separator < 1 || !/^[A-Za-z_][A-Za-z0-9_]*$/u.test(name)) {
51
+ throw new AppError(2, 'Use --var name=value for each template variable.');
52
+ }
53
+ if (values.has(name))
54
+ throw new AppError(2, 'Variable ' + name + ' was supplied more than once.');
55
+ const value = entry.slice(separator + 1);
56
+ checkValue(name, value);
57
+ values.set(name, value);
58
+ }
59
+ return values;
60
+ }
61
+ export function resolveTemplate(template, values) {
62
+ const known = new Set(template.variables.map(({ name }) => name));
63
+ for (const [name, value] of values) {
64
+ if (!known.has(name))
65
+ throw new AppError(2, 'Unknown template variable ' + name + '.');
66
+ checkValue(name, value);
67
+ }
68
+ const resolved = new Map();
69
+ const missing = [];
70
+ for (const { name, fallback } of template.variables) {
71
+ const value = values.get(name) ?? fallback;
72
+ if (value === undefined)
73
+ missing.push(name);
74
+ else
75
+ resolved.set(name, value);
76
+ }
77
+ return { resolved, missing };
78
+ }
79
+ export function renderTemplate(template, values) {
80
+ const { resolved, missing } = resolveTemplate(template, values);
81
+ if (missing.length)
82
+ throw new AppError(2, 'Supply missing template variables with --var: ' + missing.join(', ') + '.');
83
+ return {
84
+ text: template.parts
85
+ .map((part) => (typeof part === 'string' ? part : resolved.get(part.name)))
86
+ .join(''),
87
+ values: resolved,
88
+ };
89
+ }
90
+ /** 变量直接写入当前参数槽,永远不会回到分词器被解析成语法。 */
91
+ export function tokenize(template, values) {
92
+ const args = [];
93
+ let current;
94
+ let quote;
95
+ function append(value, variable = false) {
96
+ current ??= { value: '', variablePrefix: false, hasVariable: false };
97
+ if (variable && !current.value.length)
98
+ current.variablePrefix = true;
99
+ if (variable)
100
+ current.hasVariable = true;
101
+ current.value += value;
102
+ }
103
+ function end() {
104
+ if (current)
105
+ args.push(current);
106
+ current = undefined;
107
+ }
108
+ for (const part of template.parts) {
109
+ if (typeof part !== 'string') {
110
+ append(values.get(part.name), true);
111
+ continue;
112
+ }
113
+ for (let index = 0; index < part.length; index++) {
114
+ const char = part[index];
115
+ const next = part[index + 1];
116
+ if (char === '\r' || char === '\n')
117
+ return { args, unsupported: 'Multiline shell syntax' };
118
+ if (char === '\\' &&
119
+ next &&
120
+ quote !== "'" &&
121
+ (next === quote || (!quote && /[ '"\\\t]/u.test(next)))) {
122
+ append(next);
123
+ index++;
124
+ }
125
+ else if (quote) {
126
+ if (char === quote)
127
+ quote = undefined;
128
+ else if (quote === '"' && (char === '$' || char === '`')) {
129
+ return { args, unsupported: 'Shell expansion' };
130
+ }
131
+ else
132
+ append(char);
133
+ }
134
+ else if (char === "'" || char === '"') {
135
+ quote = char;
136
+ append('');
137
+ }
138
+ else if (/\s/u.test(char)) {
139
+ end();
140
+ }
141
+ else if (/[|&;<>$`*?()[\]~%]/u.test(char)) {
142
+ return { args, unsupported: 'Shell syntax or expansion' };
143
+ }
144
+ else {
145
+ append(char);
146
+ }
147
+ }
148
+ }
149
+ if (quote)
150
+ return { args, unsupported: 'Unclosed command quote' };
151
+ end();
152
+ return { args };
153
+ }
@@ -0,0 +1,53 @@
1
+ import { and, eq, desc, isNull, sql } from 'drizzle-orm';
2
+ import { decisions, decisionReviews, entityLinks, entityTags, projects, } from '../../infrastructure/database/schema.js';
3
+ import { inScope } from '../../shared/query.js';
4
+ export function decisionRepository(db) {
5
+ function detailQuery() {
6
+ return db
7
+ .select({
8
+ decision: decisions,
9
+ projectName: projects.name,
10
+ reviewed: sql `exists (select 1 from ${decisionReviews}
11
+ where ${decisionReviews.decisionId} = ${decisions.id} and ${decisionReviews.deletedAt} is null)`,
12
+ })
13
+ .from(decisions)
14
+ .leftJoin(projects, eq(decisions.projectId, projects.id));
15
+ }
16
+ return {
17
+ byId: (id) => db
18
+ .select()
19
+ .from(decisions)
20
+ .where(and(eq(decisions.id, id), isNull(decisions.deletedAt)))
21
+ .get(),
22
+ detail: (id) => detailQuery()
23
+ .where(and(eq(decisions.id, id), isNull(decisions.deletedAt)))
24
+ .get(),
25
+ list: (projectId, scope) => detailQuery()
26
+ .where(and(isNull(decisions.deletedAt), inScope(decisions.projectId, projectId, scope)))
27
+ .all(),
28
+ create: (row) => db.insert(decisions).values(row).run(),
29
+ edit: (id, values) => db.update(decisions).set(values).where(eq(decisions.id, id)).run(),
30
+ remove: (id, at) => {
31
+ db.update(decisions).set({ deletedAt: at, updatedAt: at }).where(eq(decisions.id, id)).run();
32
+ db.update(decisionReviews)
33
+ .set({ deletedAt: at })
34
+ .where(and(eq(decisionReviews.decisionId, id), isNull(decisionReviews.deletedAt)))
35
+ .run();
36
+ db.update(entityTags)
37
+ .set({ deletedAt: at, updatedAt: at })
38
+ .where(and(eq(entityTags.decisionId, id), isNull(entityTags.deletedAt)))
39
+ .run();
40
+ db.update(entityLinks)
41
+ .set({ deletedAt: at, updatedAt: at })
42
+ .where(and(eq(entityLinks.decisionId, id), isNull(entityLinks.deletedAt)))
43
+ .run();
44
+ },
45
+ append: (review) => db.insert(decisionReviews).values(review).run(),
46
+ history: (id) => db
47
+ .select()
48
+ .from(decisionReviews)
49
+ .where(and(eq(decisionReviews.decisionId, id), isNull(decisionReviews.deletedAt)))
50
+ .orderBy(desc(decisionReviews.reviewedAt), desc(decisionReviews.id))
51
+ .all(),
52
+ };
53
+ }