@stillwind/analysis 0.0.0-stage → 0.1.0-rc.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/memory.js ADDED
@@ -0,0 +1,113 @@
1
+ // src/memory.ts
2
+ /**
3
+ * Serializes in-memory analyses and discards reports from obsolete document revisions.
4
+ *
5
+ * @param options - Project membership, compiler operation, and optional resource cleanup.
6
+ * @returns A URI-based service. It supplies snapshots to compile but performs no module resolution
7
+ * itself. Closing waits for queued work and calls the cleanup operation once.
8
+ */
9
+ function createMemoryAnalysisWorkspace(options) {
10
+ const documents = /* @__PURE__ */ new Map();
11
+ let revision = 0;
12
+ let queue = Promise.resolve();
13
+ let closed = false;
14
+ let closing;
15
+ return {
16
+ /**
17
+ * Replaces an open buffer and advances the workspace revision when its state changes.
18
+ * @param uri - Original document URI, including dependencies outside the target scope.
19
+ * @param source - Complete unsaved text.
20
+ * @param version - Increasing safe integer. An identical update at the same version is accepted.
21
+ * @throws If the service is closed or the version is invalid or does not increase.
22
+ */
23
+ update(uri, source, version) {
24
+ if (closed) throw new Error("Analysis workspace is closed");
25
+ const previous = documents.get(uri);
26
+ if (previous?.version === version && previous.source === source) return;
27
+ if (!Number.isSafeInteger(version) || previous && previous.version >= version) throw new Error("Analysis document versions must increase");
28
+ documents.set(uri, {
29
+ source,
30
+ version
31
+ });
32
+ revision++;
33
+ },
34
+ /**
35
+ * Removes a buffer and advances the revision if it existed.
36
+ * @param uri - Original document URI. Unknown URIs have no effect.
37
+ */
38
+ closeDocument(uri) {
39
+ if (documents.delete(uri)) revision++;
40
+ },
41
+ /**
42
+ * Captures open buffers and queues compilation for an included target.
43
+ * @param uri - Target URI tested by the embedding's includes callback.
44
+ * @param signal - Optional cancellation checked before and after compilation.
45
+ * @returns One project result, or no result for an excluded target. Compiler failures become
46
+ * incomplete results, and stale or cancelled results omit reports.
47
+ * @throws If the service is closed or the membership callback fails.
48
+ */
49
+ analyze(uri, signal) {
50
+ if (closed) return Promise.reject(/* @__PURE__ */ new Error("Analysis workspace is closed"));
51
+ if (!options.includes(uri)) return Promise.resolve([]);
52
+ const captured = revision;
53
+ const snapshot = new Map([...documents].map(([uri, doc]) => [uri, doc.source]));
54
+ const task = queue.then(async () => {
55
+ /**
56
+ * Classifies work that can no longer publish results from the captured revision.
57
+ * @returns `cancelled` for an aborted signal, `stale` for a newer revision, or undefined.
58
+ */
59
+ const obsolete = () => signal?.aborted ? "cancelled" : captured !== revision ? "stale" : void 0;
60
+ let result = {
61
+ entry: uri,
62
+ revision: captured,
63
+ status: "incomplete",
64
+ reports: []
65
+ };
66
+ if (!obsolete()) try {
67
+ result = {
68
+ ...result,
69
+ ...await options.compile({
70
+ uri,
71
+ revision: captured,
72
+ documents: snapshot,
73
+ signal
74
+ })
75
+ };
76
+ } catch (error) {
77
+ result.error = String(error);
78
+ }
79
+ const status = obsolete();
80
+ if (status) result = {
81
+ entry: uri,
82
+ revision: captured,
83
+ status,
84
+ reports: []
85
+ };
86
+ return [{
87
+ project: 0,
88
+ config: options.config,
89
+ result
90
+ }];
91
+ });
92
+ queue = task.catch(() => {});
93
+ return task;
94
+ },
95
+ /**
96
+ * Invalidates queued snapshots and invokes the embedding's cleanup after queued work.
97
+ * @returns The same cleanup promise on repeated calls.
98
+ * @throws If the embedding's cleanup fails.
99
+ */
100
+ close() {
101
+ closing ??= (async () => {
102
+ closed = true;
103
+ revision++;
104
+ await queue;
105
+ await options.close?.();
106
+ })();
107
+ return closing;
108
+ }
109
+ };
110
+ }
111
+ export { createMemoryAnalysisWorkspace };
112
+
113
+ //# sourceMappingURL=memory.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"memory.js","names":[],"sources":["../src/memory.ts"],"sourcesContent":["import type { AnalysisResult, AnalysisWorkspaceService, WorkspaceResult } from \"./workspace.ts\";\n\n/** Compiler input captured from URI documents before asynchronous compilation starts. */\nexport interface MemoryAnalysisInput {\n /** Requested target URI accepted by the embedding's includes callback. */\n uri: string;\n /** Workspace change counter captured when the request was queued. */\n revision: number;\n /** Original text of all open documents, keyed by URI. The snapshot is independent of later updates. */\n documents: ReadonlyMap<string, string>;\n /** Optional cancellation signal. The workspace also checks it before and after calling compile. */\n signal?: AbortSignal;\n}\n\n/** Supplies the browser's WASM compiler, module loader, and type-facts service. */\nexport interface MemoryAnalysisOptions {\n /** Identifies the project in diagnostics. It need not be a filesystem path. */\n config: string;\n /**\n * Tests whether this workspace owns a target. Dependency buffers can be outside this scope.\n *\n * @param uri - Requested target URI.\n * @returns Whether compile should run for this target.\n */\n includes(uri: string): boolean;\n /**\n * Runs the embedding's compiler against one captured snapshot.\n *\n * @param input - Target, revision, open buffers, and optional cancellation signal.\n * @returns Reports and coverage information for the captured revision. Complete describes analysis\n * coverage. It does not imply that every report is successful.\n * @throws If compiler or module services fail. The workspace returns the error as an incomplete result.\n */\n compile(input: MemoryAnalysisInput): Promise<\n Pick<AnalysisResult, \"reports\" | \"dependencies\" | \"unverified\" | \"generation\" | \"error\"> & {\n /** Coverage of the captured snapshot. Compiler error reports can still have complete coverage. */\n status: \"complete\" | \"incomplete\";\n }\n >;\n /**\n * Releases resources after queued compilations finish. Called once during workspace closure.\n *\n * @returns Nothing, or a promise for asynchronous cleanup.\n * @throws If resource cleanup fails. The workspace's close promise rejects.\n */\n close?(): void | Promise<void>;\n}\n\n/**\n * Serializes in-memory analyses and discards reports from obsolete document revisions.\n *\n * @param options - Project membership, compiler operation, and optional resource cleanup.\n * @returns A URI-based service. It supplies snapshots to compile but performs no module resolution\n * itself. Closing waits for queued work and calls the cleanup operation once.\n */\nexport function createMemoryAnalysisWorkspace(\n options: MemoryAnalysisOptions,\n): AnalysisWorkspaceService {\n const documents = new Map<\n string,\n {\n /** Complete unsaved original document text. */\n source: string;\n /** Last accepted safe integer version while this URI is open. */\n version: number;\n }\n >();\n\n let revision = 0;\n let queue: Promise<unknown> = Promise.resolve();\n let closed = false;\n let closing: Promise<void> | undefined;\n\n return {\n /**\n * Replaces an open buffer and advances the workspace revision when its state changes.\n * @param uri - Original document URI, including dependencies outside the target scope.\n * @param source - Complete unsaved text.\n * @param version - Increasing safe integer. An identical update at the same version is accepted.\n * @throws If the service is closed or the version is invalid or does not increase.\n */\n update(uri, source, version) {\n if (closed) {\n throw new Error(\"Analysis workspace is closed\");\n }\n const previous = documents.get(uri);\n if (previous?.version === version && previous.source === source) {\n return;\n }\n if (!Number.isSafeInteger(version) || (previous && previous.version >= version)) {\n throw new Error(\"Analysis document versions must increase\");\n }\n documents.set(uri, { source, version });\n revision++;\n },\n /**\n * Removes a buffer and advances the revision if it existed.\n * @param uri - Original document URI. Unknown URIs have no effect.\n */\n closeDocument(uri) {\n if (documents.delete(uri)) {\n revision++;\n }\n },\n /**\n * Captures open buffers and queues compilation for an included target.\n * @param uri - Target URI tested by the embedding's includes callback.\n * @param signal - Optional cancellation checked before and after compilation.\n * @returns One project result, or no result for an excluded target. Compiler failures become\n * incomplete results, and stale or cancelled results omit reports.\n * @throws If the service is closed or the membership callback fails.\n */\n analyze(uri, signal): Promise<WorkspaceResult[]> {\n if (closed) {\n return Promise.reject(new Error(\"Analysis workspace is closed\"));\n }\n if (!options.includes(uri)) {\n return Promise.resolve([]);\n }\n const captured = revision;\n const snapshot = new Map([...documents].map(([uri, doc]) => [uri, doc.source]));\n const task = queue.then(async () => {\n /**\n * Classifies work that can no longer publish results from the captured revision.\n * @returns `cancelled` for an aborted signal, `stale` for a newer revision, or undefined.\n */\n const obsolete = () =>\n signal?.aborted\n ? (\"cancelled\" as const)\n : captured !== revision\n ? (\"stale\" as const)\n : undefined;\n let result: AnalysisResult = {\n entry: uri,\n revision: captured,\n status: \"incomplete\",\n reports: [],\n };\n if (!obsolete()) {\n try {\n result = {\n ...result,\n ...(await options.compile({\n uri,\n revision: captured,\n documents: snapshot,\n signal,\n })),\n };\n } catch (error) {\n result.error = String(error);\n }\n }\n const status = obsolete();\n if (status) {\n result = {\n entry: uri,\n revision: captured,\n status,\n reports: [],\n };\n }\n return [\n {\n project: 0,\n config: options.config,\n result,\n },\n ];\n });\n queue = task.catch(() => {});\n return task;\n },\n /**\n * Invalidates queued snapshots and invokes the embedding's cleanup after queued work.\n * @returns The same cleanup promise on repeated calls.\n * @throws If the embedding's cleanup fails.\n */\n close() {\n closing ??= (async () => {\n closed = true;\n revision++;\n await queue;\n await options.close?.();\n })();\n return closing;\n },\n };\n}\n"],"mappings":";;;;;;;;AAuDA,SAAgB,8BACd,SAC0B;CAC1B,MAAM,4BAAY,IAAI,IAQpB;CAEF,IAAI,WAAW;CACf,IAAI,QAA0B,QAAQ,QAAQ;CAC9C,IAAI,SAAS;CACb,IAAI;CAEJ,OAAO;;;;;;;;EAQL,OAAO,KAAK,QAAQ,SAAS;GAC3B,IAAI,QACF,MAAM,IAAI,MAAM,8BAA8B;GAEhD,MAAM,WAAW,UAAU,IAAI,GAAG;GAClC,IAAI,UAAU,YAAY,WAAW,SAAS,WAAW,QACvD;GAEF,IAAI,CAAC,OAAO,cAAc,OAAO,KAAM,YAAY,SAAS,WAAW,SACrE,MAAM,IAAI,MAAM,0CAA0C;GAE5D,UAAU,IAAI,KAAK;IAAE;IAAQ;GAAQ,CAAC;GACtC;EACF;;;;;EAKA,cAAc,KAAK;GACjB,IAAI,UAAU,OAAO,GAAG,GACtB;EAEJ;;;;;;;;;EASA,QAAQ,KAAK,QAAoC;GAC/C,IAAI,QACF,OAAO,QAAQ,uBAAO,IAAI,MAAM,8BAA8B,CAAC;GAEjE,IAAI,CAAC,QAAQ,SAAS,GAAG,GACvB,OAAO,QAAQ,QAAQ,CAAC,CAAC;GAE3B,MAAM,WAAW;GACjB,MAAM,WAAW,IAAI,IAAI,CAAC,GAAG,SAAS,CAAC,CAAC,KAAK,CAAC,KAAK,SAAS,CAAC,KAAK,IAAI,MAAM,CAAC,CAAC;GAC9E,MAAM,OAAO,MAAM,KAAK,YAAY;;;;;IAKlC,MAAM,iBACJ,QAAQ,UACH,cACD,aAAa,WACV,UACD,KAAA;IACR,IAAI,SAAyB;KAC3B,OAAO;KACP,UAAU;KACV,QAAQ;KACR,SAAS,CAAC;IACZ;IACA,IAAI,CAAC,SAAS,GACZ,IAAI;KACF,SAAS;MACP,GAAG;MACH,GAAI,MAAM,QAAQ,QAAQ;OACxB;OACA,UAAU;OACV,WAAW;OACX;MACF,CAAC;KACH;IACF,SAAS,OAAO;KACd,OAAO,QAAQ,OAAO,KAAK;IAC7B;IAEF,MAAM,SAAS,SAAS;IACxB,IAAI,QACF,SAAS;KACP,OAAO;KACP,UAAU;KACV;KACA,SAAS,CAAC;IACZ;IAEF,OAAO,CACL;KACE,SAAS;KACT,QAAQ,QAAQ;KAChB;IACF,CACF;GACF,CAAC;GACD,QAAQ,KAAK,YAAY,CAAC,CAAC;GAC3B,OAAO;EACT;;;;;;EAMA,QAAQ;GACN,aAAa,YAAY;IACvB,SAAS;IACT;IACA,MAAM;IACN,MAAM,QAAQ,QAAQ;GACxB,EAAA,CAAG;GACH,OAAO;EACT;CACF;AACF"}
package/dist/node.d.ts ADDED
@@ -0,0 +1,152 @@
1
+ import { a as OpenAnalysisWorkspaces, r as AnalysisWorkspaceContext } from "./workspace-BF46yPpm.js";
2
+ import { t as lintReports } from "./reports-BKeFV47o.js";
3
+ import { AnalysisWorkspace, EditorEdit, WorkspaceResult } from "@stillwind/host";
4
+ /** Original buffer and ranges excluded by a formatter adapter. Paths are absolute. */
5
+ interface RewriteInput {
6
+ /** Absolute target path used for workspace membership and dependency resolution. */
7
+ file: string;
8
+ /** Complete original text against which edits are measured. */
9
+ source: string;
10
+ /** Half-open UTF-16 ranges in source. Only sorting accepts protected ranges. */
11
+ protectedRanges?: readonly {
12
+ /** Inclusive original UTF-16 offset. */
13
+ start: number;
14
+ /** Exclusive original UTF-16 offset. */
15
+ end: number;
16
+ }[];
17
+ }
18
+ /** Replacement text and independent project findings for one original buffer. */
19
+ interface RewriteResult {
20
+ /** Absolute path copied from the corresponding input. */
21
+ file: string;
22
+ /** Final text after sorting or converged fixes. */
23
+ code: string;
24
+ /** Sorting edits in the input buffer. Iterated lint fixes omit these edits. */
25
+ edits: EditorEdit[];
26
+ /** Findings for the analyzed input of the final pass, in project order. */
27
+ results: WorkspaceResult[];
28
+ }
29
+ /** A target that could not be read, rewritten, or saved. */
30
+ interface RewriteFileFailure {
31
+ /** Absolute path of the failed target. */
32
+ file: string;
33
+ /** Reason that reading, planning, or saving this target failed. */
34
+ message: string;
35
+ /** Analysis findings captured before planning failed, when available. */
36
+ results: WorkspaceResult[];
37
+ }
38
+ /** Selects configured source files for CLI analysis and rewriting. */
39
+ interface RewriteOptions {
40
+ /** Explicit configuration path, absolute or relative to cwd. Omission searches upward from cwd. */
41
+ config?: string;
42
+ /** Directory for configuration discovery and relative config paths. Defaults to process.cwd(). */
43
+ cwd?: string;
44
+ /** Additional globs relative to each project root. Omission or an empty list retains all configured targets. */
45
+ patterns?: string[];
46
+ }
47
+ /** Sorting results whose changed paths compare original and final source bytes. */
48
+ interface FormatResult {
49
+ /** Absolute path of the evaluated configuration. */
50
+ config: string;
51
+ /** Absolute paths that changed or would change, in sorted order. */
52
+ changed: string[];
53
+ /** Findings from the original sources, in configured project and target order. */
54
+ results: WorkspaceResult[];
55
+ /** Targets that could not be read, rewritten, or saved. */
56
+ failures: RewriteFileFailure[];
57
+ /** Failures return 2. Check mode otherwise returns 1 when any file would change. */
58
+ exitCode: 0 | 1 | 2;
59
+ }
60
+ /**
61
+ * Sorts configured targets and saves changed files unless check is true.
62
+ * @param options - Configuration discovery, target filters, and optional check mode.
63
+ * @returns Changed paths, original findings, and failures. Healthy targets continue after a failure.
64
+ * @throws If selection, configuration, worker communication, or cleanup fails.
65
+ */
66
+ export declare function format(options?: RewriteOptions & {
67
+ /** Whether to report changes without saving them. Defaults to false. */
68
+ check?: boolean;
69
+ }): Promise<FormatResult>;
70
+ /** Lint results preserve project membership and identify incomplete analysis. */
71
+ interface LintResult {
72
+ /** Absolute path of the evaluated configuration. */
73
+ config: string;
74
+ /** Target results in configured project order, including overlapping project memberships. */
75
+ results: WorkspaceResult[];
76
+ /** Files whose bytes changed when fix was requested. */
77
+ changed?: string[];
78
+ /** Targets that could not be read, fixed, or saved when fix was requested. */
79
+ failures?: RewriteFileFailure[];
80
+ /**
81
+ * - 0: successful checks
82
+ * - 1: compiler errors or denied lint
83
+ * - 2: incomplete execution
84
+ */
85
+ exitCode: 0 | 1 | 2;
86
+ }
87
+ /**
88
+ * Analyzes configured target scopes in a child process and closes it before returning.
89
+ *
90
+ * @param options - Configuration discovery and optional target filters. Omission checks all
91
+ * configured targets from the process working directory.
92
+ * @returns Results and an exit code. Readonly lint returns code 2 for empty selection or incomplete analysis.
93
+ * @throws If configuration discovery, worker initialization, target enumeration, or cleanup fails.
94
+ * Fix mode reports failures per target and continues with healthy targets. Empty selection throws.
95
+ */
96
+ export declare function lint(options?: RewriteOptions & {
97
+ /** Applies converged fixes and reports findings from the final source buffers. */
98
+ fix?: boolean;
99
+ }): Promise<LintResult>;
100
+ /**
101
+ * Formats findings and incomplete analysis for terminal output.
102
+ *
103
+ * @param result - Lint results whose reports use original document locations.
104
+ * @returns Text with one-based line and column positions. Duplicate findings are removed per
105
+ * project. Findings from overlapping projects remain separate. Successful results can return empty text.
106
+ */
107
+ export declare function formatLint(result: LintResult): string;
108
+ /**
109
+ * Opens one isolated Node analysis process for each distinct configuration.
110
+ *
111
+ * @param context - Workspace directory URIs. File URIs use upward configuration discovery.
112
+ * Other URI schemes cannot open Node workspaces. An empty list uses the process working directory.
113
+ * @param config - Optional explicit configuration path, resolved from the process working directory.
114
+ * When supplied, it replaces discovery from workspace folders.
115
+ * @returns Services keyed by absolute configuration path and separate initialization errors.
116
+ * Services accept file URIs, forward buffers to their workers, and discard cancelled results.
117
+ * @throws If converting a malformed file URI or closing a failed worker throws.
118
+ */
119
+ export declare function openNodeWorkspaces(context: AnalysisWorkspaceContext, config?: string): Promise<OpenAnalysisWorkspaces>;
120
+ /** Reuses an isolated process while refreshing trusted configuration for each formatting request. */
121
+ export declare class SourceFormatter {
122
+ #private;
123
+ private readonly config;
124
+ /**
125
+ * Starts the isolated worker that evaluates configuration on each formatting request.
126
+ * @param config - Configuration path resolved in the worker's inherited working directory.
127
+ */
128
+ constructor(config: string);
129
+ /**
130
+ * Sorts the supplied buffer with current project settings.
131
+ * Files outside all configured scopes return unchanged text. Requests are serialized and never write files.
132
+ * @param input - Original buffer and optional protected ranges. Relative paths are resolved from cwd.
133
+ * @returns The sorted buffer and original findings after configuration is reopened.
134
+ * @throws If configuration loading, parsing, analysis, project agreement, rewriting, or worker communication fails.
135
+ */
136
+ format(input: RewriteInput): Promise<RewriteResult>;
137
+ /**
138
+ * Waits for queued formatting and releases the child process. Stop submitting requests before closure.
139
+ * @returns Completion of worker cleanup.
140
+ * @throws If the worker's cleanup request fails.
141
+ */
142
+ close(): Promise<void>;
143
+ }
144
+ /**
145
+ * Finds a configuration above a source file or resolves an explicit path from cwd.
146
+ * @param file - Source path whose parent starts upward discovery. Relative paths use cwd.
147
+ * @param config - Optional explicit configuration path, returned without an existence check.
148
+ * @returns The absolute configuration path, or undefined when discovery finds none.
149
+ */
150
+ export declare function findFormatterConfig(file: string, config?: string): string | undefined;
151
+ export { type FormatResult, type LintResult, type RewriteFileFailure, type RewriteInput, type RewriteOptions, type RewriteResult, lintReports };
152
+ //# sourceMappingURL=node.d.ts.map