@pulsec/dts 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,241 @@
1
+ 'use strict';
2
+
3
+ const fs = require('node:fs');
4
+ const path = require('node:path');
5
+
6
+ /**
7
+ * Strips single-line comments, block comments, and trailing commas from JSONC
8
+ * without loading the TypeScript compiler.
9
+ */
10
+ function stripJsonc(input) {
11
+ let out = '';
12
+ const len = input.length;
13
+ let i = 0;
14
+
15
+ while (i < len) {
16
+ const ch = input[i];
17
+ if (ch === '"') {
18
+ const start = i;
19
+ i++;
20
+ while (i < len && input[i] !== '"') {
21
+ if (input[i] === '\\') i += 2;
22
+ else i++;
23
+ }
24
+ if (i < len) i++;
25
+ out += input.slice(start, i);
26
+ continue;
27
+ }
28
+ if (ch === '/' && input[i + 1] === '/') {
29
+ i += 2;
30
+ while (i < len && input[i] !== '\n' && input[i] !== '\r') i++;
31
+ continue;
32
+ }
33
+ if (ch === '/' && input[i + 1] === '*') {
34
+ const end = input.indexOf('*/', i + 2);
35
+ if (end < 0) throw new SyntaxError('Unterminated block comment in tsconfig');
36
+ i = end + 2;
37
+ continue;
38
+ }
39
+ out += ch;
40
+ i++;
41
+ }
42
+
43
+ // Strip trailing commas before `}` or `]` outside strings.
44
+ let cleaned = '';
45
+ const clen = out.length;
46
+ i = 0;
47
+ while (i < clen) {
48
+ const ch = out[i];
49
+ if (ch === '"') {
50
+ const start = i;
51
+ i++;
52
+ while (i < clen && out[i] !== '"') {
53
+ if (out[i] === '\\') i += 2;
54
+ else i++;
55
+ }
56
+ if (i < clen) i++;
57
+ cleaned += out.slice(start, i);
58
+ continue;
59
+ }
60
+ if (ch === ',') {
61
+ let j = i + 1;
62
+ while (j < clen && (out[j] === ' ' || out[j] === '\t' || out[j] === '\n' || out[j] === '\r')) {
63
+ j++;
64
+ }
65
+ if (out[j] === '}' || out[j] === ']') {
66
+ i++;
67
+ continue;
68
+ }
69
+ }
70
+ cleaned += ch;
71
+ i++;
72
+ }
73
+ return cleaned;
74
+ }
75
+
76
+ function parseJsonc(text, filePath) {
77
+ const cleaned = stripJsonc(text);
78
+ try {
79
+ const parsed = JSON.parse(cleaned);
80
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
81
+ throw new Error('tsconfig root must be a JSON object');
82
+ }
83
+ return parsed;
84
+ } catch (err) {
85
+ throw new Error(`Failed to parse tsconfig "${filePath}": ${err.message}`);
86
+ }
87
+ }
88
+
89
+ function resolveExtendsPath(fromDir, spec) {
90
+ const isRelOrAbs = spec.startsWith('./') || spec.startsWith('../') || spec === '.' || spec === '..' || path.isAbsolute(spec);
91
+ if (isRelOrAbs) {
92
+ const candidate = path.resolve(fromDir, spec);
93
+ if (fs.existsSync(candidate) && fs.statSync(candidate).isFile()) return candidate;
94
+ if (!candidate.endsWith('.json')) {
95
+ const withJson = `${candidate}.json`;
96
+ if (fs.existsSync(withJson) && fs.statSync(withJson).isFile()) return withJson;
97
+ }
98
+ const dirConfig = path.join(candidate, 'tsconfig.json');
99
+ if (fs.existsSync(dirConfig) && fs.statSync(dirConfig).isFile()) return dirConfig;
100
+ } else {
101
+ // Support package-based extends (preferring package.json#tsconfig, then tsconfig.json / .json).
102
+ const pkgCandidates = spec.endsWith('.json')
103
+ ? [spec]
104
+ : [`${spec}/package.json`, `${spec}/tsconfig.json`, `${spec}.json`, spec];
105
+ for (let i = 0; i < pkgCandidates.length; i++) {
106
+ try {
107
+ const resolved = require.resolve(pkgCandidates[i], { paths: [fromDir] });
108
+ if (resolved.endsWith('/package.json') || resolved.endsWith('\\package.json')) {
109
+ const pkg = JSON.parse(fs.readFileSync(resolved, 'utf8'));
110
+ if (pkg && typeof pkg.tsconfig === 'string') {
111
+ return path.resolve(path.dirname(resolved), pkg.tsconfig);
112
+ }
113
+ const siblingTc = path.join(path.dirname(resolved), 'tsconfig.json');
114
+ if (fs.existsSync(siblingTc) && fs.statSync(siblingTc).isFile()) return siblingTc;
115
+ continue;
116
+ }
117
+ if (resolved.endsWith('.json')) return resolved;
118
+ } catch {
119
+ // try next candidate
120
+ }
121
+ }
122
+ }
123
+ throw new Error(`Cannot resolve tsconfig extends "${spec}" from "${fromDir}"`);
124
+ }
125
+
126
+ function compilePathMatchers(pathsObj, pathsBaseDir) {
127
+ if (!pathsObj || typeof pathsObj !== 'object') return [];
128
+ const matchers = [];
129
+ for (const [pattern, targets] of Object.entries(pathsObj)) {
130
+ if (!Array.isArray(targets) || targets.length === 0) continue;
131
+ const starIdx = pattern.indexOf('*');
132
+ const prefix = starIdx >= 0 ? pattern.slice(0, starIdx) : pattern;
133
+ const suffix = starIdx >= 0 ? pattern.slice(starIdx + 1) : '';
134
+ const hasWildcard = starIdx >= 0;
135
+ const resolvedTargets = targets
136
+ .filter(t => typeof t === 'string')
137
+ .map(t => {
138
+ const tStar = t.indexOf('*');
139
+ return {
140
+ baseDir: pathsBaseDir,
141
+ hasWildcard: tStar >= 0,
142
+ prefix: tStar >= 0 ? t.slice(0, tStar) : t,
143
+ suffix: tStar >= 0 ? t.slice(tStar + 1) : '',
144
+ };
145
+ });
146
+ if (resolvedTargets.length > 0) {
147
+ matchers.push({ pattern, hasWildcard, prefix, suffix, targets: resolvedTargets });
148
+ }
149
+ }
150
+ // Longer static prefix wins (matches TypeScript's specificity rule).
151
+ matchers.sort((a, b) => {
152
+ if (a.hasWildcard !== b.hasWildcard) return a.hasWildcard ? 1 : -1;
153
+ return b.prefix.length - a.prefix.length;
154
+ });
155
+ return matchers;
156
+ }
157
+
158
+ function loadTsconfigInternal(configPath, seen) {
159
+ const absPath = path.resolve(configPath);
160
+ const realPath = fs.realpathSync(absPath);
161
+ if (seen.has(realPath)) {
162
+ throw new Error(`Circular tsconfig extends detected at "${absPath}"`);
163
+ }
164
+ seen.add(realPath);
165
+
166
+ const dir = path.dirname(absPath);
167
+ const raw = parseJsonc(fs.readFileSync(absPath, 'utf8'), absPath);
168
+
169
+ let mergedOptions = {};
170
+ let baseUrlDir = null;
171
+ let pathsBaseDir = null;
172
+ let rootDir = null;
173
+ let outDir = null;
174
+ let include = null;
175
+ let exclude = null;
176
+
177
+ if (raw.extends) {
178
+ const extList = Array.isArray(raw.extends) ? raw.extends : [raw.extends];
179
+ for (const extSpec of extList) {
180
+ if (typeof extSpec !== 'string') continue;
181
+ const extPath = resolveExtendsPath(dir, extSpec);
182
+ const base = loadTsconfigInternal(extPath, seen);
183
+ mergedOptions = { ...mergedOptions, ...base.compilerOptions };
184
+ if (base.baseUrl) baseUrlDir = base.baseUrl;
185
+ if (base.pathsBaseDir) pathsBaseDir = base.pathsBaseDir;
186
+ if (base.rootDir) rootDir = base.rootDir;
187
+ if (base.outDir) outDir = base.outDir;
188
+ if (base.include) include = base.include;
189
+ if (base.exclude) exclude = base.exclude;
190
+ }
191
+ }
192
+
193
+ const co = raw.compilerOptions && typeof raw.compilerOptions === 'object' ? raw.compilerOptions : {};
194
+ mergedOptions = { ...mergedOptions, ...co };
195
+
196
+ if (typeof co.baseUrl === 'string') {
197
+ baseUrlDir = path.resolve(dir, co.baseUrl);
198
+ }
199
+ if (co.paths && typeof co.paths === 'object') {
200
+ pathsBaseDir = baseUrlDir || dir;
201
+ }
202
+ if (typeof co.rootDir === 'string') {
203
+ rootDir = path.resolve(dir, co.rootDir);
204
+ }
205
+ if (typeof co.outDir === 'string') {
206
+ outDir = path.resolve(dir, co.outDir);
207
+ }
208
+ if (Array.isArray(raw.include)) include = raw.include.slice();
209
+ if (Array.isArray(raw.exclude)) exclude = raw.exclude.slice();
210
+
211
+ seen.delete(realPath);
212
+
213
+ return {
214
+ configPath: absPath,
215
+ configDir: dir,
216
+ compilerOptions: mergedOptions,
217
+ baseUrl: baseUrlDir,
218
+ pathsBaseDir: pathsBaseDir || baseUrlDir || dir,
219
+ pathMatchers: compilePathMatchers(mergedOptions.paths, pathsBaseDir || baseUrlDir || dir),
220
+ rootDir,
221
+ outDir,
222
+ include,
223
+ exclude,
224
+ };
225
+ }
226
+
227
+ /**
228
+ * Loads and resolves a tsconfig.json (including JSONC comments and `extends`).
229
+ */
230
+ function loadTsconfig(configPath) {
231
+ if (typeof configPath !== 'string' || !configPath) {
232
+ throw new TypeError('loadTsconfig requires a non-empty file path');
233
+ }
234
+ return loadTsconfigInternal(configPath, new Set());
235
+ }
236
+
237
+ module.exports = {
238
+ stripJsonc,
239
+ parseJsonc,
240
+ loadTsconfig,
241
+ };
@@ -0,0 +1,91 @@
1
+ import path from 'node:path';
2
+ import dts from './index.cjs';
3
+
4
+ const { buildDeclarations, createDtsCache } = dts;
5
+
6
+ /**
7
+ * Vite / Rollup plugin for ultra-fast `.d.ts` generation and rollup bundling
8
+ * powered by pulsec's native multi-threaded emitter.
9
+ */
10
+ export function pulsecDts(options = {}) {
11
+ const cache = options.cache === false ? null : (options.cache || createDtsCache());
12
+ let root = process.cwd();
13
+ let resolvedOutDir = options.outDir || null;
14
+ let libEntries = null;
15
+
16
+ return {
17
+ name: 'pulsec:dts',
18
+ apply: 'build',
19
+
20
+ configResolved(config) {
21
+ root = config.root || process.cwd();
22
+ if (options.outDir) {
23
+ resolvedOutDir = path.resolve(root, options.outDir);
24
+ } else if (config.build && config.build.outDir) {
25
+ resolvedOutDir = path.resolve(root, config.build.outDir);
26
+ }
27
+ if (!options.entry && !options.entries && !options.inputs && config.build && config.build.lib && config.build.lib.entry) {
28
+ libEntries = config.build.lib.entry;
29
+ }
30
+ },
31
+
32
+ async closeBundle() {
33
+ const resolveRel = p => (typeof p === 'string' ? path.resolve(root, p) : p);
34
+ const outDir = resolvedOutDir || path.resolve(root, 'dist');
35
+ const bundle = options.bundle ?? Boolean(options.entry || options.entries || libEntries);
36
+
37
+ let resolvedEntries = options.entries;
38
+ const resolveEntryMapOrList = val => {
39
+ if (typeof val === 'string') return [resolveRel(val)];
40
+ if (Array.isArray(val)) return val.map(resolveRel);
41
+ if (val && typeof val === 'object') {
42
+ const mapped = {};
43
+ for (const [k, v] of Object.entries(val)) mapped[k] = resolveRel(v);
44
+ return mapped;
45
+ }
46
+ return undefined;
47
+ };
48
+ if (resolvedEntries) {
49
+ resolvedEntries = resolveEntryMapOrList(resolvedEntries);
50
+ }
51
+
52
+ const result = await buildDeclarations({
53
+ bundle,
54
+ entry: resolveRel(options.entry),
55
+ entries: resolvedEntries || (bundle && !options.entry ? resolveEntryMapOrList(libEntries) : undefined),
56
+ inputs: options.inputs
57
+ ? (Array.isArray(options.inputs) ? options.inputs.map(resolveRel) : resolveRel(options.inputs))
58
+ : (!bundle ? [resolveRel(options.rootDir) || path.resolve(root, 'src')] : undefined),
59
+ rootDir: resolveRel(options.rootDir),
60
+ out: resolveRel(options.out),
61
+ outDir,
62
+ tsconfig: typeof options.tsconfig === 'string' ? resolveRel(options.tsconfig) : options.tsconfig,
63
+ external: options.external,
64
+ concurrency: options.concurrency,
65
+ banner: options.banner,
66
+ footer: options.footer,
67
+ skipUnchanged: options.skipUnchanged,
68
+ cache,
69
+ });
70
+
71
+ if (result.diagnostics && result.diagnostics.length > 0) {
72
+ const msg = result.diagnostics
73
+ .map(d => `${d.file} [${d.start}..${d.end}] (${d.code}) ${d.message}`)
74
+ .join('\n');
75
+ if (options.strict === false) {
76
+ if (this && typeof this.warn === 'function') {
77
+ this.warn(`@pulsec/dts reported ${result.diagnostics.length} diagnostic(s):\n${msg}`);
78
+ }
79
+ return;
80
+ }
81
+ if (this && typeof this.error === 'function') {
82
+ this.error(`@pulsec/dts failed with ${result.diagnostics.length} diagnostic(s):\n${msg}`);
83
+ } else {
84
+ throw new Error(`@pulsec/dts failed with ${result.diagnostics.length} diagnostic(s):\n${msg}`);
85
+ }
86
+ }
87
+ },
88
+ };
89
+ }
90
+
91
+ export default pulsecDts;
package/vite.d.ts ADDED
@@ -0,0 +1,24 @@
1
+ import type { BuildDeclarationsOptions, DtsCache } from './index.d.ts';
2
+
3
+ export interface PulsecDtsPluginOptions extends Omit<BuildDeclarationsOptions, 'cache'> {
4
+ /** Pass `false` to disable incremental in-memory caching across rebuilds. */
5
+ cache?: DtsCache | false;
6
+ /** Fail the build when declaration diagnostics occur (default: `true`). */
7
+ strict?: boolean;
8
+ }
9
+
10
+ export interface PulsecDtsVitePlugin {
11
+ name: string;
12
+ apply: 'build';
13
+ configResolved(config: {
14
+ root?: string;
15
+ build?: {
16
+ outDir?: string;
17
+ lib?: false | { entry?: string | string[] | Record<string, string> };
18
+ };
19
+ }): void;
20
+ closeBundle(): Promise<void>;
21
+ }
22
+
23
+ export function pulsecDts(options?: PulsecDtsPluginOptions): PulsecDtsVitePlugin;
24
+ export default pulsecDts;