@starci/eslint-grammar-core 0.22.0 → 0.23.1

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 (69) hide show
  1. package/CHANGELOG.md +8 -0
  2. package/dist/lib/app-shell-create.js +2 -2
  3. package/package.json +4 -2
  4. package/runtime/bundle.json +2 -68
  5. package/runtime/engine/by-code-unit.mjs +0 -12
  6. package/runtime/engine/config.mjs +0 -461
  7. package/runtime/engine/invalid-config.mjs +0 -15
  8. package/runtime/engine/model-config.mjs +0 -112
  9. package/runtime/engine/orca-config.mjs +0 -34
  10. package/runtime/engine/plain-object.mjs +0 -5
  11. package/runtime/engine/release-config.mjs +0 -32
  12. package/runtime/engine/removed-vocabulary.mjs +0 -27
  13. package/runtime/engine/resources-config.mjs +0 -59
  14. package/runtime/engine/runtime-root.mjs +0 -138
  15. package/runtime/engine/secrets.mjs +0 -202
  16. package/runtime/engine/sonar-config.mjs +0 -24
  17. package/runtime/engine/yaml.mjs +0 -161
  18. package/runtime/knowledge/grammars/core/playbook.yaml +0 -1198
  19. package/runtime/knowledge/grammars/index.yaml +0 -114
  20. package/runtime/knowledge/hfs/canon-pins.yaml +0 -720
  21. package/runtime/knowledge/hfs/rules.yaml +0 -6760
  22. package/runtime/knowledge/hfs/slots.yaml +0 -2783
  23. package/runtime/knowledge/ui/presentation/font.yaml +0 -101
  24. package/runtime/knowledge/ui/presentation/padding.yaml +0 -217
  25. package/runtime/modules/kernel/removed-vocabulary.yaml +0 -458
  26. package/runtime/modules/models/registry.yaml +0 -221
  27. package/runtime/modules/models/runtimes.yaml +0 -556
  28. package/runtime/modules/models/tiers.yaml +0 -66
  29. package/runtime/scripts/hfs/allows.mjs +0 -77
  30. package/runtime/scripts/hfs/architecture/component-tiers.mjs +0 -161
  31. package/runtime/scripts/hfs/architecture/config.mjs +0 -407
  32. package/runtime/scripts/hfs/architecture/root-packages.mjs +0 -78
  33. package/runtime/scripts/hfs/architecture/side-boundary.mjs +0 -13
  34. package/runtime/scripts/hfs/architecture/type-context.mjs +0 -335
  35. package/runtime/scripts/hfs/architecture/typescript.mjs +0 -477
  36. package/runtime/scripts/hfs/declaration-shape.mjs +0 -196
  37. package/runtime/scripts/hfs/declaration-slots.mjs +0 -89
  38. package/runtime/scripts/hfs/edition-slots.mjs +0 -80
  39. package/runtime/scripts/hfs/manifest-shape.mjs +0 -474
  40. package/runtime/scripts/hfs/param-names.mjs +0 -13
  41. package/runtime/scripts/hfs/rule-catalog.mjs +0 -458
  42. package/runtime/scripts/hfs/rule-params-shape.mjs +0 -103
  43. package/runtime/scripts/hfs/slot-app-view.mjs +0 -97
  44. package/runtime/scripts/hfs/slot-classify.mjs +0 -69
  45. package/runtime/scripts/hfs/slot-errors.mjs +0 -12
  46. package/runtime/scripts/hfs/slot-imports.mjs +0 -98
  47. package/runtime/scripts/hfs/slot-manifest-shape.mjs +0 -111
  48. package/runtime/scripts/hfs/slot-match.mjs +0 -164
  49. package/runtime/scripts/hfs/slot-path.mjs +0 -6
  50. package/runtime/scripts/hfs/slot-required.mjs +0 -95
  51. package/runtime/scripts/hfs/slot-semantic-problems.mjs +0 -175
  52. package/runtime/scripts/hfs/slot-side-problems.mjs +0 -32
  53. package/runtime/scripts/hfs/slots.mjs +0 -306
  54. package/runtime/scripts/hfs/typescript-programs.mjs +0 -95
  55. package/runtime/scripts/hfs/view.mjs +0 -180
  56. package/runtime/scripts/lib/glob.mjs +0 -32
  57. package/runtime/scripts/lib/grammar-lint.mjs +0 -57
  58. package/runtime/scripts/lib/i18n.mjs +0 -82
  59. package/runtime/scripts/lib/json-clone.mjs +0 -70
  60. package/runtime/scripts/lib/json.mjs +0 -44
  61. package/runtime/scripts/lib/list.mjs +0 -26
  62. package/runtime/scripts/lib/path-key.mjs +0 -124
  63. package/runtime/scripts/lib/read-text.mjs +0 -47
  64. package/runtime/scripts/lib/regex.mjs +0 -3
  65. package/runtime/scripts/lib/source-phrases.mjs +0 -34
  66. package/runtime/scripts/lib/ts-analysis.mjs +0 -39
  67. package/runtime/scripts/lib/ts-ast.mjs +0 -63
  68. package/runtime/scripts/lib/walk.mjs +0 -45
  69. package/runtime/scripts/lib/yaml-cached.mjs +0 -14
