@dialecte/cli 0.1.0 → 0.2.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.
@@ -0,0 +1,1745 @@
1
+ // src/lib/api/find-by-path.ts
2
+ function findByPath(params) {
3
+ const path = params.path.replace(/^q\./, "doc.query.");
4
+ const methods = params.indexes.flatMap(
5
+ (index) => index.methods.map((method) => ({ method, packageName: index.package }))
6
+ );
7
+ const exact = methods.filter(({ method }) => routesOf(method).includes(path));
8
+ if (exact.length > 0) return exact;
9
+ return methods.filter(
10
+ ({ method }) => routesOf(method).some((route) => route.endsWith(`.${path}`))
11
+ );
12
+ }
13
+ function routesOf(method) {
14
+ return [method.path, ...method.otherRoutes];
15
+ }
16
+
17
+ // src/lib/skills/api-index.constants.ts
18
+ var TEXT_COLLATOR = new Intl.Collator("en", { sensitivity: "base" });
19
+
20
+ // src/lib/api/find-methods.constants.ts
21
+ var STEM_SUFFIXES = [
22
+ // a verb form keeps a stem of four letters: `copying` → `copy`, but `naming` stays (never `nam`, the noun)
23
+ { ending: "ing", minimumStem: 4 },
24
+ { ending: "ed", minimumStem: 4 },
25
+ { ending: "es", minimumStem: 3 },
26
+ { ending: "s", minimumStem: 2 }
27
+ ];
28
+ var STOP_WORDS = /* @__PURE__ */ new Set([
29
+ "a",
30
+ "all",
31
+ "an",
32
+ "and",
33
+ "as",
34
+ "at",
35
+ "be",
36
+ "by",
37
+ "do",
38
+ "element",
39
+ "for",
40
+ "get",
41
+ "from",
42
+ "how",
43
+ "i",
44
+ "in",
45
+ "into",
46
+ "is",
47
+ "it",
48
+ "its",
49
+ "me",
50
+ "my",
51
+ "need",
52
+ "of",
53
+ "on",
54
+ "or",
55
+ "the",
56
+ "to",
57
+ "that",
58
+ "this",
59
+ "we",
60
+ "what",
61
+ "which",
62
+ "with"
63
+ ]);
64
+ var CORE_PACKAGE_NAME = "@dialecte/core";
65
+
66
+ // src/lib/api/find-methods.ts
67
+ function findMethods(params) {
68
+ const needWords = new Set(wordsOf(params.need));
69
+ if (needWords.size === 0) return [];
70
+ return params.indexes.flatMap(
71
+ (index) => index.methods.map((method) => scoreMethod({ method, packageName: index.package, needWords }))
72
+ ).filter((found) => found.hits.intent + found.hits.summary + found.hits.name > 0).sort(compareFound).slice(0, params.limit);
73
+ }
74
+ function wordsOf(text) {
75
+ return text.replace(/([a-z0-9])([A-Z])/g, "$1 $2").toLowerCase().split(/[^a-z0-9]+/).filter((word) => word !== "" && !STOP_WORDS.has(word)).map(stem);
76
+ }
77
+ function stem(word) {
78
+ const base = word.match(/^(.{2,})ie[sd]$/) ? `${word.slice(0, -3)}y` : STEM_SUFFIXES.map((suffix) => stripped({ word, suffix })).find(isDefined) ?? word;
79
+ return base.length > 3 && base.endsWith("e") ? base.slice(0, -1) : base;
80
+ }
81
+ function stripped(params) {
82
+ const { word, suffix } = params;
83
+ if (!word.endsWith(suffix.ending) || word.endsWith(`s${suffix.ending}`) && suffix.ending === "s")
84
+ return void 0;
85
+ const rest = word.slice(0, -suffix.ending.length);
86
+ return rest.length >= suffix.minimumStem && /[aeiouy]/.test(rest) ? rest : void 0;
87
+ }
88
+ function isDefined(value) {
89
+ return value !== void 0;
90
+ }
91
+ function scoreMethod(params) {
92
+ const { method, needWords } = params;
93
+ const intentMatches = method.intents.map((intent) => sharedCount({ text: intent, needWords }));
94
+ const hits = {
95
+ intent: sharedCount({ text: method.intents.join(" "), needWords }),
96
+ summary: sharedCount({ text: method.summary ?? "", needWords }),
97
+ name: sharedCount({ text: routeName(method), needWords })
98
+ };
99
+ const best = Math.max(0, ...intentMatches);
100
+ return {
101
+ method,
102
+ packageName: params.packageName,
103
+ hits,
104
+ matchingIntent: best > 0 ? method.intents[intentMatches.indexOf(best)] : void 0
105
+ };
106
+ }
107
+ function sharedCount(params) {
108
+ return new Set(wordsOf(params.text).filter((word) => params.needWords.has(word))).size;
109
+ }
110
+ function routeName(method) {
111
+ if (method.entry !== void 0 && method.path.startsWith(`${method.entry}.`))
112
+ return method.path.slice(method.entry.length + 1);
113
+ return method.path.replace(/^(doc\.query|tx|doc|project)\./, "");
114
+ }
115
+ function compareFound(left, right) {
116
+ return right.hits.intent - left.hits.intent || right.hits.summary - left.hits.summary || right.hits.name - left.hits.name || Number(left.packageName === CORE_PACKAGE_NAME) - Number(right.packageName === CORE_PACKAGE_NAME) || TEXT_COLLATOR.compare(left.method.path, right.method.path);
117
+ }
118
+
119
+ // src/lib/api/read-api-indexes.ts
120
+ import { existsSync as existsSync2, readdirSync as readdirSync2, readFileSync as readFileSync2 } from "fs";
121
+ import { join as join2 } from "path";
122
+
123
+ // src/lib/skills/skill-file.constants.ts
124
+ var SKILLS_FOLDER = "skills";
125
+ var SKILL_NAME_PATTERN = /^(?=.{1,64}$)[a-z0-9]+(-[a-z0-9]+)*$/;
126
+
127
+ // src/lib/skills/sync-skills.ts
128
+ import {
129
+ cpSync,
130
+ existsSync,
131
+ lstatSync as lstatSync2,
132
+ mkdirSync,
133
+ readdirSync,
134
+ readFileSync,
135
+ readlinkSync,
136
+ rmSync,
137
+ symlinkSync,
138
+ unlinkSync,
139
+ writeFileSync
140
+ } from "fs";
141
+ import { dirname, join, parse, relative, resolve } from "path";
142
+
143
+ // src/lib/file-system.ts
144
+ import { lstatSync, realpathSync } from "fs";
145
+
146
+ // src/lib/skills/sync-skills.constants.ts
147
+ var MANIFEST_FILE = ".dialecte-skills.json";
148
+ var AGENT_SKILL_FOLDERS = {
149
+ claude: ".claude/skills",
150
+ copilot: ".github/skills",
151
+ agents: ".agents/skills"
152
+ };
153
+
154
+ // src/lib/skills/sync-skills.ts
155
+ function discoverSkillSources(params) {
156
+ const missingDependencies = [];
157
+ const { from } = params;
158
+ const origins = from ? readdirSync(from, { withFileTypes: true }).filter((entry) => entry.isDirectory() && !entry.name.startsWith(".")).map((entry) => ({ origin: entry.name, folder: join(from, entry.name) })) : dependencyNames(params.cwd).flatMap((name) => {
159
+ const folder = findInstalledPackage({ cwd: params.cwd, name });
160
+ if (folder) return [{ origin: name, folder }];
161
+ missingDependencies.push(name);
162
+ return [];
163
+ });
164
+ const sources = origins.flatMap(skillsOf);
165
+ const originByName = /* @__PURE__ */ new Map();
166
+ for (const source of sources) {
167
+ const previous = originByName.get(source.name);
168
+ if (previous)
169
+ throw new Error(`skill "${source.name}" is shipped by both ${previous} and ${source.origin}`);
170
+ originByName.set(source.name, source.origin);
171
+ }
172
+ return { sources, missingDependencies };
173
+ }
174
+ function dependencyNames(cwd) {
175
+ const manifest = JSON.parse(readFileSync(join(cwd, "package.json"), "utf8"));
176
+ return [
177
+ .../* @__PURE__ */ new Set([
178
+ ...Object.keys(manifest.dependencies ?? {}),
179
+ ...Object.keys(manifest.devDependencies ?? {}),
180
+ ...Object.keys(manifest.peerDependencies ?? {})
181
+ ])
182
+ ];
183
+ }
184
+ function findInstalledPackage(params) {
185
+ let folder = params.cwd;
186
+ const { root } = parse(folder);
187
+ for (; ; ) {
188
+ const candidate = join(folder, "node_modules", params.name);
189
+ if (existsSync(candidate)) return candidate;
190
+ if (folder === root) return void 0;
191
+ folder = dirname(folder);
192
+ }
193
+ }
194
+ function skillsOf(params) {
195
+ const skillsFolder = join(params.folder, SKILLS_FOLDER);
196
+ if (!existsSync(skillsFolder)) return [];
197
+ const version = packageVersion(params.folder);
198
+ return readdirSync(skillsFolder, { withFileTypes: true }).filter(
199
+ (entry) => entry.isDirectory() && existsSync(join(skillsFolder, entry.name, "SKILL.md"))
200
+ ).map((entry) => ({
201
+ name: entry.name,
202
+ path: join(skillsFolder, entry.name),
203
+ origin: params.origin,
204
+ ...version === void 0 ? {} : { version }
205
+ }));
206
+ }
207
+ function packageVersion(folder) {
208
+ const path = join(folder, "package.json");
209
+ if (!existsSync(path)) return void 0;
210
+ const version = JSON.parse(readFileSync(path, "utf8")).version;
211
+ return typeof version === "string" ? version : void 0;
212
+ }
213
+ function readSyncManifest(targetFolder) {
214
+ const path = join(targetFolder, MANIFEST_FILE);
215
+ if (!existsSync(path)) return { installed: [], versions: {} };
216
+ const manifest = JSON.parse(readFileSync(path, "utf8"));
217
+ const installed = Array.isArray(manifest.installed) ? manifest.installed.filter(
218
+ (name) => typeof name === "string" && SKILL_NAME_PATTERN.test(name)
219
+ ) : [];
220
+ const versions = {};
221
+ if (typeof manifest.versions === "object" && manifest.versions !== null) {
222
+ for (const [name, entry] of Object.entries(manifest.versions))
223
+ if (isSyncedVersion(entry)) versions[name] = entry;
224
+ }
225
+ const stationAgents = Array.isArray(manifest.stationAgents) ? manifest.stationAgents.filter((name) => typeof name === "string") : void 0;
226
+ return {
227
+ installed,
228
+ versions,
229
+ ...typeof manifest.vendor === "string" ? { vendor: manifest.vendor } : {},
230
+ ...stationAgents ? { stationAgents } : {},
231
+ ...manifest.sessionCheck === true ? { sessionCheck: true } : {},
232
+ ...manifest.settingsCreated === true ? { settingsCreated: true } : {},
233
+ ...typeof manifest.sessionCheckInserted === "string" ? { sessionCheckInserted: manifest.sessionCheckInserted } : {}
234
+ };
235
+ }
236
+ function isSyncedVersion(value) {
237
+ return typeof value === "object" && value !== null && "package" in value && typeof value.package === "string" && "version" in value && typeof value.version === "string";
238
+ }
239
+
240
+ // src/lib/api/api-json.constants.ts
241
+ var API_JSON_FILE = "api.json";
242
+ var API_JSON_FOLDER = "references";
243
+ var MEMBER_SUGGESTION_LIMIT = 5;
244
+ var SHORT_SUMMARY_MAX_LENGTH = 120;
245
+
246
+ // src/lib/api/read-api-indexes.ts
247
+ function readApiIndexes(params) {
248
+ const { cwd } = params;
249
+ const skillFolders = [
250
+ ...ownSkillFolders(cwd),
251
+ ...discoverSkillSources({ cwd }).sources.map((source) => source.path)
252
+ ];
253
+ const byPackage = /* @__PURE__ */ new Map();
254
+ for (const folder of skillFolders) {
255
+ const path = join2(folder, API_JSON_FOLDER, API_JSON_FILE);
256
+ if (!existsSync2(path)) continue;
257
+ const index = readApiJson(path);
258
+ if (!byPackage.has(index.package)) byPackage.set(index.package, index);
259
+ }
260
+ return [...byPackage.values()].sort(
261
+ (left, right) => TEXT_COLLATOR.compare(left.package, right.package)
262
+ );
263
+ }
264
+ function ownSkillFolders(cwd) {
265
+ const skillsRoot = join2(cwd, SKILLS_FOLDER);
266
+ if (!existsSync2(skillsRoot)) return [];
267
+ return readdirSync2(skillsRoot, { withFileTypes: true }).filter((entry) => entry.isDirectory()).map((entry) => join2(skillsRoot, entry.name)).sort();
268
+ }
269
+ function readApiJson(path) {
270
+ const fix = "reinstall the package, or run `dialecte skills generate` in its repository";
271
+ let value;
272
+ try {
273
+ value = JSON.parse(readFileSync2(path, "utf8"));
274
+ } catch (error) {
275
+ throw new Error(
276
+ `${path} is not a valid api index (${error instanceof Error ? error.message : String(error)}): ${fix}`
277
+ );
278
+ }
279
+ if (!isApiJson(value))
280
+ throw new Error(`${path} is not a valid api index (no package name or no method list): ${fix}`);
281
+ return value;
282
+ }
283
+ function isApiJson(value) {
284
+ return typeof value === "object" && value !== null && "package" in value && typeof value.package === "string" && "methods" in value && Array.isArray(value.methods);
285
+ }
286
+
287
+ // src/lib/api/short-summary.ts
288
+ function shortSummary(summary) {
289
+ const sentence = summary.match(/^.*?[.!?](?=\s|$)/)?.[0] ?? summary;
290
+ return sentence.length > SHORT_SUMMARY_MAX_LENGTH ? `${sentence.slice(0, SHORT_SUMMARY_MAX_LENGTH - 1)}\u2026` : sentence;
291
+ }
292
+
293
+ // src/lib/api/render-api.ts
294
+ function renderFound(params) {
295
+ if (params.json)
296
+ return toJson({
297
+ need: params.need,
298
+ methods: params.found.map((found) => ({
299
+ path: found.method.path,
300
+ root: found.method.root,
301
+ package: found.packageName,
302
+ hits: found.hits,
303
+ intent: found.matchingIntent,
304
+ summary: found.method.summary
305
+ }))
306
+ });
307
+ return params.found.map(
308
+ (found) => `${found.method.path} ${found.method.root} ${found.matchingIntent ?? shortSummary(found.method.summary ?? "-")} ${found.packageName}
309
+ `
310
+ ).join("");
311
+ }
312
+ function renderShown(params) {
313
+ if (params.json)
314
+ return toJson({
315
+ methods: params.methods.map(({ method, packageName: packageName2 }) => ({
316
+ package: packageName2,
317
+ ...method
318
+ }))
319
+ });
320
+ return params.methods.map(renderMethod).join("\n");
321
+ }
322
+ function renderMethod({ method, packageName: packageName2 }) {
323
+ const lines = [`${method.path} (${packageName2})`, method.signature];
324
+ if (method.summary) lines.push(method.summary);
325
+ if (method.intents.length) lines.push(`intents: ${method.intents.join("; ")}`);
326
+ if (method.otherRoutes.length) lines.push(`also: ${method.otherRoutes.join(", ")}`);
327
+ if (method.declaredAt) lines.push(`source (repository): ${method.declaredAt}`);
328
+ if (method.example) lines.push(`example: ${method.example}`);
329
+ return `${lines.join("\n")}
330
+ `;
331
+ }
332
+ function toJson(value) {
333
+ return `${JSON.stringify(value, null, " ")}
334
+ `;
335
+ }
336
+
337
+ // src/lib/config.ts
338
+ import { readFileSync as readFileSync3, existsSync as existsSync3, readdirSync as readdirSync3, statSync } from "fs";
339
+ import { join as join3 } from "path";
340
+ var getArg = (argv, name) => {
341
+ const i = argv.indexOf(`--${name}`);
342
+ return i >= 0 ? argv[i + 1] : void 0;
343
+ };
344
+ var hasFlag = (argv, name) => argv.includes(`--${name}`);
345
+ function positionalArguments(params) {
346
+ const words = [];
347
+ for (let index = 0; index < params.argv.length; index++) {
348
+ const argument = params.argv[index];
349
+ if (!argument.startsWith("--")) words.push(argument);
350
+ else if (params.valueOptions.includes(argument.slice(2))) index++;
351
+ }
352
+ return words;
353
+ }
354
+ var tsconfigOf = (argv, cwd = process.cwd()) => getArg(argv, "tsconfig") ?? pkgConfig(cwd).tsconfig ?? "tsconfig.build.json";
355
+ var readPkg = (cwd) => {
356
+ const p = join3(cwd, "package.json");
357
+ return existsSync3(p) ? JSON.parse(readFileSync3(p, "utf8")) : {};
358
+ };
359
+ var pkgConfig = (cwd) => readPkg(cwd).dialecte ?? {};
360
+ var capitalize = (s) => s.charAt(0).toUpperCase() + s.slice(1);
361
+ function discoverNamespace(cwd) {
362
+ return capitalize(
363
+ String(readPkg(cwd).name ?? "dialecte").split("/").pop() ?? "dialecte"
364
+ );
365
+ }
366
+ function discoverVersions(cwd) {
367
+ const src = join3(cwd, "src");
368
+ if (!existsSync3(src)) return [];
369
+ return readdirSync3(src).filter((v) => statSync(join3(src, v)).isDirectory()).filter(
370
+ (v) => existsSync3(join3(src, v, "definition", "constants.generated.ts")) && existsSync3(join3(src, v, "definition", "definition.generated.ts"))
371
+ ).sort();
372
+ }
373
+ var CORE_PACKAGE = "@dialecte/core";
374
+ var CORE_TEST_DIALECT = {
375
+ version: "core",
376
+ binding: {
377
+ kind: "core",
378
+ coreAlias: "Core",
379
+ coreImport: "@/index",
380
+ configType: "TestDialecteConfig",
381
+ configImport: "@/test/config"
382
+ },
383
+ constantsDir: "./src/test/generated",
384
+ outDir: "./benchmarks/types/generated"
385
+ };
386
+ function resolveTargets(argv, cwd = process.cwd()) {
387
+ if (readPkg(cwd).name === CORE_PACKAGE)
388
+ return [
389
+ {
390
+ ...CORE_TEST_DIALECT,
391
+ version: getArg(argv, "version") ?? CORE_TEST_DIALECT.version,
392
+ constantsDir: getArg(argv, "constants-dir") ?? CORE_TEST_DIALECT.constantsDir,
393
+ outDir: getArg(argv, "out") ?? CORE_TEST_DIALECT.outDir
394
+ }
395
+ ];
396
+ const cfg = pkgConfig(cwd);
397
+ const namespace = getArg(argv, "namespace") ?? cfg.namespace ?? discoverNamespace(cwd);
398
+ const only = getArg(argv, "version");
399
+ let versions = discoverVersions(cwd);
400
+ if (only) versions = versions.filter((v) => v === only);
401
+ if (!versions.length && (getArg(argv, "constants-dir") || getArg(argv, "entry")))
402
+ versions = [only ?? "default"];
403
+ return versions.map((version) => {
404
+ const entry = getArg(argv, "entry") ?? cfg.entry ?? `@/${version}`;
405
+ return {
406
+ version,
407
+ binding: { kind: "namespace", name: namespace, import: entry },
408
+ constantsDir: getArg(argv, "constants-dir") ?? cfg.constantsDir ?? `./src/${version}/definition`,
409
+ outDir: getArg(argv, "out") ?? cfg.out ?? `./benchmarks/types/${version}/generated`
410
+ };
411
+ });
412
+ }
413
+
414
+ // src/lib/missing-package.ts
415
+ import { existsSync as existsSync4 } from "fs";
416
+ import { join as join4 } from "path";
417
+ function missingPackage(params) {
418
+ return existsSync4(join4(params.cwd, "package.json")) ? void 0 : {
419
+ output: `no package.json in ${params.cwd}: run dialecte in your package's folder
420
+ `,
421
+ exitCode: 2
422
+ };
423
+ }
424
+
425
+ // src/commands/api.constants.ts
426
+ var API_SUBCOMMANDS = ["find", "show"];
427
+ var API_VALUE_OPTIONS = ["package", "limit"];
428
+ var DEFAULT_FIND_LIMIT = 5;
429
+ var API_USAGE = 'usage: dialecte api find "<need>" [--package <name>] [--limit 5] [--json] | dialecte api show <path> [--json]';
430
+
431
+ // src/commands/api.ts
432
+ function runApi(params) {
433
+ const missing = missingPackage({ cwd: params.cwd });
434
+ if (missing) return missing;
435
+ const [subcommand, ...rest] = params.argv;
436
+ const words = positionalArguments({ argv: rest, valueOptions: API_VALUE_OPTIONS });
437
+ const limit = Number(getArg([...rest], "limit") ?? DEFAULT_FIND_LIMIT);
438
+ if (!isSubcommand(subcommand) || words.length === 0 || !Number.isInteger(limit) || limit < 1)
439
+ return { output: `${API_USAGE}
440
+ `, exitCode: 2 };
441
+ const packageName2 = getArg([...rest], "package");
442
+ const indexes = readApiIndexes({ cwd: params.cwd }).filter(
443
+ (index) => packageName2 === void 0 || index.package === packageName2
444
+ );
445
+ const json = hasFlag([...rest], "json");
446
+ return subcommand === "find" ? find({ indexes, need: words.join(" "), limit, json }) : show({ indexes, path: words[0], json });
447
+ }
448
+ function isSubcommand(value) {
449
+ return API_SUBCOMMANDS.some((subcommand) => subcommand === value);
450
+ }
451
+ function find(params) {
452
+ const found = findMethods(params);
453
+ if (found.length === 0 && !params.json)
454
+ return {
455
+ output: `no method found for "${params.need}" in ${packagesText(params.indexes)}: try other words, or \`npx @dialecte/cli members <expression>\` for the live types
456
+ `,
457
+ exitCode: 1
458
+ };
459
+ return {
460
+ output: renderFound({ need: params.need, found, json: params.json }),
461
+ exitCode: found.length ? 0 : 1
462
+ };
463
+ }
464
+ function show(params) {
465
+ const methods = findByPath(params);
466
+ if (methods.length === 0 && !params.json)
467
+ return {
468
+ output: `no method "${params.path}" in ${packagesText(params.indexes)}: \`npx @dialecte/cli api find "<what you need>"\` lists the routes
469
+ `,
470
+ exitCode: 1
471
+ };
472
+ return { output: renderShown({ methods, json: params.json }), exitCode: methods.length ? 0 : 1 };
473
+ }
474
+ function packagesText(indexes) {
475
+ return indexes.length ? indexes.map((index) => index.package).join(", ") : "no installed package (none ships skills/<name>/references/api.json)";
476
+ }
477
+
478
+ // src/lib/doctor/answer-doctor.ts
479
+ function answerDoctor(params) {
480
+ const exitCode = params.lines.some((line) => line.status === "warning") ? 1 : 0;
481
+ if (params.json)
482
+ return { output: `${JSON.stringify({ lines: params.lines }, null, " ")}
483
+ `, exitCode };
484
+ return { output: params.lines.map(renderLine).join(""), exitCode };
485
+ }
486
+ function answerDoctorBrief(lines) {
487
+ return {
488
+ output: lines.filter((line) => line.status === "warning").map(renderLine).join(""),
489
+ exitCode: 0
490
+ };
491
+ }
492
+ function renderLine(line) {
493
+ return line.status === "ok" ? `\u2705 ${line.subject} ${line.detail}
494
+ ` : `\u26A0\uFE0F ${line.subject} ${line.detail}${line.fix ? ` - fix: ${line.fix}` : ""}
495
+ `;
496
+ }
497
+
498
+ // src/lib/doctor/diagnose.ts
499
+ import { existsSync as existsSync7, lstatSync as lstatSync3, readdirSync as readdirSync4, readFileSync as readFileSync5 } from "fs";
500
+ import { dirname as dirname2, join as join7, resolve as resolve2 } from "path";
501
+
502
+ // src/lib/doctor/doctor.constants.ts
503
+ var DIALECTE_SCOPE = "@dialecte/";
504
+ var CORE_PACKAGE2 = "@dialecte/core";
505
+ var SYNC_COMMAND = "npx @dialecte/cli skills sync";
506
+ var INSTALL_COMMAND = "npm install";
507
+ var ALIGN_CORE_FIX = "align @dialecte/core with the version the dialecte pins (or upgrade the dialecte), then npm install";
508
+ var CORE_API_GENERATIONS = [
509
+ {
510
+ from: [0, 7],
511
+ name: "0.7",
512
+ says: "import inside the store (project.importFile answers { documentId, diagnostics }), per-file IO hook session, createTestHelpers"
513
+ },
514
+ {
515
+ from: [0, 0],
516
+ name: "0.6",
517
+ says: "import and IO hooks before the store owned them: read the skills of this version, not the latest docs"
518
+ }
519
+ ];
520
+ var CHECKOUT_LIST_LIMIT = 8;
521
+ var STATION_AGENTS_SUBJECT = "station agents";
522
+
523
+ // src/lib/doctor/station-agent-lines.ts
524
+ import { existsSync as existsSync6, readFileSync as readFileSync4 } from "fs";
525
+ import { join as join6 } from "path";
526
+
527
+ // src/lib/models/remembered-vendor.ts
528
+ import { existsSync as existsSync5, statSync as statSync2 } from "fs";
529
+ import { join as join5 } from "path";
530
+
531
+ // src/lib/models/model-tiers.constants.ts
532
+ var VENDOR_IDS = ["anthropic", "openai", "google"];
533
+ var TIER_NAMES = ["fast", "standard", "strong", "frontier"];
534
+ var TIER_DEFINITIONS = {
535
+ fast: 'search and locate, graders with a schema, log and diff summaries, format and shape checks, "does file X say Y"',
536
+ standard: "implementer on a mechanical or well-specified lot, fix mode on wording and rename findings, skill-eval runs, independent readers of a standard",
537
+ strong: "the orchestrator, an implementer on a design-heavy lot, the review (one agent, both passes), adjudicating a disagreement, the retro",
538
+ frontier: "rare: a plan challenge, a cross-repo architecture decision, a stuck lot after the 3-round cap"
539
+ };
540
+ var MODEL_TIERS = {
541
+ checkedAt: "2026-10-28",
542
+ vendors: {
543
+ anthropic: {
544
+ tiers: {
545
+ fast: { model: "Haiku 5.5" },
546
+ standard: { model: "Sonnet 5.5" },
547
+ strong: { model: "Opus 5.5" },
548
+ frontier: { model: "Fable 5.1" }
549
+ }
550
+ },
551
+ openai: {
552
+ tiers: {
553
+ fast: { model: "Luna" },
554
+ standard: { model: "Sol" },
555
+ strong: { model: "Sol", effort: "high" },
556
+ frontier: { model: "Astra" }
557
+ }
558
+ },
559
+ google: {
560
+ note: "frontier: check Google's own model page for the current flagship (4 Argon, if generally available)",
561
+ tiers: {
562
+ fast: { model: "Flash-Lite" },
563
+ standard: { model: "Flash" },
564
+ strong: { model: "Pro" },
565
+ frontier: { model: "the current flagship" }
566
+ }
567
+ }
568
+ }
569
+ };
570
+
571
+ // src/lib/models/vendor-id.ts
572
+ function isVendorId(value) {
573
+ return VENDOR_IDS.includes(value);
574
+ }
575
+
576
+ // src/lib/models/remembered-vendor.ts
577
+ function listManifestFolders(cwd) {
578
+ return Object.values(AGENT_SKILL_FOLDERS).filter(
579
+ (folder) => existsSync5(join5(cwd, folder, MANIFEST_FILE))
580
+ );
581
+ }
582
+ function readRememberedVendor(cwd) {
583
+ const warnings = [];
584
+ const entries = [];
585
+ for (const folder of listManifestFolders(cwd)) {
586
+ const { vendor } = readSyncManifest(join5(cwd, folder));
587
+ if (vendor === void 0) continue;
588
+ if (!isVendorId(vendor)) {
589
+ warnings.push(`${folder}/${MANIFEST_FILE}: unknown vendor "${vendor}" ignored`);
590
+ continue;
591
+ }
592
+ entries.push({
593
+ folder,
594
+ vendor,
595
+ writtenAt: statSync2(join5(cwd, folder, MANIFEST_FILE)).mtimeMs
596
+ });
597
+ }
598
+ entries.sort((first, second) => second.writtenAt - first.writtenAt);
599
+ if (new Set(entries.map((entry) => entry.vendor)).size > 1)
600
+ warnings.push(
601
+ `manifests disagree on the vendor (${entries.map((entry) => `${entry.folder}: ${entry.vendor}`).join(", ")}): using the most recent, ${entries[0].vendor}`
602
+ );
603
+ return { vendor: entries[0]?.vendor, warnings };
604
+ }
605
+
606
+ // src/lib/stations/station-agents.constants.ts
607
+ var STATION_AGENT_PREFIX = "dialecte-";
608
+ var CLAUDE_AGENTS_FOLDER = ".claude/agents";
609
+ var CLAUDE_MODEL_ALIASES = ["haiku", "sonnet", "opus", "fable"];
610
+ var READ_TOOLS = ["Read", "Glob", "Grep", "Skill"];
611
+ var REVIEW_TOOLS = ["Read", "Glob", "Grep", "Bash", "Skill"];
612
+ var EDIT_TOOLS = ["Read", "Write", "Edit", "Glob", "Grep", "Bash", "Skill"];
613
+ var LOAD_SKILLS_LINE = "Load first, with the Skill tool: `dialecte-lot` (your station and its report shape), `dialecte-contributing` (the gates and the code rules), `dialecte` (the API). They are the source of truth; this file only sets your envelope.";
614
+ var NEVER_LINE = "Never: commit, stage (`git add`), push, merge, `git stash`, `git reset`, `git restore`, `git checkout --`, `rm`; nothing outside the worktree your brief names. Your brief is your whole context.";
615
+ var GENERATED_NOTE = "Generated by `npx @dialecte/cli skills sync` from `dialecte models`; the next sync overwrites it.";
616
+ var STATIONS = [
617
+ {
618
+ name: "test-writer",
619
+ tier: "standard",
620
+ tools: EDIT_TOOLS,
621
+ description: "Dialecte lot, test station of one brief step: writes the tests (and stubs) from the brief and the existing code, then proves them red with `dialecte tdd red`. Give it the brief step.",
622
+ role: [
623
+ "You are the test station of a Dialecte lot (`dialecte-lot`): you write the tests of one brief step from the spec, never the production code.",
624
+ "You may add stubs whose body throws `not implemented: <name>` so the tests compile; call them inside `expect(...)`.",
625
+ "Run `dialecte tdd red` until every case is red on an assertion, and answer with its output."
626
+ ]
627
+ },
628
+ {
629
+ name: "test-reviewer",
630
+ tier: "strong",
631
+ tools: REVIEW_TOOLS,
632
+ description: "Dialecte lot, test review before any code: reads only the tests against the brief (does each pin a behaviour, would a plausible wrong implementation fail it). Read-only.",
633
+ role: [
634
+ "You are the test review of a Dialecte lot (`dialecte-lot`): you read the tests of the step against the brief, before any production code.",
635
+ "You modify nothing (`dialecte tdd status` is the one command to run). Answer per test: the behaviour it pins, a plausible wrong implementation it lets through, a verdict."
636
+ ]
637
+ },
638
+ {
639
+ name: "implementer",
640
+ tier: "standard",
641
+ tools: EDIT_TOOLS,
642
+ description: "Dialecte lot, Station 1 (implement) on a mechanical or fully specified lot: production code only until `dialecte tdd green`, then the fast gate. Give it the brief.",
643
+ role: [
644
+ "You are the implementer of a Dialecte lot: Station 1 of `dialecte-lot`, step mode.",
645
+ "The tests are written and red: change production code only until `dialecte tdd green` passes; a test you find wrong goes back to the test station with the reason. Run the fast gate, and answer with the implement report shape of the skill."
646
+ ]
647
+ },
648
+ {
649
+ name: "implementer-strong",
650
+ tier: "strong",
651
+ tools: EDIT_TOOLS,
652
+ description: "Dialecte lot, Station 1 (implement) on a design-heavy lot: production code only until `dialecte tdd green`, then the fast gate. Give it the brief.",
653
+ role: [
654
+ "You are the implementer of a design-heavy Dialecte lot: Station 1 of `dialecte-lot`, step mode.",
655
+ "The tests are written and red: change production code only until `dialecte tdd green` passes; a test you find wrong goes back to the test station with the reason. Run the fast gate, and answer with the implement report shape of the skill."
656
+ ]
657
+ },
658
+ {
659
+ name: "reviewer",
660
+ tier: "strong",
661
+ tools: REVIEW_TOOLS,
662
+ description: "Dialecte lot, Station 3 (independent review): pass 1 correctness, pass 2 fit, read-only. Give it the brief and the diff, not the implementer conclusions.",
663
+ role: [
664
+ "You are the reviewer of a Dialecte lot: Station 3 of `dialecte-lot`, a different agent from the implementer.",
665
+ "You modify nothing: you read the diff and run the tests. Answer with the review report shape of the skill (both passes, a verdict)."
666
+ ]
667
+ },
668
+ {
669
+ name: "fixer",
670
+ tier: "standard",
671
+ tools: EDIT_TOOLS,
672
+ description: "Dialecte lot, Station 4 (fix mode) on wording and naming findings: fixed, disagreed or escalated per finding. Give it the findings.",
673
+ role: [
674
+ "You are the implementer in fix mode: Station 4 of `dialecte-lot`.",
675
+ "For each finding answer fixed, disagreed (one line why) or needs the user; never drop one."
676
+ ]
677
+ },
678
+ {
679
+ name: "eval-runner",
680
+ tier: "standard",
681
+ tools: EDIT_TOOLS,
682
+ description: "Runs one skill-eval case of a Dialecte skill, with or without the skill, and leaves the outputs the graders read.",
683
+ role: [
684
+ "You run one skill-eval case of `dialecte-lot` (a skill text change goes through skill-creator evals).",
685
+ "Follow the case prompt exactly, with or without the skill as your brief says, and write only the outputs it names."
686
+ ]
687
+ },
688
+ {
689
+ name: "grader",
690
+ tier: "fast",
691
+ tools: READ_TOOLS,
692
+ description: "Grades the output of a skill-eval run against one grader file, pass or fail with the evidence. Read-only.",
693
+ role: [
694
+ "You grade the output of a skill-eval run against the grader files your brief names.",
695
+ "You read, never run or change anything: answer pass or fail per grader, with the line that shows it."
696
+ ]
697
+ },
698
+ {
699
+ name: "standard-reader",
700
+ tier: "standard",
701
+ tools: READ_TOOLS,
702
+ description: "Independent reader of the IEC standard markdown for one question, with line references. Read-only.",
703
+ role: [
704
+ 'You read the standard for one question: "Reading the standard" of `dialecte-contributing`.',
705
+ "You read the standard markdown only, answer with line references, and never rely on what another agent concluded."
706
+ ]
707
+ },
708
+ {
709
+ name: "searcher",
710
+ tier: "fast",
711
+ tools: READ_TOOLS,
712
+ description: "Finds where something lives in a Dialecte repository (files, symbols, API paths) and answers with paths and line numbers. Read-only.",
713
+ role: [
714
+ "You locate code, files or documentation for the question your brief asks, in the Dialecte repositories it names.",
715
+ "You read, never change anything: answer with absolute paths and line numbers, nothing speculative."
716
+ ]
717
+ }
718
+ ];
719
+
720
+ // src/lib/stations/render-station-agent.ts
721
+ function claudeModelAlias(modelName) {
722
+ const alias = modelName.split(" ")[0].toLowerCase();
723
+ return CLAUDE_MODEL_ALIASES.includes(alias) ? alias : void 0;
724
+ }
725
+ function renderStationAgent(params) {
726
+ const { station, model } = params;
727
+ return [
728
+ "---",
729
+ `name: ${STATION_AGENT_PREFIX}${station.name}`,
730
+ `description: ${JSON.stringify(station.description)}`,
731
+ `tools: ${station.tools.join(", ")}`,
732
+ `model: ${model}`,
733
+ "---",
734
+ `<!-- ${GENERATED_NOTE} -->`,
735
+ "",
736
+ ...station.role,
737
+ "",
738
+ LOAD_SKILLS_LINE,
739
+ "",
740
+ NEVER_LINE,
741
+ ""
742
+ ].join("\n");
743
+ }
744
+ function planStationAgents(params) {
745
+ const { vendor } = params;
746
+ if (vendor === void 0)
747
+ return {
748
+ kind: "skipped",
749
+ reason: "no model vendor known for this project, so no Claude Code station agents: run `skills sync --vendor anthropic`"
750
+ };
751
+ if (vendor !== "anthropic")
752
+ return {
753
+ kind: "skipped",
754
+ reason: `no Claude Code station agents: the project's vendor is ${vendor}, whose tiers are named by \`dialecte models\``
755
+ };
756
+ const tiers = MODEL_TIERS.vendors[vendor].tiers;
757
+ const files = [];
758
+ for (const station of STATIONS) {
759
+ const modelName = tiers[station.tier].model;
760
+ const model = claudeModelAlias(modelName);
761
+ if (model === void 0)
762
+ return {
763
+ kind: "skipped",
764
+ reason: `no Claude Code station agents: "${modelName}" (${station.tier}) is not a model name Claude Code accepts`
765
+ };
766
+ files.push({
767
+ name: `${STATION_AGENT_PREFIX}${station.name}.md`,
768
+ content: renderStationAgent({ station, model })
769
+ });
770
+ }
771
+ return { kind: "files", files };
772
+ }
773
+
774
+ // src/lib/doctor/station-agent-lines.ts
775
+ function stationAgentLines(cwd) {
776
+ const manifestFolder = join6(cwd, AGENT_SKILL_FOLDERS.claude);
777
+ if (!existsSync6(join6(manifestFolder, MANIFEST_FILE))) return [];
778
+ const listed = readSyncManifest(manifestFolder).stationAgents ?? [];
779
+ if (listed.length === 0) return [];
780
+ const plan = planStationAgents({ vendor: readRememberedVendor(cwd).vendor });
781
+ if (plan.kind !== "files") return [];
782
+ const missing = [];
783
+ const stale = [];
784
+ for (const file of plan.files) {
785
+ const path = join6(cwd, CLAUDE_AGENTS_FOLDER, file.name);
786
+ if (!existsSync6(path)) missing.push(file.name);
787
+ else if (listed.includes(file.name) && readFileSync4(path, "utf8") !== file.content)
788
+ stale.push(file.name);
789
+ }
790
+ if (missing.length === 0 && stale.length === 0)
791
+ return [{ status: "ok", subject: STATION_AGENTS_SUBJECT, detail: `${CLAUDE_AGENTS_FOLDER} in sync` }];
792
+ const parts = [
793
+ ...stale.length ? [`holds stale ${stale.join(", ")}`] : [],
794
+ ...missing.length ? [`lacks ${missing.join(", ")}`] : []
795
+ ];
796
+ return [
797
+ {
798
+ status: "warning",
799
+ subject: STATION_AGENTS_SUBJECT,
800
+ detail: `${CLAUDE_AGENTS_FOLDER} ${parts.join("; ")}`,
801
+ fix: SYNC_COMMAND
802
+ }
803
+ ];
804
+ }
805
+
806
+ // src/lib/doctor/diagnose.ts
807
+ function diagnose(context) {
808
+ return [
809
+ { status: "ok", subject: "dialecte", detail: `cli ${context.cliVersion} running` },
810
+ ...installedPackages(context.cwd),
811
+ ...coreGenerations(context.cwd),
812
+ ...skills(context.cwd),
813
+ ...stationAgentLines(context.cwd),
814
+ ...context.brief ? [] : localCheckouts(context)
815
+ ];
816
+ }
817
+ function installedPackages(cwd) {
818
+ const declared = declaredVersions(cwd);
819
+ return Object.keys(declared).filter((name) => name.startsWith(DIALECTE_SCOPE)).sort(TEXT_COLLATOR.compare).map(function packageLine(name) {
820
+ const version = installedVersion({ cwd, name });
821
+ if (version === void 0)
822
+ return { status: "warning", subject: name, detail: "not installed", fix: INSTALL_COMMAND };
823
+ const pinned = declared[name];
824
+ if (/^\d/.test(pinned) && pinned !== version)
825
+ return {
826
+ status: "warning",
827
+ subject: name,
828
+ detail: `${version} installed, ${pinned} declared`,
829
+ fix: INSTALL_COMMAND
830
+ };
831
+ return { status: "ok", subject: name, detail: version };
832
+ });
833
+ }
834
+ function coreGenerations(cwd) {
835
+ const dialectes = dependencyNames(cwd).sort(TEXT_COLLATOR.compare).flatMap(function dialecteOnCore(name) {
836
+ const folder = findInstalledPackage({ cwd, name });
837
+ return folder && dependsOnCore(folder) ? [{ name, folder }] : [];
838
+ });
839
+ const appCore = installedVersion({ cwd, name: CORE_PACKAGE2 });
840
+ const owners = dialectes.length ? dialectes : [{ name: void 0, folder: cwd }];
841
+ return owners.flatMap(function generationLine({ name, folder }) {
842
+ const version = installedVersion({ cwd: folder, name: CORE_PACKAGE2 });
843
+ if (version === void 0) return [];
844
+ const [major = 0, minor = 0] = version.split(".").map(Number);
845
+ const generation = CORE_API_GENERATIONS.find(
846
+ ({ from }) => major > from[0] || major === from[0] && minor >= from[1]
847
+ );
848
+ if (!generation) return [];
849
+ const says = `${generation.name}: ${generation.says}`;
850
+ if (name && appCore !== void 0 && appCore !== version)
851
+ return [
852
+ {
853
+ status: "warning",
854
+ subject: "core API",
855
+ detail: `${name} on core ${version}, your app on core ${appCore}: two cores side by side (${says})`,
856
+ fix: ALIGN_CORE_FIX
857
+ }
858
+ ];
859
+ const owner = name ? `${name} on core ${version}` : `core ${version}`;
860
+ return [{ status: "ok", subject: "core API", detail: `${owner} - ${says}` }];
861
+ });
862
+ }
863
+ function skills(cwd) {
864
+ const { sources } = discoverSkillSources({ cwd });
865
+ if (sources.length === 0)
866
+ return [{ status: "ok", subject: "skills", detail: "no dependency ships skills" }];
867
+ const synced = Object.values(AGENT_SKILL_FOLDERS).filter(
868
+ (folder) => existsSync7(join7(cwd, folder, MANIFEST_FILE))
869
+ );
870
+ if (synced.length === 0)
871
+ return [
872
+ {
873
+ status: "warning",
874
+ subject: "skills",
875
+ detail: `not installed for your agents (${sources.map((source) => source.name).join(", ")} shipped)`,
876
+ fix: SYNC_COMMAND
877
+ }
878
+ ];
879
+ return synced.map(function syncLine(folder) {
880
+ const manifest = readSyncManifest(join7(cwd, folder));
881
+ const missing = sources.map((source) => source.name).filter((name) => !manifest.installed.includes(name));
882
+ if (missing.length)
883
+ return {
884
+ status: "warning",
885
+ subject: "skills",
886
+ detail: `${folder} lacks ${missing.join(", ")}`,
887
+ fix: SYNC_COMMAND
888
+ };
889
+ const stale = sources.flatMap(function staleCopy(source) {
890
+ const recorded = manifest.versions[source.name];
891
+ if (isLink(join7(cwd, folder, source.name)) || source.version === void 0) return [];
892
+ if (recorded?.version === source.version) return [];
893
+ return [
894
+ `${source.name} of ${source.origin} ${recorded?.version ?? "an unknown version"}, ${source.version} installed`
895
+ ];
896
+ });
897
+ if (stale.length)
898
+ return {
899
+ status: "warning",
900
+ subject: "skills",
901
+ detail: `${folder} holds ${stale.join("; ")}`,
902
+ fix: SYNC_COMMAND
903
+ };
904
+ return { status: "ok", subject: "skills", detail: `${folder} in sync with node_modules` };
905
+ });
906
+ }
907
+ function isLink(path) {
908
+ try {
909
+ return lstatSync3(path).isSymbolicLink();
910
+ } catch {
911
+ return false;
912
+ }
913
+ }
914
+ function dependsOnCore(folder) {
915
+ const manifest = JSON.parse(readFileSync5(join7(folder, "package.json"), "utf8"));
916
+ return manifest.name !== CORE_PACKAGE2 && (manifest.dependencies?.[CORE_PACKAGE2] !== void 0 || manifest.peerDependencies?.[CORE_PACKAGE2] !== void 0);
917
+ }
918
+ function localCheckouts(context) {
919
+ const roots = [
920
+ ...new Set([context.dialecteRoot, dirname2(resolve2(context.cwd))].filter(isDefined2))
921
+ ];
922
+ return roots.map(function checkoutLine(root) {
923
+ const names = existsSync7(root) ? readdirSync4(root, { withFileTypes: true }).filter((entry) => entry.isDirectory() && join7(root, entry.name) !== resolve2(context.cwd)).filter((entry) => packageName(join7(root, entry.name))?.startsWith(DIALECTE_SCOPE)).map((entry) => entry.name).sort(TEXT_COLLATOR.compare) : [];
924
+ return {
925
+ status: "ok",
926
+ subject: "checkouts",
927
+ detail: names.length ? `${root}: ${names.slice(0, CHECKOUT_LIST_LIMIT).join(", ")}${names.length > CHECKOUT_LIST_LIMIT ? ` and ${names.length - CHECKOUT_LIST_LIMIT} more` : ""}` : `none in ${root} (the installed packages are the source)`
928
+ };
929
+ });
930
+ }
931
+ function declaredVersions(cwd) {
932
+ const manifest = JSON.parse(readFileSync5(join7(cwd, "package.json"), "utf8"));
933
+ const names = dependencyNames(cwd);
934
+ return Object.fromEntries(
935
+ names.map((name) => [
936
+ name,
937
+ String(
938
+ manifest.dependencies?.[name] ?? manifest.devDependencies?.[name] ?? manifest.peerDependencies?.[name]
939
+ )
940
+ ])
941
+ );
942
+ }
943
+ function installedVersion(params) {
944
+ const folder = findInstalledPackage(params);
945
+ if (!folder || !existsSync7(join7(folder, "package.json"))) return void 0;
946
+ const version = JSON.parse(readFileSync5(join7(folder, "package.json"), "utf8")).version;
947
+ return typeof version === "string" ? version : void 0;
948
+ }
949
+ function packageName(folder) {
950
+ const path = join7(folder, "package.json");
951
+ if (!existsSync7(path)) return void 0;
952
+ const name = JSON.parse(readFileSync5(path, "utf8")).name;
953
+ return typeof name === "string" ? name : void 0;
954
+ }
955
+ function isDefined2(value) {
956
+ return value !== void 0;
957
+ }
958
+
959
+ // src/lib/read-cli-version.ts
960
+ import { existsSync as existsSync8, readFileSync as readFileSync6 } from "fs";
961
+ import { dirname as dirname3, join as join8 } from "path";
962
+ import { fileURLToPath } from "url";
963
+ function readCliVersion(params = {}) {
964
+ const startFolder = params.startFolder ?? dirname3(fileURLToPath(import.meta.url));
965
+ let folder = startFolder;
966
+ while (!existsSync8(join8(folder, "package.json"))) {
967
+ const parent = dirname3(folder);
968
+ if (parent === folder)
969
+ throw new Error(`no package.json above ${startFolder}: cannot read the cli version`);
970
+ folder = parent;
971
+ }
972
+ const { version } = JSON.parse(readFileSync6(join8(folder, "package.json"), "utf8"));
973
+ return version;
974
+ }
975
+
976
+ // src/commands/doctor.ts
977
+ function runDoctor(params) {
978
+ const { argv, cliVersion, ...rest } = params;
979
+ if (hasFlag([...argv], "brief")) return runBrief({ ...rest, cliVersion });
980
+ const missing = missingPackage({ cwd: params.cwd });
981
+ if (missing) return missing;
982
+ return answerDoctor({
983
+ lines: diagnose({ ...rest, cliVersion: resolveVersion(cliVersion) }),
984
+ json: hasFlag([...argv], "json")
985
+ });
986
+ }
987
+ function runBrief(context) {
988
+ try {
989
+ return answerDoctorBrief(
990
+ diagnose({ ...context, cliVersion: resolveVersion(context.cliVersion), brief: true })
991
+ );
992
+ } catch {
993
+ return { output: "", exitCode: 0 };
994
+ }
995
+ }
996
+ function resolveVersion(cliVersion) {
997
+ return typeof cliVersion === "string" ? cliVersion : cliVersion();
998
+ }
999
+
1000
+ // src/lib/closest-names.ts
1001
+ function closestNames(params) {
1002
+ const name = params.name.toLowerCase();
1003
+ const threshold = Math.max(2, Math.floor(name.length / 3));
1004
+ return params.candidates.map((candidate) => ({
1005
+ candidate,
1006
+ distance: candidate.toLowerCase().includes(name) ? 0 : editDistance({ from: name, to: candidate.toLowerCase() })
1007
+ })).filter(({ distance }) => distance <= threshold).sort(
1008
+ (left, right) => left.distance - right.distance || TEXT_COLLATOR.compare(left.candidate, right.candidate)
1009
+ ).slice(0, params.limit).map(({ candidate }) => candidate);
1010
+ }
1011
+ function editDistance(params) {
1012
+ const { from, to } = params;
1013
+ let previous = Array.from({ length: to.length + 1 }, (_, index) => index);
1014
+ for (let row = 1; row <= from.length; row++) {
1015
+ const current = [row];
1016
+ for (let column = 1; column <= to.length; column++)
1017
+ current[column] = Math.min(
1018
+ previous[column] + 1,
1019
+ current[column - 1] + 1,
1020
+ previous[column - 1] + (from[row - 1] === to[column - 1] ? 0 : 1)
1021
+ );
1022
+ previous = current;
1023
+ }
1024
+ return previous[to.length];
1025
+ }
1026
+
1027
+ // src/lib/api/list-members.ts
1028
+ function listMembers(params) {
1029
+ const path = discoveryPath(params.expression);
1030
+ const exact = params.entries.find((entry) => entry.path === path);
1031
+ if (exact) return [methodMember({ entry: exact, name: lastSegment(path) })];
1032
+ const methods = [];
1033
+ const methodCountByGroup = /* @__PURE__ */ new Map();
1034
+ for (const entry of params.entries) {
1035
+ if (!entry.path.startsWith(`${path}.`)) continue;
1036
+ const [name, ...below] = entry.path.slice(path.length + 1).split(".");
1037
+ if (below.length === 0) methods.push(methodMember({ entry, name }));
1038
+ else methodCountByGroup.set(name, (methodCountByGroup.get(name) ?? 0) + 1);
1039
+ }
1040
+ const groups = [...methodCountByGroup].map(([name, methodCount]) => ({
1041
+ kind: "group",
1042
+ name,
1043
+ methodCount
1044
+ }));
1045
+ return [...methods.sort(byName), ...groups.sort(byName)];
1046
+ }
1047
+ function discoveryPath(expression) {
1048
+ return expression.replace(/^(doc\.query|query)(?=\.|$)/, "q");
1049
+ }
1050
+ function methodMember(params) {
1051
+ return {
1052
+ kind: "method",
1053
+ name: params.name,
1054
+ summary: params.entry.summary,
1055
+ intents: params.entry.intents
1056
+ };
1057
+ }
1058
+ function lastSegment(path) {
1059
+ return path.slice(path.lastIndexOf(".") + 1);
1060
+ }
1061
+ function byName(left, right) {
1062
+ return TEXT_COLLATOR.compare(left.name, right.name);
1063
+ }
1064
+
1065
+ // src/lib/api/answer-members.ts
1066
+ function answerMembers(params) {
1067
+ const { expression } = params;
1068
+ const members = listMembers(params);
1069
+ if (params.json)
1070
+ return {
1071
+ output: `${JSON.stringify({ expression, members }, null, " ")}
1072
+ `,
1073
+ exitCode: members.length ? 0 : 1
1074
+ };
1075
+ if (members.length)
1076
+ return { output: `${[expression, ...members.map(memberLine)].join("\n")}
1077
+ `, exitCode: 0 };
1078
+ const parent = expression.slice(0, Math.max(0, expression.lastIndexOf(".")));
1079
+ const neighbours = parent ? listMembers({ entries: params.entries, expression: parent }).map((member) => member.name) : [];
1080
+ const closest = closestNames({
1081
+ name: expression.slice(expression.lastIndexOf(".") + 1),
1082
+ candidates: neighbours,
1083
+ limit: MEMBER_SUGGESTION_LIMIT
1084
+ });
1085
+ const hint = parent ? ` - under ${parent}: ${(closest.length ? closest : neighbours).join(", ") || "nothing"}` : "";
1086
+ return { output: `nothing at ${expression}${hint}
1087
+ `, exitCode: 1 };
1088
+ }
1089
+ function memberLine(member) {
1090
+ if (member.kind === "group")
1091
+ return ` ${member.name}. ${member.methodCount} method${member.methodCount === 1 ? "" : "s"}`;
1092
+ return member.summary ? ` ${member.name}() ${shortSummary(member.summary)}` : ` ${member.name}()`;
1093
+ }
1094
+
1095
+ // src/lib/discover.ts
1096
+ import { mkdirSync as mkdirSync2, rmSync as rmSync2, writeFileSync as writeFileSync2 } from "fs";
1097
+ import { dirname as dirname4, join as join9, relative as relative2 } from "path";
1098
+
1099
+ // src/lib/discover.constants.ts
1100
+ import ts from "typescript";
1101
+ var ENTRY_FOLDER = "node_modules/.cache/dialecte";
1102
+ var ROOTS = ["q", "tx", "doc", "project"];
1103
+ var PRIMITIVE_LIKE = ts.TypeFlags.StringLike | ts.TypeFlags.NumberLike | ts.TypeFlags.BooleanLike | ts.TypeFlags.ESSymbolLike | ts.TypeFlags.VoidLike | ts.TypeFlags.Null | ts.TypeFlags.BigIntLike;
1104
+ var SIGNATURE_FORMAT = ts.TypeFormatFlags.WriteArrowStyleSignature | ts.TypeFormatFlags.UseAliasDefinedOutsideCurrentScope;
1105
+ var FENCED_CODE_PATTERN = /^[ \t]*```[a-z]*[ \t]*\n([\s\S]*?)^[ \t]*```/m;
1106
+ var SIGNATURE_PRINTER = ts.createPrinter({ removeComments: true });
1107
+
1108
+ // src/lib/render-jsdoc-text.ts
1109
+ function renderJsDocText(parts) {
1110
+ let text = "";
1111
+ let link;
1112
+ for (const part of parts ?? []) {
1113
+ if (part.kind === "link" && part.text.startsWith("{@link"))
1114
+ link = { name: void 0, label: "" };
1115
+ else if (link && part.kind === "linkName") link.name = part.text;
1116
+ else if (link && part.kind === "linkText") link.label += part.text;
1117
+ else if (link && part.kind === "link") {
1118
+ text += renderLink(link);
1119
+ link = void 0;
1120
+ } else text += part.text;
1121
+ }
1122
+ return text;
1123
+ }
1124
+ function renderLink(link) {
1125
+ if (link.name !== void 0) return link.label.trim() || `\`${link.name}\``;
1126
+ const [target = "", ...label] = link.label.trim().split(/\s+/);
1127
+ return label.join(" ") || `\`${target}\``;
1128
+ }
1129
+
1130
+ // src/lib/discover.ts
1131
+ import ts2 from "typescript";
1132
+ function discoverMethods(params) {
1133
+ const { entrySource, tsconfig, root, maxDepth = 1 } = params;
1134
+ const entryPath = join9(root, ENTRY_FOLDER, `discover-entry-${process.pid}.ts`);
1135
+ mkdirSync2(dirname4(entryPath), { recursive: true });
1136
+ writeFileSync2(entryPath, entrySource);
1137
+ try {
1138
+ const parsed = ts2.parseJsonConfigFileContent(
1139
+ ts2.readConfigFile(join9(root, tsconfig), ts2.sys.readFile).config,
1140
+ ts2.sys,
1141
+ root
1142
+ );
1143
+ const program = ts2.createProgram([entryPath], {
1144
+ ...parsed.options,
1145
+ noEmit: true,
1146
+ rootDir: root
1147
+ });
1148
+ const checker = program.getTypeChecker();
1149
+ const sourceFile = program.getSourceFile(entryPath);
1150
+ if (!sourceFile) return [];
1151
+ const exportsByName = new Map(
1152
+ checker.getExportsOfModule(checker.getSymbolAtLocation(sourceFile)).map((symbol) => [symbol.getName(), symbol])
1153
+ );
1154
+ const entries = [];
1155
+ for (const rootName of ROOTS) {
1156
+ const symbol = exportsByName.get(rootName);
1157
+ if (symbol)
1158
+ walkMembers({
1159
+ checker,
1160
+ sourceFile,
1161
+ type: checker.getTypeOfSymbolAtLocation(symbol, sourceFile),
1162
+ path: rootName,
1163
+ depth: 0,
1164
+ maxDepth,
1165
+ root,
1166
+ entries
1167
+ });
1168
+ }
1169
+ return entries;
1170
+ } finally {
1171
+ rmSync2(entryPath, { force: true });
1172
+ }
1173
+ }
1174
+ function walkMembers(params) {
1175
+ const { checker, sourceFile, type, path, depth, maxDepth } = params;
1176
+ for (const property of type.getProperties()) {
1177
+ if (!isPublic(property)) continue;
1178
+ const propertyType = checker.getTypeOfSymbolAtLocation(
1179
+ property,
1180
+ declarationOf(property) ?? sourceFile
1181
+ );
1182
+ const propertyPath = `${path}.${property.getName()}`;
1183
+ if (propertyType.getCallSignatures().length > 0) {
1184
+ const { documentation, declaringSymbol } = documentationOf({
1185
+ checker,
1186
+ symbol: property,
1187
+ root: params.root
1188
+ });
1189
+ params.entries.push({
1190
+ path: propertyPath,
1191
+ signature: signatureOf({ checker, boundType: propertyType, declaringSymbol }),
1192
+ ...documentation
1193
+ });
1194
+ } else if (depth < maxDepth && !(propertyType.flags & PRIMITIVE_LIKE) && propertyType.getProperties().some(
1195
+ (member) => isPublic(member) && !isTypeScriptLibrary(member) && checker.getTypeOfSymbolAtLocation(member, declarationOf(member) ?? sourceFile).getCallSignatures().length > 0
1196
+ ))
1197
+ walkMembers({ ...params, type: propertyType, path: propertyPath, depth: depth + 1 });
1198
+ }
1199
+ }
1200
+ function signatureOf(params) {
1201
+ const { checker } = params;
1202
+ const boundSignatures = params.boundType.getCallSignatures();
1203
+ const declarations = callableDeclarations(params.declaringSymbol);
1204
+ if (declarations.length === 0)
1205
+ return boundSignatures.map(
1206
+ (signature) => checker.signatureToString(signature, void 0, SIGNATURE_FORMAT, ts2.SignatureKind.Call)
1207
+ ).join("\n");
1208
+ const boundParameterCount = Math.max(
1209
+ ...boundSignatures.map((signature) => parameterCount({ checker, signature }))
1210
+ );
1211
+ return declarations.map((declaration) => declaredSignatureText({ checker, declaration, boundParameterCount })).join("\n");
1212
+ }
1213
+ function parameterCount(params) {
1214
+ const { checker } = params;
1215
+ const parameters = params.signature.getParameters();
1216
+ const last = parameters.at(-1);
1217
+ if (!last) return 0;
1218
+ const lastType = checker.getTypeOfSymbol(last);
1219
+ return checker.isTupleType(lastType) ? parameters.length - 1 + checker.getTypeArguments(lastType).length : parameters.length;
1220
+ }
1221
+ function callableDeclarations(symbol) {
1222
+ const declarations = (symbol?.declarations ?? []).flatMap(
1223
+ (declaration) => {
1224
+ if (ts2.isFunctionDeclaration(declaration) || ts2.isMethodDeclaration(declaration))
1225
+ return [declaration];
1226
+ if (ts2.isVariableDeclaration(declaration) && declaration.initializer && (ts2.isArrowFunction(declaration.initializer) || ts2.isFunctionExpression(declaration.initializer)))
1227
+ return [declaration.initializer];
1228
+ return [];
1229
+ }
1230
+ );
1231
+ const overloads = declarations.filter((declaration) => !hasBody(declaration));
1232
+ return overloads.length > 0 ? overloads : declarations;
1233
+ }
1234
+ function hasBody(declaration) {
1235
+ return "body" in declaration && declaration.body !== void 0;
1236
+ }
1237
+ function declaredSignatureText(params) {
1238
+ const { checker, declaration } = params;
1239
+ const sourceFile = declaration.getSourceFile();
1240
+ const signature = checker.getSignatureFromDeclaration(declaration);
1241
+ const parameters = declaration.parameters;
1242
+ const skipped = Math.max(0, parameters.length - params.boundParameterCount);
1243
+ const typeParameters = declaration.typeParameters?.length ? `<${declaration.typeParameters.map((typeParameter) => printed({ node: typeParameter, sourceFile })).join(", ")}>` : "";
1244
+ const parameterTexts = parameters.slice(skipped).map(function parameterText(parameter) {
1245
+ const optional = parameter.questionToken || parameter.initializer ? "?" : "";
1246
+ const rest = parameter.dotDotDotToken ? "..." : "";
1247
+ const type = parameter.type ? printed({ node: parameter.type, sourceFile }) : checker.typeToString(checker.getTypeAtLocation(parameter), declaration, SIGNATURE_FORMAT);
1248
+ return `${rest}${printed({ node: parameter.name, sourceFile })}${optional}: ${type}`;
1249
+ });
1250
+ const returnType = declaration.type ? printed({ node: declaration.type, sourceFile }) : signature ? checker.typeToString(signature.getReturnType(), declaration, SIGNATURE_FORMAT) : "unknown";
1251
+ return `${typeParameters}(${parameterTexts.join(", ")}) => ${returnType}`;
1252
+ }
1253
+ function printed(params) {
1254
+ return SIGNATURE_PRINTER.printNode(
1255
+ ts2.EmitHint.Unspecified,
1256
+ params.node,
1257
+ params.sourceFile
1258
+ ).replace(/\s*\n\s*/g, " ");
1259
+ }
1260
+ function documentationOf(params) {
1261
+ const { checker } = params;
1262
+ const visited = /* @__PURE__ */ new Set();
1263
+ const queue = [params.symbol];
1264
+ let declaringSymbol;
1265
+ while (queue.length) {
1266
+ const symbol = queue.shift();
1267
+ if (!symbol || visited.has(symbol)) continue;
1268
+ visited.add(symbol);
1269
+ if (symbol.flags & ts2.SymbolFlags.Alias) {
1270
+ queue.push(checker.getAliasedSymbol(symbol));
1271
+ continue;
1272
+ }
1273
+ declaringSymbol ??= symbol;
1274
+ const comment = renderJsDocText(symbol.getDocumentationComment(checker));
1275
+ if (comment) {
1276
+ const tags2 = symbol.getJsDocTags(checker);
1277
+ return {
1278
+ documentation: {
1279
+ summary: firstParagraph(comment),
1280
+ intents: intentsOf(tags2),
1281
+ example: exampleOf(tags2),
1282
+ definedInPackage: isDeclaredInPackage({ symbol, root: params.root }),
1283
+ internal: tags2.some((tag) => tag.name === "internal"),
1284
+ declaredAt: declarationKey({ symbol, root: params.root })
1285
+ },
1286
+ declaringSymbol: symbol
1287
+ };
1288
+ }
1289
+ for (const declaration of symbol.declarations ?? []) {
1290
+ if (ts2.isShorthandPropertyAssignment(declaration))
1291
+ queue.push(checker.getShorthandAssignmentValueSymbol(declaration));
1292
+ else if (ts2.isPropertyAssignment(declaration))
1293
+ queue.push(assignedSymbol({ checker, initializer: declaration.initializer }));
1294
+ else if (ts2.isExportSpecifier(declaration))
1295
+ queue.push(checker.getExportSpecifierLocalTargetSymbol(declaration));
1296
+ }
1297
+ }
1298
+ const declaringFunction = lastDeclared(visited) ?? declaringSymbol;
1299
+ const tags = declaringFunction?.getJsDocTags(checker) ?? [];
1300
+ return {
1301
+ documentation: {
1302
+ summary: void 0,
1303
+ intents: intentsOf(tags),
1304
+ example: exampleOf(tags),
1305
+ internal: tags.some((tag) => tag.name === "internal"),
1306
+ definedInPackage: isDeclaredInPackage({ symbol: declaringFunction, root: params.root }),
1307
+ declaredAt: declarationKey({ symbol: declaringFunction, root: params.root })
1308
+ },
1309
+ declaringSymbol: declaringFunction
1310
+ };
1311
+ }
1312
+ function firstParagraph(comment) {
1313
+ return comment.split(/\n\s*\n/)[0].replace(/\s+/g, " ").trim();
1314
+ }
1315
+ function intentsOf(tags) {
1316
+ return tags.filter((tag) => tag.name === "intent").flatMap((tag) => parseIntentText(renderJsDocText(tag.text)));
1317
+ }
1318
+ function exampleOf(tags) {
1319
+ const tag = tags.find((candidate) => candidate.name === "example");
1320
+ if (!tag) return void 0;
1321
+ const text = renderJsDocText(tag.text);
1322
+ const fenced = text.match(FENCED_CODE_PATTERN);
1323
+ const code = (fenced ? fenced[1] : text).trim();
1324
+ return code || void 0;
1325
+ }
1326
+ function parseIntentText(text) {
1327
+ const intents = [];
1328
+ let depth = 0;
1329
+ let current = "";
1330
+ for (const character of text.split(/\n\s*\n/)[0]) {
1331
+ if (character === "(") depth++;
1332
+ else if (character === ")") depth = Math.max(0, depth - 1);
1333
+ if (character === "," && depth === 0) {
1334
+ intents.push(current);
1335
+ current = "";
1336
+ } else current += character;
1337
+ }
1338
+ intents.push(current);
1339
+ return intents.map((intent) => intent.replace(/\s+/g, " ").trim()).filter(Boolean);
1340
+ }
1341
+ function assignedSymbol(params) {
1342
+ const { checker, initializer } = params;
1343
+ if (ts2.isIdentifier(initializer)) return checker.getSymbolAtLocation(initializer);
1344
+ if (ts2.isPropertyAccessExpression(initializer))
1345
+ return checker.getSymbolAtLocation(initializer.name);
1346
+ return void 0;
1347
+ }
1348
+ function lastDeclared(symbols) {
1349
+ return [...symbols].reverse().find((symbol) => (symbol.declarations ?? []).some(declaresFunction));
1350
+ }
1351
+ function declaresFunction(declaration) {
1352
+ if (ts2.isFunctionDeclaration(declaration) || ts2.isMethodDeclaration(declaration)) return true;
1353
+ if (!ts2.isVariableDeclaration(declaration) || !declaration.initializer) return false;
1354
+ return ts2.isArrowFunction(declaration.initializer) || ts2.isFunctionExpression(declaration.initializer);
1355
+ }
1356
+ function declarationKey(params) {
1357
+ const declaration = params.symbol?.declarations?.[0];
1358
+ if (!declaration) return void 0;
1359
+ return `${relative2(params.root, declaration.getSourceFile().fileName)}:${declaration.getStart()}`;
1360
+ }
1361
+ function isDeclaredInPackage(params) {
1362
+ const fileName = params.symbol?.declarations?.[0]?.getSourceFile().fileName;
1363
+ if (!fileName) return false;
1364
+ const path = relative2(params.root, fileName);
1365
+ return !path.startsWith("..") && !path.split(/[\\/]/).includes("node_modules");
1366
+ }
1367
+ function declarationOf(symbol) {
1368
+ return symbol.valueDeclaration ?? symbol.declarations?.[0];
1369
+ }
1370
+ function isPublic(symbol) {
1371
+ const declaration = declarationOf(symbol);
1372
+ return !declaration || !(ts2.getCombinedModifierFlags(declaration) & (ts2.ModifierFlags.Private | ts2.ModifierFlags.Protected));
1373
+ }
1374
+ function isTypeScriptLibrary(symbol) {
1375
+ return (declarationOf(symbol)?.getSourceFile()?.fileName ?? "").includes(
1376
+ "/node_modules/typescript/"
1377
+ );
1378
+ }
1379
+
1380
+ // src/lib/binding-refs.ts
1381
+ function refsOf(binding) {
1382
+ if (binding.kind === "namespace") {
1383
+ return {
1384
+ imports: [`import type { ${binding.name} } from '${binding.import}'`],
1385
+ elementsOf: `${binding.name}.ElementsOf`,
1386
+ query: `${binding.name}.Query`,
1387
+ transaction: `${binding.name}.Transaction`,
1388
+ generic: (genericName, element) => `${binding.name}.${genericName}<${element}>`,
1389
+ nullary: (typeName2) => `${binding.name}.${typeName2}`
1390
+ };
1391
+ }
1392
+ return {
1393
+ imports: [
1394
+ `import type * as ${binding.coreAlias} from '${binding.coreImport}'`,
1395
+ `import type { ${binding.configType} } from '${binding.configImport}'`
1396
+ ],
1397
+ elementsOf: `${binding.coreAlias}.ElementsOf<${binding.configType}>`,
1398
+ query: `${binding.coreAlias}.Query<${binding.configType}>`,
1399
+ transaction: `${binding.coreAlias}.Transaction<${binding.configType}>`,
1400
+ generic: (genericName, element) => `${binding.coreAlias}.${genericName}<${binding.configType}, ${element}>`,
1401
+ nullary: (typeName2) => `${binding.coreAlias}.${typeName2}<${binding.configType}>`
1402
+ };
1403
+ }
1404
+
1405
+ // src/lib/discovery-entry.ts
1406
+ function discoveryEntry(binding) {
1407
+ const refs = refsOf(binding);
1408
+ return [
1409
+ ...refs.imports,
1410
+ `declare const q: ${refs.query}`,
1411
+ `declare const tx: ${refs.transaction}`,
1412
+ `declare const doc: ${refs.nullary("Document")}`,
1413
+ `declare const project: ${refs.nullary("Project")}`,
1414
+ `export { q, tx, doc, project }`,
1415
+ ""
1416
+ ].join("\n");
1417
+ }
1418
+
1419
+ // src/commands/members.constants.ts
1420
+ var MEMBERS_VALUE_OPTIONS = [
1421
+ "namespace",
1422
+ "entry",
1423
+ "version",
1424
+ "tsconfig",
1425
+ "constants-dir",
1426
+ "out"
1427
+ ];
1428
+ var MEMBERS_USAGE = "usage: dialecte members <expression> [--json] [--version <v>] (in an app: --namespace <Name> --entry <module exporting it>)";
1429
+
1430
+ // src/commands/skills.constants.ts
1431
+ var METHOD_DISCOVERY_DEPTH = 3;
1432
+
1433
+ // src/commands/members.ts
1434
+ function readMemberEntries(params) {
1435
+ const missing = missingPackage({ cwd: params.cwd });
1436
+ if (missing) return { kind: "output", output: missing };
1437
+ const { argv, cwd } = params;
1438
+ const [expression] = positionalArguments({ argv, valueOptions: MEMBERS_VALUE_OPTIONS });
1439
+ const [target] = resolveTargets(argv, cwd);
1440
+ if (!expression || !target)
1441
+ return { kind: "output", output: { output: `${MEMBERS_USAGE}
1442
+ `, exitCode: 2 } };
1443
+ const entries = discoverMethods({
1444
+ entrySource: discoveryEntry(target.binding),
1445
+ tsconfig: tsconfigOf(argv, cwd),
1446
+ root: cwd,
1447
+ // one level below the expression, so each group it holds is counted
1448
+ maxDepth: Math.max(METHOD_DISCOVERY_DEPTH, discoveryPath(expression).split(".").length)
1449
+ });
1450
+ return { kind: "entries", entries, expression };
1451
+ }
1452
+
1453
+ // src/lib/models/answer-models.ts
1454
+ function answerModels(params) {
1455
+ const knownIds = VENDOR_IDS;
1456
+ if (params.vendor === void 0)
1457
+ return {
1458
+ output: `dialecte models: no vendor known for this project. Run \`dialecte skills sync --vendor <${knownIds.join("|")}>\`, or pass \`--vendor <id>\`.
1459
+ `,
1460
+ exitCode: 2
1461
+ };
1462
+ if (!isVendorId(params.vendor))
1463
+ return {
1464
+ output: `dialecte models: unknown vendor "${params.vendor}" (known: ${knownIds.join(", ")})
1465
+ `,
1466
+ exitCode: 1
1467
+ };
1468
+ const models = MODEL_TIERS.vendors[params.vendor];
1469
+ if (params.json)
1470
+ return {
1471
+ output: `${JSON.stringify(
1472
+ {
1473
+ vendor: params.vendor,
1474
+ checkedAt: MODEL_TIERS.checkedAt,
1475
+ tiers: models.tiers,
1476
+ ...models.note === void 0 ? {} : { note: models.note },
1477
+ definitions: TIER_DEFINITIONS
1478
+ },
1479
+ null,
1480
+ " "
1481
+ )}
1482
+ `,
1483
+ exitCode: 0
1484
+ };
1485
+ const width = Math.max(...TIER_NAMES.map((tier) => tier.length)) + 2;
1486
+ const lines = [
1487
+ `vendor ${params.vendor} (checked ${MODEL_TIERS.checkedAt})`,
1488
+ ...TIER_NAMES.map((tier) => `${tier.padEnd(width)}${renderModel(models.tiers[tier])}`),
1489
+ ...models.note === void 0 ? [] : [`note: ${models.note}`],
1490
+ "",
1491
+ ...TIER_NAMES.map((tier) => `${tier.padEnd(width)}${TIER_DEFINITIONS[tier]}`)
1492
+ ];
1493
+ return { output: `${lines.join("\n")}
1494
+ `, exitCode: 0 };
1495
+ }
1496
+ function renderModel(tierModel) {
1497
+ return tierModel.effort === void 0 ? tierModel.model : `${tierModel.model} (${tierModel.effort})`;
1498
+ }
1499
+
1500
+ // src/commands/models.ts
1501
+ function runModels(params) {
1502
+ const missing = missingPackage({ cwd: params.cwd });
1503
+ if (missing) return { ...missing, warnings: "" };
1504
+ const argv = [...params.argv];
1505
+ const remembered = readRememberedVendor(params.cwd);
1506
+ const answer = answerModels({
1507
+ vendor: getArg(argv, "vendor") ?? remembered.vendor,
1508
+ json: hasFlag(argv, "json")
1509
+ });
1510
+ return { ...answer, warnings: remembered.warnings.map((warning) => `\u26A0\uFE0F ${warning}
1511
+ `).join("") };
1512
+ }
1513
+
1514
+ // src/lib/schema/describe-element.ts
1515
+ function describeElement(params) {
1516
+ const { config, readers, packageName: packageName2 } = params.dialecte;
1517
+ const record = { tagName: params.tagName, parent: null, attributes: [] };
1518
+ const definition = config.elements.includes(params.tagName) ? readers.resolveDefinition({ dialecteConfig: config, record }) : void 0;
1519
+ if (definition === void 0) return void 0;
1520
+ const occurrences = readers.childOccurrences({ definition });
1521
+ const children = readers.orderByConfigSequence({
1522
+ parentTagName: definition.tag,
1523
+ children: definition.children.sequence.map((tagName) => ({ tagName })),
1524
+ childrenConfig: config.children
1525
+ }).map(({ tagName }) => ({ tag: tagName, ...occurrences[tagName] }));
1526
+ return {
1527
+ packageName: packageName2,
1528
+ tag: definition.tag,
1529
+ namespace: definition.namespace.uri,
1530
+ parents: definition.parents,
1531
+ children,
1532
+ anyChild: definition.children.any === true,
1533
+ attributes: definition.attributes.sequence.map(function describeAttribute(attributeName) {
1534
+ const rules = readers.getAttributeRules({ dialecteConfig: config, record, attributeName });
1535
+ const datatype = definition.attributes.details[attributeName]?.type;
1536
+ return {
1537
+ name: attributeName,
1538
+ required: rules.isRequired,
1539
+ identityField: rules.isIdentityField,
1540
+ default: rules.default,
1541
+ fixed: rules.fixed,
1542
+ namespace: rules.namespace?.uri,
1543
+ type: typeName(datatype),
1544
+ enumeration: readers.enumeratedValues(datatype),
1545
+ patterns: readers.valuePatterns(datatype).map((pattern) => pattern.source)
1546
+ };
1547
+ }),
1548
+ text: definition.textContent ? typeName(definition.textContent.type) ?? "string" : void 0,
1549
+ xsiTypes: readers.admittedXsiTypes({ dialecteConfig: config, record })
1550
+ };
1551
+ }
1552
+ function typeName(datatype) {
1553
+ if (datatype === void 0) return void 0;
1554
+ if ("builtin" in datatype) return datatype.builtin;
1555
+ return "list" in datatype ? "list" : "union";
1556
+ }
1557
+
1558
+ // src/lib/schema/schema.constants.ts
1559
+ var CORE_PACKAGE3 = "@dialecte/core";
1560
+ var CORE_READERS_ENTRY = "@dialecte/core/utils";
1561
+ var CORE_READER_NAMES = [
1562
+ "resolveDefinition",
1563
+ "getAttributeRules",
1564
+ "enumeratedValues",
1565
+ "valuePatterns",
1566
+ "admittedXsiTypes",
1567
+ "childOccurrences",
1568
+ "orderByConfigSequence"
1569
+ ];
1570
+ var SUGGESTION_LIMIT = 5;
1571
+
1572
+ // src/lib/schema/answer-schema.ts
1573
+ function answerSchema(params) {
1574
+ const { loaded, tagName } = params;
1575
+ const elements = loaded.dialectes.flatMap(
1576
+ (dialecte) => describeElement({ dialecte, tagName }) ?? []
1577
+ );
1578
+ if (params.json)
1579
+ return {
1580
+ output: `${JSON.stringify({ elements, skipped: loaded.skipped }, null, " ")}
1581
+ `,
1582
+ exitCode: elements.length ? 0 : 1
1583
+ };
1584
+ if (elements.length) return { output: elements.map(renderElement).join("\n"), exitCode: 0 };
1585
+ const skipped = loaded.skipped.length ? ` (skipped ${loaded.skipped.map((entry) => `${entry.packageName}: ${entry.reason}`).join("; ")})` : "";
1586
+ if (loaded.dialectes.length === 0)
1587
+ return { output: `no installed dialecte holds "${tagName}"${skipped}
1588
+ `, exitCode: 1 };
1589
+ const suggestions = loaded.dialectes.map((dialecte) => {
1590
+ const closest = closestNames({
1591
+ name: tagName,
1592
+ candidates: dialecte.config.elements,
1593
+ limit: SUGGESTION_LIMIT
1594
+ });
1595
+ return `no element "${tagName}" in ${dialecte.packageName}${closest.length ? ` - closest: ${closest.join(", ")}` : ""}`;
1596
+ });
1597
+ return { output: `${suggestions.join("\n")}${skipped}
1598
+ `, exitCode: 1 };
1599
+ }
1600
+ function renderElement(element) {
1601
+ const lines = [
1602
+ `${element.tag} ${element.packageName} {${element.namespace}}`,
1603
+ `parents: ${element.parents.join(", ") || "none (the root)"}`
1604
+ ];
1605
+ if (element.children.length || element.anyChild) lines.push("children, in order:");
1606
+ else lines.push("children: none");
1607
+ for (const child of element.children)
1608
+ lines.push(` ${child.tag} ${child.min}..${child.max ?? "*"}`);
1609
+ if (element.anyChild) lines.push(" any element of another namespace");
1610
+ lines.push(element.attributes.length ? "attributes:" : "attributes: none");
1611
+ for (const attribute of element.attributes) lines.push(` ${renderAttribute(attribute)}`);
1612
+ lines.push(`text: ${element.text ?? "none"}`);
1613
+ if (element.xsiTypes.length) lines.push(`xsi:type: ${element.xsiTypes.join(", ")}`);
1614
+ return `${lines.join("\n")}
1615
+ `;
1616
+ }
1617
+ function renderAttribute(attribute) {
1618
+ const parts = [
1619
+ // a foreign attribute is stored and written with its prefix (`ext:cA`): the name says it
1620
+ attribute.name,
1621
+ attribute.required ? "required" : "optional"
1622
+ ];
1623
+ if (attribute.identityField) parts.push("identity");
1624
+ if (attribute.type) parts.push(attribute.type);
1625
+ if (attribute.fixed !== void 0) parts.push(`fixed ${JSON.stringify(attribute.fixed)}`);
1626
+ if (attribute.default !== void 0) parts.push(`default ${JSON.stringify(attribute.default)}`);
1627
+ if (attribute.enumeration.length) parts.push(`one of: ${attribute.enumeration.join(", ")}`);
1628
+ for (const pattern of attribute.patterns) parts.push(`pattern ${pattern}`);
1629
+ return parts.join(" ");
1630
+ }
1631
+
1632
+ // src/lib/schema/load-dialectes.ts
1633
+ import { existsSync as existsSync9, readFileSync as readFileSync7 } from "fs";
1634
+ import { createRequire } from "module";
1635
+ import { join as join10 } from "path";
1636
+ import { pathToFileURL } from "url";
1637
+ async function loadDialectes(params) {
1638
+ const folders = [
1639
+ params.cwd,
1640
+ ...dependencyNames(params.cwd).flatMap(
1641
+ (name) => findInstalledPackage({ cwd: params.cwd, name }) ?? []
1642
+ )
1643
+ ];
1644
+ const result = { dialectes: [], skipped: [] };
1645
+ for (const folder of folders) {
1646
+ const manifest = readManifest(folder);
1647
+ if (!manifest?.name || !isBuiltOnCore(manifest)) continue;
1648
+ try {
1649
+ const loaded = await loadDialecte({ folder, manifest, packageName: manifest.name });
1650
+ if (loaded) result.dialectes.push(loaded);
1651
+ } catch (error) {
1652
+ result.skipped.push({
1653
+ packageName: manifest.name,
1654
+ reason: error instanceof Error ? error.message : String(error)
1655
+ });
1656
+ }
1657
+ }
1658
+ result.dialectes.sort((left, right) => TEXT_COLLATOR.compare(left.packageName, right.packageName));
1659
+ return result;
1660
+ }
1661
+ async function loadDialecte(params) {
1662
+ let config;
1663
+ for (const file of entryFiles(params)) {
1664
+ const exported = await import(pathToFileURL(file).href);
1665
+ config = Object.values(exported).find(isDialecteConfig);
1666
+ if (config) break;
1667
+ }
1668
+ if (!config) return void 0;
1669
+ const readersFile = createRequire(join10(params.folder, "package.json")).resolve(CORE_READERS_ENTRY);
1670
+ const readers = await import(pathToFileURL(readersFile).href);
1671
+ if (!isCoreReaders(readers))
1672
+ throw new Error(
1673
+ `its core (${readersFile}) lacks ${CORE_READER_NAMES.filter((name) => typeof readers[name] !== "function").join(", ")}: update @dialecte/core`
1674
+ );
1675
+ return { packageName: params.packageName, config, readers };
1676
+ }
1677
+ function readManifest(folder) {
1678
+ const path = join10(folder, "package.json");
1679
+ return existsSync9(path) ? JSON.parse(readFileSync7(path, "utf8")) : void 0;
1680
+ }
1681
+ function isBuiltOnCore(manifest) {
1682
+ return manifest.name !== CORE_PACKAGE3 && (manifest.dependencies?.[CORE_PACKAGE3] !== void 0 || manifest.peerDependencies?.[CORE_PACKAGE3] !== void 0);
1683
+ }
1684
+ function entryFiles(params) {
1685
+ const { exports, main } = params.manifest;
1686
+ const targets = exports === void 0 ? main ? [[".", main]] : [] : typeof exports === "string" ? [[".", exports]] : Object.entries(exports);
1687
+ return targets.filter(([subpath]) => !subpath.split("/").includes("test") && !subpath.includes("*")).flatMap(([, target]) => {
1688
+ const file = fileOf(target);
1689
+ return file && file.endsWith("js") ? [join10(params.folder, file)] : [];
1690
+ }).map(function existingFile(file) {
1691
+ if (!existsSync9(file))
1692
+ throw new Error(`entry file not found: ${file} (is the package built?)`);
1693
+ return file;
1694
+ });
1695
+ }
1696
+ function fileOf(target) {
1697
+ if (typeof target === "string") return target;
1698
+ const file = target.import ?? target.node ?? target.default;
1699
+ return typeof file === "string" ? file : void 0;
1700
+ }
1701
+ function isDialecteConfig(value) {
1702
+ return typeof value === "object" && value !== null && "rootElementName" in value && typeof value.rootElementName === "string" && "definition" in value && typeof value.definition === "object";
1703
+ }
1704
+ function isCoreReaders(module) {
1705
+ return CORE_READER_NAMES.every((name) => typeof module[name] === "function");
1706
+ }
1707
+
1708
+ // src/commands/schema.constants.ts
1709
+ var SCHEMA_VALUE_OPTIONS = ["package"];
1710
+ var SCHEMA_USAGE = "usage: dialecte schema <Tag> [--package <name>] [--json]";
1711
+
1712
+ // src/commands/schema.ts
1713
+ async function readSchemaDialectes(params) {
1714
+ const missing = missingPackage({ cwd: params.cwd });
1715
+ if (missing) return { kind: "output", output: missing };
1716
+ const [tagName] = positionalArguments({ argv: params.argv, valueOptions: SCHEMA_VALUE_OPTIONS });
1717
+ if (!tagName) return { kind: "output", output: { output: `${SCHEMA_USAGE}
1718
+ `, exitCode: 2 } };
1719
+ const packageName2 = getArg(params.argv, "package");
1720
+ const loaded = await loadDialectes({ cwd: params.cwd });
1721
+ return {
1722
+ kind: "dialectes",
1723
+ tagName,
1724
+ packageName: packageName2,
1725
+ installed: loaded.dialectes.map((dialecte) => dialecte.packageName),
1726
+ loaded: {
1727
+ dialectes: loaded.dialectes.filter(
1728
+ (dialecte) => packageName2 === void 0 || dialecte.packageName === packageName2
1729
+ ),
1730
+ skipped: loaded.skipped
1731
+ }
1732
+ };
1733
+ }
1734
+ export {
1735
+ answerMembers,
1736
+ answerSchema,
1737
+ packagesText,
1738
+ readApiIndexes,
1739
+ readCliVersion,
1740
+ readMemberEntries,
1741
+ readSchemaDialectes,
1742
+ runApi,
1743
+ runDoctor,
1744
+ runModels
1745
+ };