@@ -1,180 +0,0 @@
1
- // hfs-view.mjs - the frozen view of one side of an app (be/ or fe/, the side folder as its root) that the lint factories hand
2
- // their rules (`settings.starci.hfs`). Both @starci/eslint-canon-be and @starci/eslint-canon-fe ship a byte copy of this file in their
3
- // runtime/ bundle (scripts/hfs/sync-runtime.mjs), so a path-scoped rule in either package asks the SAME resolver the
4
- // architecture machine and `starci app check` use, and never tests a path with a regular expression of its own.
5
- import fs from 'node:fs';
6
- import path from 'node:path';
7
- import { allowsFile } from './allows.mjs';
8
- import { openHfs } from './slots.mjs';
9
- import { ROOT_PACKAGE_SLOTS } from './architecture/root-packages.mjs';
10
- const posix = (p) => String(p).replaceAll('\\', '/');
11
- const isAbsoluteAny = (text) => path.isAbsolute(text) || /^[A-Za-z]:\//.test(text);
12
- /**
13
- * The view rules read, over an opened resolver.
14
- *
15
- * @param {object} opened - The result of `openHfs` (manifest, repo and resolver methods).
16
- * @param {string} repoRoot - The absolute repository root.
17
- * @returns {object} The frozen view: profile, apps, connections, patterns, ruleParams, relative, classify, slotOf, tierOf, ownerOf, slot.
18
- */
19
- function hfsView(opened, repoRoot) {
20
- const rel = (file) => {
21
- const text = posix(file);
22
- if (!isAbsoluteAny(text))
23
- return text.replace(/^\.\//, '');
24
- return posix(path.relative(repoRoot, file));
25
- };
26
- const slotCache = new Map();
27
- const classify = (file) => {
28
- const key = rel(file);
29
- if (!slotCache.has(key))
30
- slotCache.set(key, opened.classifyPath(key));
31
- return slotCache.get(key);
32
- };
33
- return Object.freeze({
34
- repoRoot,
35
- profile: opened.repo.profile,
36
- side: opened.repo.side ?? null,
37
- edition: opened.repo.edition ?? 'full',
38
- ...(opened.repo.grammar === undefined ? {} : { grammar: opened.repo.grammar }),
39
- apps: opened.repo.apps,
40
- connections: opened.repo.connections,
41
- patterns: Object.freeze([...(opened.repo.patterns ?? [])]),
42
- ruleParams: opened.ruleParams(),
43
- /** The repository-relative, forward-slash form of a linted filename. */
44
- relative: rel,
45
- /** The classification of a file: `{ slot, tier, owner?, bindings? ... }` or a no-slot status. */
46
- classify,
47
- /** The slot id that owns a file, or null when no slot does. */
48
- slotOf: (file) => classify(file).slot ?? null,
49
- /** The tier of a file, or null. */
50
- tierOf: (file) => opened.tierOf(rel(file)) ?? null,
51
- /** The owner root of a file, or null. */
52
- ownerOf: (file) => opened.ownerOf(rel(file))?.root ?? null,
53
- /** What the slot that owns a file says about it: `{ slot, root, relative, allowed, entry?, forbiddenBy?, allows }`, or null when the slot names no `allows`. */
54
- allows: (file) => allowsFile(opened, rel(file)),
55
- /** A slot definition by id. */
56
- slot: (id) => opened.slot(id),
57
- });
58
- }
59
- /**
60
- * The view of the app folder on disk at `repoRoot`, against the manifest under `runtimeRoot`: a side folder (be/, fe/) finds the
61
- * app-root hfs.json one level up and gets that side's view, so every linted file below it is judged by its own side's slots.
62
- *
63
- * @param {{ runtimeRoot: string, repoRoot: string }} input - Where the manifest copy lives and the side folder (or app root).
64
- * @returns {object} The frozen view.
65
- */
66
- export const openHfsView = ({ runtimeRoot, repoRoot }) => hfsView(openHfs({ root: runtimeRoot, repoRoot }), repoRoot);
67
- /**
68
- * The view of one side of an in-memory app declaration (rule tests): no file is read except the manifest.
69
- *
70
- * @param {{ runtimeRoot: string, declaration: object, repoRoot: string, side: string }} input - Manifest root, hfs.json object, the linted side folder, its side.
71
- * @returns {object} The frozen view.
72
- */
73
- export const declaredHfsView = ({ runtimeRoot, declaration, repoRoot, side }) => hfsView(openHfs({ root: runtimeRoot, declaration, side }), repoRoot);
74
- const CONTRACT_KEYS = ['errorBase', 'outcome'];
75
- /**
76
- * The contract of the package at `packageDir` (app-root relative, `packages/<pkg>`), read from the `starci` key of its manifest. A
77
- * declaration that is not `{ name, file }` with an identifier name and a file inside `src/` stops the lint, because a rule must not guess.
78
- *
79
- * @param {string} repoRoot - The absolute app root.
80
- * @param {string} packageDir - The package folder, relative to the app root.
81
- * @returns {object} The declared error base and outcome union, each with its file relative to the app root.
82
- */
83
- export const readPackageContract = (repoRoot, packageDir) => {
84
- const manifestPath = path.join(repoRoot, packageDir, 'package.json');
85
- const manifest = (fs.existsSync(manifestPath) ? JSON.parse(fs.readFileSync(manifestPath, 'utf8')) : null);
86
- const declared = manifest?.starci;
87
- if (declared === undefined)
88
- return {};
89
- if (typeof declared !== 'object' || declared === null)
90
- throw new Error(`${packageDir}/package.json: "starci" is an object ({ errorBase, outcome })`);
91
- const contract = {};
92
- for (const key of CONTRACT_KEYS) {
93
- const entry = declared[key];
94
- if (entry === undefined)
95
- continue;
96
- const { name, file } = (typeof entry === 'object' && entry !== null ? entry : {});
97
- if (typeof name !== 'string' || !/^[A-Za-z_$][\w$]*$/.test(name) || typeof file !== 'string' || !/^src\/(?:[\w.-]+\/)*[\w.-]+\.ts$/.test(file)) {
98
- throw new Error(`${packageDir}/package.json: "starci.${key}" is { "name": "<Identifier>", "file": "src/<path>.ts" }`);
99
- }
100
- contract[key] = Object.freeze({ name, file: `${packageDir}/${file}` });
101
- }
102
- return Object.freeze(contract);
103
- };
104
- /**
105
- * The view of the root workspace packages of an app (`packages/<pkg>/src/**`, slots app.packages and app.module-registry), as the lint of one
106
- * side sees them: the rule parameters, the apps and the Grammar of `side` (a package is judged by the laws of the side whose subpath a file
107
- * sits in), and the paths of the APP ROOT (`repoRoot` is the app root, not a side folder). The slots answer for the root paths; a file of a
108
- * package is of the tier `package` and has no owner: the owner laws (one `index.ts` per owner root) are the module folders', a package's public
109
- * surface being the `exports` of its manifest.
110
- *
111
- * @param {object} opened - The result of `openHfs` for the app root (profile app, both sides resolved).
112
- * @param {string} repoRoot - The absolute app root.
113
- * @param {string} side - `be` or `fe`: the side whose laws the file is judged by.
114
- * @returns {object} The frozen view: the profile of the side over the paths of the app root.
115
- */
116
- function packagesView(opened, repoRoot, side) {
117
- const scope = opened.sides?.[side];
118
- const sideRepo = opened.repo.sides?.[side];
119
- if (scope === undefined || sideRepo === undefined)
120
- throw new Error('the view of the root packages needs the declaration of an app with both sides');
121
- const rel = (file) => {
122
- const text = posix(file);
123
- return isAbsoluteAny(text) ? posix(path.relative(repoRoot, file)) : text.replace(/^\.\//, '');
124
- };
125
- const cache = new Map();
126
- const classify = (file) => {
127
- const key = rel(file);
128
- if (!cache.has(key))
129
- cache.set(key, opened.classifyPath(key));
130
- return cache.get(key);
131
- };
132
- const packageOf = (file) => {
133
- const slot = classify(file).slot;
134
- const relative = rel(file);
135
- return slot !== undefined && ROOT_PACKAGE_SLOTS.has(slot) ? relative.split('/').slice(0, 2).join('/') : null;
136
- };
137
- const contracts = new Map();
138
- const packageContract = (file) => {
139
- const dir = packageOf(file);
140
- if (dir === null)
141
- return null;
142
- if (!contracts.has(dir))
143
- contracts.set(dir, readPackageContract(repoRoot, dir));
144
- return contracts.get(dir);
145
- };
146
- return Object.freeze({
147
- repoRoot,
148
- profile: side,
149
- side,
150
- edition: opened.repo.edition ?? 'full',
151
- ...(sideRepo.grammar === undefined ? {} : { grammar: sideRepo.grammar }),
152
- apps: sideRepo.apps,
153
- connections: sideRepo.connections,
154
- patterns: Object.freeze([...(sideRepo.patterns ?? [])]),
155
- ruleParams: scope.ruleParams(),
156
- relative: rel,
157
- classify,
158
- slotOf: (file) => classify(file).slot ?? null,
159
- tierOf: (file) => (packageOf(file) === null ? null : 'package'),
160
- // A package is no owner of the module laws (one index.ts at the owner root): its public surface is the `exports` of its manifest, so no file of it has an owner.
161
- ownerOf: () => null,
162
- allows: (file) => allowsFile(opened, rel(file)),
163
- slot: (id) => opened.slot(id),
164
- packageContract,
165
- });
166
- }
167
- /**
168
- * The view of the root packages of the app at `repoRoot` (the app root, where the root `eslint.config.mjs` lives), for the laws of `side`.
169
- *
170
- * @param {{ runtimeRoot: string, repoRoot: string, side: string }} input - Where the manifest copy lives, the app root, and the side whose laws apply.
171
- * @returns {object} The frozen view.
172
- */
173
- export const openPackagesHfsView = ({ runtimeRoot, repoRoot, side }) => packagesView(openHfs({ root: runtimeRoot, repoRoot }), repoRoot, side);
174
- /**
175
- * The view of the root packages of an in-memory app declaration (rule tests): no file is read except the manifest.
176
- *
177
- * @param {{ runtimeRoot: string, declaration: object, repoRoot: string, side: string }} input - Manifest root, the app hfs.json object, the app root and the side.
178
- * @returns {object} The frozen view.
179
- */
180
- export const declaredPackagesHfsView = ({ runtimeRoot, declaration, repoRoot, side }) => packagesView(openHfs({ root: runtimeRoot, declaration }), repoRoot, side);
@@ -1,32 +0,0 @@
1
- // glob.mjs — the path-glob subset ESLint, SonarQube and the scoped-lint config share: `**` spans directories,
2
- // `*` and `?` stay inside one segment, `{a,b}` alternates.
3
- import { posixPath } from './path-key.mjs';
4
- /** Every alternative a `{a,b}` pattern spells, braces expanded left to right. */
5
- export function braceVariants(value) {
6
- const match = /\{([^{}]+)\}/.exec(value);
7
- return match ? match[1].split(',').flatMap((part) => braceVariants(`${value.slice(0, match.index)}${part}${value.slice(match.index + match[0].length)}`)) : [value];
8
- }
9
- /** The anchored RegExp of one brace-free glob, read as a posix path (backslashes and a leading './' folded). */
10
- export function globExpression(value) {
11
- const input = posixPath(value);
12
- let source = '';
13
- for (let i = 0; i < input.length; i += 1) {
14
- const c = input.charAt(i);
15
- if (c === '*' && input[i + 1] === '*') {
16
- i += 1;
17
- if (input[i + 1] === '/') {
18
- i += 1;
19
- source += '(?:.*/)?';
20
- }
21
- else
22
- source += '.*';
23
- }
24
- else if (c === '*')
25
- source += '[^/]*';
26
- else if (c === '?')
27
- source += '[^/]';
28
- else
29
- source += /[.+^${}()|[\]\\]/.test(c) ? `\\${c}` : c;
30
- }
31
- return new RegExp(`^${source}$`);
32
- }
@@ -1,57 +0,0 @@
1
- // Grammar-family lint selection reads the family catalog; an absent selection never chooses a family.
2
- import fs from 'node:fs';
3
- import { parseYamlCached } from './yaml-cached.mjs';
4
- const CATALOG_FILE = new URL('../../knowledge/grammars/index.yaml', import.meta.url);
5
- function readCatalog() {
6
- return parseYamlCached(fs.readFileSync(CATALOG_FILE, 'utf8'));
7
- }
8
- function selectedFamily(family) {
9
- if (typeof family !== 'string' || !family.trim())
10
- throw new Error('sides.fe.grammar must explicitly name the selected Grammar family');
11
- const catalog = readCatalog();
12
- const matches = (catalog.families ?? []).filter(entry => entry.id === family);
13
- if (matches.length !== 1)
14
- throw new Error(`Grammar family ${family} has no declared lint contract in knowledge/grammars/index.yaml`);
15
- return { catalog, selected: matches[0] };
16
- }
17
- /**
18
- * Resolve a selection to its declared family id; only a catalog family id resolves, there are no aliases.
19
- * @param {string} family - The id an app or caller names (sides.fe.grammar).
20
- * @returns {{ id: string }} The declared family id.
21
- */
22
- export function resolveGrammarFamily(family) {
23
- return Object.freeze({ id: selectedFamily(family).selected.id });
24
- }
25
- /** The explicitly selected authored family entry; callers share the catalog lookup rather than inferring a family. */
26
- export function grammarFamilyFor(family) {
27
- return Object.freeze(selectedFamily(family).selected);
28
- }
29
- /** The declared family's lint contract, including an explicit null package when that family has no rules. */
30
- export function grammarLintFor(family) {
31
- const { selected } = selectedFamily(family);
32
- if (!selected.lint || !Object.hasOwn(selected.lint, 'package')) {
33
- throw new Error(`Grammar family ${family} has no declared lint contract in knowledge/grammars/index.yaml`);
34
- }
35
- const lint = selected.lint;
36
- if (lint.package === null)
37
- return Object.freeze({ family: selected.id, package: null });
38
- if (typeof lint.package !== 'string' || !lint.package.startsWith('@starci/eslint-grammar-')
39
- || typeof lint.factory !== 'string' || !/^[a-zA-Z][a-zA-Z0-9]*$/.test(lint.factory)
40
- || typeof lint.prefix !== 'string' || !/^[a-z][a-z0-9-]*$/.test(lint.prefix)) {
41
- throw new Error(`Grammar family ${family} has an invalid lint contract in knowledge/grammars/index.yaml`);
42
- }
43
- return Object.freeze({ family: selected.id, package: lint.package, factory: lint.factory, prefix: lint.prefix });
44
- }
45
- /** The selected family's shared component/export contract, resolved through its catalog reference. */
46
- export function grammarContractFor(family) {
47
- const { catalog, selected } = selectedFamily(family);
48
- const owners = (catalog.families ?? []).filter(entry => entry.id === selected.contractRef);
49
- const contract = owners.length === 1 ? owners[0]?.componentContract : null;
50
- if (!contract || typeof contract.package !== 'string' || !contract.package
51
- || typeof contract.entry !== 'string' || !contract.entry.startsWith(`${contract.package}/`)
52
- || typeof contract.styleEntry !== 'string' || !contract.styleEntry.startsWith(`${contract.package}/`)
53
- || !Array.isArray(contract.peers) || !contract.peers.every(peer => typeof peer === 'string' && peer.trim())) {
54
- throw new Error(`Grammar family ${family} has no valid component contract in knowledge/grammars/index.yaml`);
55
- }
56
- return Object.freeze({ ...contract, peers: Object.freeze([...contract.peers]) });
57
- }
@@ -1,82 +0,0 @@
1
- // i18n.mjs - the ONE mechanism for text the owner must read in Vietnamese. Runtime source, comments and messages are English;
2
- // a message the owner reads (a Telegram notice, a why line, a progress report) is written once in English at its call site and
3
- // translated through a DECLARED catalog keyed from that English source: modules/i18n/messages/<area>.yaml, a list of
4
- // `{en, vi}` entries. Each area belongs to a scope: `runtime` for Node callers or `ui` for the generated browser catalog.
5
- // The `vi` field is declared in scripts/lib/language.mjs, so it is the only Vietnamese source. There is no per-module
6
- // `TEXT.vi` table and no second catalog mechanism.
7
- //
8
- // const tr = translator(config.language); // 'vi' translates, anything else returns the English source
9
- // tr('Workflow {id} needs your decision', { id })
10
- //
11
- // A placeholder is `{name}`; the English and the Vietnamese of one entry carry exactly the same placeholders
12
- // (scripts/checks/check-i18n-catalog.mjs). An English source with no entry is returned as is: a missing translation degrades
13
- // to English, never to a blank.
14
- import { byCodeUnit } from './list.mjs';
15
- import { escapeRegExp } from './regex.mjs';
16
- import fs from 'node:fs';
17
- import path from 'node:path';
18
- import { skillRoot } from '../../engine/runtime-root.mjs';
19
- import { parseYaml } from '../../engine/yaml.mjs';
20
- import { DEFAULT_OWNER_LANGUAGE, loadConfig } from '../../engine/config.mjs';
21
- export const CATALOG_DIR = 'modules/i18n/messages';
22
- export const PLACEHOLDER = /\{([A-Za-z_]\w*)\}/g;
23
- const cache = new Map();
24
- /** The catalog files of a runtime root: repository-relative paths, sorted. */
25
- export function catalogFiles(root = skillRoot) {
26
- const dir = path.join(root, ...CATALOG_DIR.split('/'));
27
- try {
28
- return fs.readdirSync(dir).filter((name) => /\.ya?ml$/.test(name)).sort().map((name) => `${CATALOG_DIR}/${name}`);
29
- }
30
- catch {
31
- return [];
32
- }
33
- }
34
- /** Every entry in one catalog scope: `[{ en, vi, area, scope, file }]`. */
35
- export function catalogEntries(root = skillRoot, { scope = 'runtime' } = {}) {
36
- return catalogFiles(root).flatMap((rel) => {
37
- const doc = parseYaml(fs.readFileSync(path.join(root, ...rel.split('/')), 'utf8'));
38
- const documentScope = typeof doc?.scope === 'string' ? doc.scope : 'runtime';
39
- if (documentScope !== scope)
40
- return [];
41
- return (Array.isArray(doc?.messages) ? doc.messages : []).map((entry) => ({
42
- en: entry?.en, vi: entry?.vi, area: doc?.area, scope: documentScope, file: rel,
43
- }));
44
- });
45
- }
46
- /** One scoped catalog as a Map from the English source to the Vietnamese text (cached per root and scope). */
47
- export function loadCatalog(root = skillRoot, { scope = 'runtime' } = {}) {
48
- const key = `${root}\0${scope}`;
49
- if (!cache.has(key))
50
- cache.set(key, new Map(catalogEntries(root, { scope }).filter((e) => typeof e.en === 'string' && typeof e.vi === 'string').map((e) => [e.en, e.vi])));
51
- return cache.get(key);
52
- }
53
- /** The names each `pattern` match captures (group 1) in `text`, in match order (`sort` sorts them). */
54
- export const captureNames = (text, pattern, { sort = false } = {}) => {
55
- const names = [...String(text).matchAll(pattern)].map((m) => m[1]);
56
- return sort ? names.sort(byCodeUnit) : names;
57
- };
58
- /** The names of the placeholders of a message. */
59
- export const placeholdersOf = (text) => captureNames(text, PLACEHOLDER, { sort: true });
60
- /** `text` with each `{name}` replaced by vars[name] (an unknown name is left as written). */
61
- export const fill = (text, vars = {}) => String(text).replace(PLACEHOLDER, (whole, name) => (Object.hasOwn(vars, name) ? String(vars[name]) : whole));
62
- /** The message `en` in `language` (`vi` translates through the catalog; any other language is the English source). */
63
- export function translate(en, vars = {}, { language = DEFAULT_OWNER_LANGUAGE, root = skillRoot, scope = 'runtime' } = {}) {
64
- const vi = language === 'vi' ? loadCatalog(root, { scope }).get(en) : undefined;
65
- return fill(vi ?? en, vars);
66
- }
67
- /** The owner's language (config.yaml `language`); `fallback` when there is no readable config (DEFAULT_OWNER_LANGUAGE of engine/config.mjs). */
68
- export function ownerLanguage(fallback = DEFAULT_OWNER_LANGUAGE) {
69
- try {
70
- return loadConfig()?.language ?? fallback;
71
- }
72
- catch {
73
- return fallback;
74
- }
75
- }
76
- /** A translator bound to one language: `tr(en, vars)`. */
77
- export const translator = (language = DEFAULT_OWNER_LANGUAGE, { root = skillRoot, scope = 'runtime' } = {}) => (en, vars = {}) => translate(en, vars, { language, root, scope });
78
- /**
79
- * A pattern source matching `en` in the owner's language or in English: each language's rendering of the English source,
80
- * escaped, with the placeholder `slot` (a placeholder name of `en`) replaced by `slotPattern`. Never hardcodes a spelling.
81
- */
82
- export const translatedPattern = (en, slot, slotPattern, languages = ['en', 'vi']) => `(?:${languages.map((language) => escapeRegExp(translate(en, { [slot]: '@@' }, { language })).replace('@@', slotPattern)).join('|')})`;
@@ -1,70 +0,0 @@
1
- // json-clone.mjs — a deep copy that keeps exactly what survives a JSON text and nothing else: the plain-data
2
- // copy of a value, detached from every reference, frozen state and class of the original. `structuredClone` keeps
3
- // what JSON drops (undefined members, Dates, Maps, sparse holes) and refuses what JSON accepts (functions,
4
- // `toJSON` objects), so it is not a substitute; this walks the value once under the JSON.stringify rules.
5
- /** The boxed primitives JSON.stringify unwraps: recognised by the internal slot a valueOf call reads, as JSON does. */
6
- const BOXED = [
7
- { slot: Number.prototype.valueOf, read: Number },
8
- { slot: String.prototype.valueOf, read: String },
9
- { slot: Boolean.prototype.valueOf, read: (box) => Boolean.prototype.valueOf.call(box) },
10
- { slot: BigInt.prototype.valueOf, read: (box) => BigInt.prototype.valueOf.call(box) },
11
- ];
12
- /** Whether `value` carries the internal slot `slot` reads (a valueOf of that boxed type does not throw on it). */
13
- const hasSlot = (slot, value) => {
14
- try {
15
- slot.call(value);
16
- return true;
17
- }
18
- catch {
19
- return false;
20
- }
21
- };
22
- /** What JSON.stringify takes of `holder[key]`: the toJSON result when there is one, a boxed primitive unwrapped. */
23
- const serialized = (holder, key) => {
24
- let value = holder[key];
25
- if (value !== null && (typeof value === 'object' || typeof value === 'bigint') && typeof value.toJSON === 'function')
26
- value = value.toJSON(key);
27
- if (value === null || typeof value !== 'object')
28
- return value;
29
- const box = BOXED.find((candidate) => hasSlot(candidate.slot, value));
30
- return box ? box.read(value) : value;
31
- };
32
- /** A member JSON leaves out of an object (and writes as null in an array). */
33
- const isAbsent = (value) => value === undefined || typeof value === 'function' || typeof value === 'symbol';
34
- const copyValue = (value, ancestors) => {
35
- if (value === null || typeof value === 'string' || typeof value === 'boolean')
36
- return value;
37
- if (typeof value === 'number')
38
- return Number.isFinite(value) ? value + 0 : null;
39
- if (typeof value === 'bigint')
40
- throw new TypeError('Do not know how to serialize a BigInt');
41
- if (ancestors.includes(value))
42
- throw new TypeError('Converting circular structure to JSON');
43
- const inside = [...ancestors, value];
44
- if (Array.isArray(value)) {
45
- return Array.from({ length: value.length }, (_, index) => {
46
- const item = serialized(value, String(index));
47
- return isAbsent(item) ? null : copyValue(item, inside);
48
- });
49
- }
50
- const holder = value;
51
- const entries = [];
52
- for (const name of Object.keys(holder)) {
53
- const member = serialized(holder, name);
54
- if (!isAbsent(member))
55
- entries.push([name, copyValue(member, inside)]);
56
- }
57
- return Object.fromEntries(entries);
58
- };
59
- /**
60
- * `value` copied as JSON data: members that are undefined, functions or symbols are dropped (an array item becomes
61
- * null), non-finite numbers become null and -0 becomes 0, `toJSON` results replace their objects (a Date becomes its ISO string), boxed
62
- * primitives unwrap, and a cycle or a BigInt throws a TypeError. A value JSON has no text for (undefined, a function,
63
- * a symbol) throws a SyntaxError, as parsing the missing text does.
64
- */
65
- export function jsonClone(value) {
66
- const top = serialized({ '': value }, '');
67
- if (isAbsent(top))
68
- throw new SyntaxError('"undefined" is not valid JSON');
69
- return copyValue(top, []);
70
- }
@@ -1,44 +0,0 @@
1
- // json.mjs — the ledger's forgiving JSON read. Every one of these rows may hold text a peer wrote or a
2
- // truncated payload, so a malformed column is the caller's fallback, never a throw. The parse of the
3
- // literal 'null' is kept as null (callers that want {} instead write `parseJsonOr`).
4
- import { readParsedFile } from './read-text.mjs';
5
- /** `text` as JSON, or `fallback` when it does not parse. */
6
- // reason: JSON parsed from a ledger column or file is an untyped input boundary; each caller narrows what it reads.
7
- export const parseJson = (text, fallback = null) => {
8
- try {
9
- return JSON.parse(text);
10
- }
11
- catch {
12
- return fallback;
13
- }
14
- };
15
- /** `text` as JSON, or `fallback` when it does not parse OR parses to null/undefined. Rows written
16
- * as the literal 'null' read back as the fallback too, so a caller that wants an object gets one. */
17
- // reason: same parsed-JSON boundary as parseJson.
18
- export const parseJsonOr = (text, fallback = {}) => parseJson(text) ?? fallback;
19
- /** A jobs/events row spread with `payload`: the row's payload_json parsed via parseJsonOr
20
- * (`fallback` defaults to {}). Pass fallback null to keep a raw parseJson result, nulls included. */
21
- // reason: same parsed-JSON boundary as parseJson.
22
- export const withPayload = (row, fallback = {}) => (row ? { ...row, payload: parseJsonOr(row.payload_json, fallback) } : row);
23
- /** `file` read and parsed as JSON, or `fallback` when the file is missing, unreadable or malformed. */
24
- // reason: same parsed-JSON boundary as parseJson.
25
- export const readJsonFile = (file, fallback = null) => readParsedFile(file, JSON.parse, fallback);
26
- /** `stdout` as JSON: the trimmed text, else its first-{-to-last-} span; null when neither parses. */
27
- // reason: same parsed-JSON boundary as parseJson.
28
- export const jsonFromStdout = (stdout) => {
29
- const text = String(stdout ?? '').trim();
30
- if (!text)
31
- return null;
32
- try {
33
- return JSON.parse(text);
34
- }
35
- catch { /* fall through */ }
36
- const first = text.indexOf('{'), last = text.lastIndexOf('}');
37
- if (first >= 0 && last > first) {
38
- try {
39
- return JSON.parse(text.slice(first, last + 1));
40
- }
41
- catch { /* not json */ }
42
- }
43
- return null;
44
- };
@@ -1,26 +0,0 @@
1
- // list.mjs — the array-or-empty coercion half the scripts re-declared by hand.
2
- // `v` when it already is an array, else []. Scalars are NOT wrapped: a caller that wants
3
- // `[v]` for a lone value writes its own coercion (see contract-version's list).
4
- export const list = (v) => (Array.isArray(v) ? v : []);
5
- /** `v` as an array: itself when already one, [] for null/undefined, else [v]. */
6
- export const asList = (v) => {
7
- if (Array.isArray(v))
8
- return v;
9
- if (v == null)
10
- return [];
11
- return [v];
12
- };
13
- /** The object entries of `v` (a non-array reads as []). */
14
- export const objectList = (v) => (Array.isArray(v) ? v : []).filter((item) => item && typeof item === 'object');
15
- /** Every entry of `v` a non-empty string (`blank: false` also rejects all-whitespace entries). */
16
- export const stringList = (v, { blank = true } = {}) => Array.isArray(v) && v.every((s) => typeof s === 'string' && s.length > 0 && (blank || s.trim().length > 0));
17
- /** A non-empty list of distinct values, all accepted by the supplied predicate. */
18
- export const nonemptyUniqueList = (values, accepts) => Array.isArray(values) && values.length > 0
19
- && values.every((entry) => accepts(entry)) && new Set(values).size === values.length;
20
- /** The items of a `sep`-separated list: trimmed, empties dropped; `dedupe` keeps first occurrences only. */
21
- export const splitList = (v, { sep = ',', dedupe = false } = {}) => {
22
- const items = String(v ?? '').split(sep).map((s) => s.trim()).filter(Boolean);
23
- return dedupe ? [...new Set(items)] : items;
24
- };
25
- // The comparator of a bare `sort()` (UTF-16 code-unit order) is owned by the engine, which cannot import scripts/lib.
26
- export { byCodeUnit } from '../../engine/by-code-unit.mjs';
@@ -1,124 +0,0 @@
1
- // path-key.mjs — spelling and comparing paths the way this host's filesystem does.
2
- import fs from 'node:fs';
3
- import path from 'node:path';
4
- const WIN = process.platform === 'win32';
5
- /** `p` with every backslash turned into a forward slash; null and undefined read as ''. */
6
- export const slash = (p) => String(p ?? '').replaceAll('\\', '/');
7
- /** `text` without its trailing '/' run (a loop: a trailing-run pattern backtracks super-linearly). */
8
- export const trimTrailingSlashes = (text) => {
9
- for (let end = text.length;; end -= 1)
10
- if (end === 0 || text[end - 1] !== '/')
11
- return text.slice(0, end);
12
- };
13
- // A trailing '*' run with the one '/' before it (the glob suffix of 'dir/**'); text without a trailing '*' is unchanged.
14
- const stripTrailingStars = (text) => {
15
- let end = text.length;
16
- while (end > 0 && text[end - 1] === '*')
17
- end -= 1;
18
- if (end === text.length)
19
- return text;
20
- return text.slice(0, end > 0 && text[end - 1] === '/' ? end - 1 : end);
21
- };
22
- /** A relative path in git's spelling: forward slashes, no leading './'. */
23
- export const posixPath = (p) => slash(p).replace(/^\.\//, '');
24
- /** Whether posix `file` is `prefix` itself or under it (`file === prefix || file` starts with `prefix/`). */
25
- export const sameOrUnder = (file, prefix) => file === prefix || file.startsWith(`${prefix}/`);
26
- /** `p` case-folded where the filesystem ignores case (Windows). */
27
- export const foldCase = (p) => (WIN ? p.toLowerCase() : p);
28
- /** Whether two spellings name the same path on this host's filesystem. */
29
- export const samePath = (a, b) => foldCase(a) === foldCase(b);
30
- /**
31
- * A path's comparable identity: absolute, forward slashes, no trailing slash, case-folded on Windows.
32
- * `fold: true` folds case on every platform (a comparison against a lowercase-stored root needs it).
33
- */
34
- export const pathKey = (p, { fold = WIN } = {}) => {
35
- const key = trimTrailingSlashes(slash(path.resolve(p)));
36
- return fold ? key.toLowerCase() : key;
37
- };
38
- /** `a` is `b` or under it, or the reverse: two path spellings whose trees touch. */
39
- export const pathsOverlap = (a, b) => sameOrUnder(a, b) || sameOrUnder(b, a);
40
- /**
41
- * A path-ish string in compare form, options in spelling order:
42
- * `trim` blanks at the ends, `collapse` folds '//' runs to '/', `dot` drops a leading './',
43
- * `glob` strips a trailing glob ('star': '*'/'**' with their slash, 'double': a '/**' only),
44
- * `fold` lowercases. A trailing '/' always goes. Null reads as ''.
45
- * @param {string|number|null|undefined} p
46
- * @param {{trim?: boolean, collapse?: boolean, dot?: boolean, glob?: string|null, fold?: boolean}} [options]
47
- */
48
- export const normPath = (p, { trim = false, collapse = false, dot = false, glob = null, fold = false } = {}) => {
49
- let s = p == null ? '' : String(p);
50
- if (trim)
51
- s = s.trim();
52
- s = slash(s);
53
- if (collapse)
54
- s = s.replace(/\/{2,}/g, '/');
55
- if (dot)
56
- s = s.replace(/^\.\//, '');
57
- if (glob === 'star')
58
- s = stripTrailingStars(s);
59
- else if (glob === 'double')
60
- s = s.replace(/\/\*\*$/, '');
61
- s = trimTrailingSlashes(s);
62
- return fold ? s.toLowerCase() : s;
63
- };
64
- /** A work-relative path in one spelling: forward slashes, no leading ./, no trailing slash. */
65
- export const normWork = (p) => trimTrailingSlashes(String(p ?? '').trim().replaceAll('\\', '/').replace(/^\.\/+/, ''));
66
- /** `p` resolved and dereferenced (realpath where the path exists) — the canonical spelling of a checkout dir. */
67
- export const realPath = (p) => {
68
- const resolved = path.resolve(p);
69
- try {
70
- return fs.realpathSync.native(resolved);
71
- }
72
- catch {
73
- return resolved;
74
- }
75
- };
76
- /** `p` with its nearest existing ancestor dereferenced and the not-yet-created rest appended: a root's canonical spelling before it exists. */
77
- export const canonicalPath = (p) => {
78
- const rest = [];
79
- for (let at = path.resolve(p);; at = path.dirname(at)) {
80
- try {
81
- return path.join(fs.realpathSync.native(at), ...rest);
82
- }
83
- catch { /* not created yet */ }
84
- if (path.dirname(at) === at)
85
- return path.resolve(p);
86
- rest.unshift(path.basename(at));
87
- }
88
- };
89
- /** `p` resolved and case-folded where the filesystem ignores case — the Map key of an absolute path. */
90
- export const resolvedKey = (p) => foldCase(path.resolve(p));
91
- /** Whether `a` and `b` resolve to the same path (always case-folded, so differently-cased spellings count). */
92
- export const sameResolvedPath = (a, b) => pathKey(a, { fold: true }) === pathKey(b, { fold: true });
93
- /**
94
- * Whether `file` sits under `root`; `includeSelf` also admits the root itself. `key` normalizes
95
- * both sides first (e.g. the registry's realpath-folded treeKey) when their spellings need it.
96
- */
97
- export const insidePath = (root, file, { key = (p) => p, includeSelf = false } = {}) => {
98
- const rel = path.relative(key(root), key(file));
99
- return (includeSelf || Boolean(rel)) && !rel.startsWith('..') && !path.isAbsolute(rel);
100
- };
101
- /**
102
- * `candidate` (absolute, or relative to `base`) resolved and dereferenced, required to sit under `base` (or be it):
103
- * the boundary check for a path an operator, an agent or another process hands in. `base` is canonicalised once and the
104
- * candidate is judged below it, so `..` segments and links leading out are refused; returns the canonical path, or throws
105
- * a PATH_OUTSIDE_BASE refusal (`label` names the argument in the message).
106
- */
107
- export const containedPath = (base, candidate, { label = 'path' } = {}) => {
108
- const root = canonicalPath(base);
109
- const resolved = canonicalPath(path.resolve(root, String(candidate ?? '')));
110
- const prefix = root.endsWith(path.sep) ? root : root + path.sep;
111
- if (!insidePath(root, resolved, { includeSelf: true }) || (resolved !== root && !resolved.startsWith(prefix)))
112
- throw Object.assign(new Error(`${label} ${String(candidate)} is outside ${root} [PATH_OUTSIDE_BASE]`), { code: 'PATH_OUTSIDE_BASE' });
113
- return resolved;
114
- };
115
- /**
116
- * A path-ish value (a string or a {path} entry) in relative compare form: trimmed, forward slashes,
117
- * no trailing '/**' glob or slashes, no leading './'; `fold` lowercases for a case-insensitive key.
118
- */
119
- export const normRel = (p, { fold = false } = {}) => {
120
- const s = trimTrailingSlashes(String(typeof p === 'string' ? p : p?.path ?? '').trim().replaceAll('\\', '/').replace(/\/\*\*$/, '')).replace(/^\.\//, '');
121
- return fold ? s.toLowerCase() : s;
122
- };
123
- /** Whether `file` equals or sits under one of `prefixes` (posix spellings; `dot` counts a '.' prefix as covering all). */
124
- export const underAny = (file, prefixes, { dot = false } = {}) => (prefixes ?? []).some((p) => (dot && p === '.') || sameOrUnder(file, p));