@canonical/design-system 0.2.4 → 0.2.5
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/definitions/ontology.ttl +8 -0
- package/package.json +1 -1
- package/src/collect/generateTurtle.tests.ts +94 -1
- package/src/collect/generateTurtle.ts +65 -3
- package/src/collect/resolvePublicExports.tests.ts +159 -0
- package/src/collect/resolvePublicExports.ts +244 -0
- package/src/collect/types.ts +11 -0
package/definitions/ontology.ttl
CHANGED
|
@@ -562,6 +562,14 @@ ds:versionedLink
|
|
|
562
562
|
skos:definition "URL to a specific tagged version of this implementation in source control" ;
|
|
563
563
|
ds:acceptanceCriteria "Must be a valid URL including version tag" .
|
|
564
564
|
|
|
565
|
+
ds:importStatement
|
|
566
|
+
a owl:DatatypeProperty, owl:FunctionalProperty ;
|
|
567
|
+
rdfs:domain ds:ImplementationObject ;
|
|
568
|
+
rdfs:range xsd:string ;
|
|
569
|
+
rdfs:label "importStatement" ;
|
|
570
|
+
skos:definition "The statement a consumer pastes to bring this implementation into a file, naming the published package (e.g. 'import { Button } from \"@canonical/react-ds-global\";'). Derived from the name the library's public entry point actually exports the implementation's source file under, not from the file name." ;
|
|
571
|
+
ds:acceptanceCriteria "Must be a complete import statement naming the published package specifier and an export the package really provides. ABSENT rather than guessed when the implementation is not reachable by name from the library's entry point — a subcomponent published only as a property of its parent (Breadcrumbs.Item) or an internal file carries none." .
|
|
572
|
+
|
|
565
573
|
ds:isDraft
|
|
566
574
|
a owl:DatatypeProperty ;
|
|
567
575
|
rdfs:domain ds:ImplementationObject ;
|
package/package.json
CHANGED
|
@@ -1,4 +1,7 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
|
|
2
|
+
import { tmpdir } from "node:os";
|
|
3
|
+
import { dirname, join } from "node:path";
|
|
4
|
+
import { afterEach, describe, expect, it } from "vitest";
|
|
2
5
|
import {
|
|
3
6
|
generateLibraryTurtle,
|
|
4
7
|
generateObjectsTurtle,
|
|
@@ -334,3 +337,93 @@ describe("generateObjectsTurtle named IRIs and links", () => {
|
|
|
334
337
|
expect(forward).toBe(reversed);
|
|
335
338
|
});
|
|
336
339
|
});
|
|
340
|
+
|
|
341
|
+
describe("generateObjectsTurtle import statements", () => {
|
|
342
|
+
const roots: string[] = [];
|
|
343
|
+
|
|
344
|
+
function packageTree(files: Record<string, string>): string {
|
|
345
|
+
const root = mkdtempSync(join(tmpdir(), "ds-import-"));
|
|
346
|
+
roots.push(root);
|
|
347
|
+
for (const [path, content] of Object.entries(files)) {
|
|
348
|
+
const full = join(root, path);
|
|
349
|
+
mkdirSync(dirname(full), { recursive: true });
|
|
350
|
+
writeFileSync(full, content);
|
|
351
|
+
}
|
|
352
|
+
return root;
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
afterEach(() => {
|
|
356
|
+
for (const root of roots.splice(0)) {
|
|
357
|
+
rmSync(root, { recursive: true, force: true });
|
|
358
|
+
}
|
|
359
|
+
});
|
|
360
|
+
|
|
361
|
+
const config: CollectConfig = {
|
|
362
|
+
name: "@canonical/react-ds-global",
|
|
363
|
+
platform: "react",
|
|
364
|
+
link: "https://github.com/canonical/pragma",
|
|
365
|
+
prefix: { short: "ds", namespace: "https://ds.canonical.com/" },
|
|
366
|
+
pattern: "src/**/*.tsx",
|
|
367
|
+
};
|
|
368
|
+
|
|
369
|
+
it("emits the published name, not the file name", async () => {
|
|
370
|
+
const root = packageTree({
|
|
371
|
+
"src/index.ts": 'export { default as Button } from "./Button.js";',
|
|
372
|
+
"src/Button.tsx": "export default () => null;",
|
|
373
|
+
});
|
|
374
|
+
const annotations: ImplementsAnnotation[] = [
|
|
375
|
+
{
|
|
376
|
+
filePath: join(root, "src/Button.tsx"),
|
|
377
|
+
blockUri: "ds:global.component.button",
|
|
378
|
+
},
|
|
379
|
+
];
|
|
380
|
+
|
|
381
|
+
const ttl = await generateObjectsTurtle(config, annotations, root);
|
|
382
|
+
|
|
383
|
+
expect(ttl).toContain(
|
|
384
|
+
'ds:importStatement "import { Button } from \\"@canonical/react-ds-global\\";"',
|
|
385
|
+
);
|
|
386
|
+
});
|
|
387
|
+
|
|
388
|
+
// An import a consumer cannot resolve is worse than no import at all.
|
|
389
|
+
it("emits none for a file the package does not export", async () => {
|
|
390
|
+
const root = packageTree({
|
|
391
|
+
"src/index.ts": 'export { default as Card } from "./Card.js";',
|
|
392
|
+
"src/Card.tsx": "export default () => null;",
|
|
393
|
+
"src/common/Header.tsx": "export default () => null;",
|
|
394
|
+
});
|
|
395
|
+
const annotations: ImplementsAnnotation[] = [
|
|
396
|
+
{
|
|
397
|
+
filePath: join(root, "src/common/Header.tsx"),
|
|
398
|
+
blockUri: "ds:global.subcomponent.card-header",
|
|
399
|
+
},
|
|
400
|
+
];
|
|
401
|
+
|
|
402
|
+
const ttl = await generateObjectsTurtle(config, annotations, root);
|
|
403
|
+
|
|
404
|
+
expect(ttl).toContain("ds:implementsBlock");
|
|
405
|
+
expect(ttl).not.toContain("ds:importStatement");
|
|
406
|
+
});
|
|
407
|
+
|
|
408
|
+
it("finds the SvelteKit barrel without configuration", async () => {
|
|
409
|
+
const root = packageTree({
|
|
410
|
+
"src/lib/index.ts":
|
|
411
|
+
'export { default as SkipLink } from "./SkipLink.svelte";',
|
|
412
|
+
"src/lib/SkipLink.svelte": "<a></a>",
|
|
413
|
+
});
|
|
414
|
+
const annotations: ImplementsAnnotation[] = [
|
|
415
|
+
{
|
|
416
|
+
filePath: join(root, "src/lib/SkipLink.svelte"),
|
|
417
|
+
blockUri: "ds:global.pattern.skip_link",
|
|
418
|
+
},
|
|
419
|
+
];
|
|
420
|
+
|
|
421
|
+
const ttl = await generateObjectsTurtle(
|
|
422
|
+
{ ...config, name: "@canonical/svelte-ds-global" },
|
|
423
|
+
annotations,
|
|
424
|
+
root,
|
|
425
|
+
);
|
|
426
|
+
|
|
427
|
+
expect(ttl).toContain("import { SkipLink }");
|
|
428
|
+
});
|
|
429
|
+
});
|
|
@@ -1,6 +1,8 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { existsSync } from "node:fs";
|
|
2
|
+
import { join, relative } from "node:path";
|
|
2
3
|
import { GraphStore, PrefixMap } from "../graph/index.js";
|
|
3
4
|
import serializeToTurtle from "../serializers/TTLSerializer.js";
|
|
5
|
+
import resolvePublicExports, { importNameFor } from "./resolvePublicExports.js";
|
|
4
6
|
import type { CollectConfig, ImplementsAnnotation } from "./types.js";
|
|
5
7
|
|
|
6
8
|
/** Standard RDF/OWL namespaces - these are always included */
|
|
@@ -188,19 +190,63 @@ function buildSourceLink(
|
|
|
188
190
|
return `${repo}/blob/${ref}/${prefix}${relativePath}`;
|
|
189
191
|
}
|
|
190
192
|
|
|
193
|
+
/**
|
|
194
|
+
* Conventional public entry modules, tried in order when config names none.
|
|
195
|
+
*
|
|
196
|
+
* Two conventions live side by side in one monorepo: a bundler package puts its
|
|
197
|
+
* barrel at `src/index.ts`, a SvelteKit library at `src/lib/index.ts`. Trying
|
|
198
|
+
* both means neither kind needs to configure anything; `entry` stays available
|
|
199
|
+
* for a package that does neither.
|
|
200
|
+
*/
|
|
201
|
+
const DEFAULT_ENTRY_FILES = [
|
|
202
|
+
"src/index.ts",
|
|
203
|
+
"src/index.tsx",
|
|
204
|
+
"src/lib/index.ts",
|
|
205
|
+
];
|
|
206
|
+
|
|
207
|
+
/**
|
|
208
|
+
* The entry module to walk exports from — the configured one, or the first
|
|
209
|
+
* conventional path that exists. Falls back to the first candidate so a package
|
|
210
|
+
* with no barrel at all resolves to a missing file, which yields no exports and
|
|
211
|
+
* therefore no import statements.
|
|
212
|
+
*/
|
|
213
|
+
function resolveEntryFile(config: CollectConfig, basePath: string): string {
|
|
214
|
+
if (config.entry) {
|
|
215
|
+
return join(basePath, config.entry);
|
|
216
|
+
}
|
|
217
|
+
const found = DEFAULT_ENTRY_FILES.map((candidate) =>
|
|
218
|
+
join(basePath, candidate),
|
|
219
|
+
).find((candidate) => existsSync(candidate));
|
|
220
|
+
return found ?? join(basePath, DEFAULT_ENTRY_FILES[0]);
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
/**
|
|
224
|
+
* The import statement a consumer pastes to reach this implementation.
|
|
225
|
+
*
|
|
226
|
+
* Built from the PUBLISHED package specifier and the name the package's barrel
|
|
227
|
+
* chain actually exports the file under — never from the file name, which is
|
|
228
|
+
* routinely not the exported name. Returns undefined when the file is not
|
|
229
|
+
* publicly exported, and the caller then emits no statement: a reader who sees
|
|
230
|
+
* no import learns something true, where a guessed one would send them to a
|
|
231
|
+
* symbol that does not exist.
|
|
232
|
+
*/
|
|
233
|
+
function buildImportStatement(packageName: string, exportName: string): string {
|
|
234
|
+
return `import { ${exportName} } from "${packageName}";`;
|
|
235
|
+
}
|
|
236
|
+
|
|
191
237
|
/**
|
|
192
238
|
* Generate the ImplementationObject .ttl content from annotations
|
|
193
239
|
* ImplementationObjects are named IRIs (ds:implementation.{librarySlug}.{blockLocalName})
|
|
194
240
|
* attached to the library, so they keep a stable identity across releases
|
|
195
241
|
* when ingested into a knowledge graph.
|
|
196
242
|
*/
|
|
197
|
-
export function generateObjectsTurtle(
|
|
243
|
+
export async function generateObjectsTurtle(
|
|
198
244
|
config: CollectConfig,
|
|
199
245
|
annotations: ImplementsAnnotation[],
|
|
200
246
|
basePath: string,
|
|
201
247
|
): Promise<string> {
|
|
202
248
|
if (annotations.length === 0) {
|
|
203
|
-
return
|
|
249
|
+
return "";
|
|
204
250
|
}
|
|
205
251
|
|
|
206
252
|
const store = new GraphStore();
|
|
@@ -210,6 +256,12 @@ export function generateObjectsTurtle(
|
|
|
210
256
|
const librarySlug = slugify(config.name);
|
|
211
257
|
const libraryUri = `${config.prefix.namespace}implementation.library.${librarySlug}`;
|
|
212
258
|
|
|
259
|
+
// What the package publishes, and under which names. Resolved once per
|
|
260
|
+
// library: the barrel walk is shared by every annotation below.
|
|
261
|
+
const publicExports = await resolvePublicExports(
|
|
262
|
+
resolveEntryFile(config, basePath),
|
|
263
|
+
);
|
|
264
|
+
|
|
213
265
|
// Sort for deterministic output so regenerated files diff cleanly
|
|
214
266
|
const sorted = [...annotations].sort((a, b) => {
|
|
215
267
|
const byBlock = a.blockUri.localeCompare(b.blockUri);
|
|
@@ -259,6 +311,16 @@ export function generateObjectsTurtle(
|
|
|
259
311
|
buildSourceLink(config, "main", relativePath),
|
|
260
312
|
);
|
|
261
313
|
|
|
314
|
+
// Add the import statement, when the file is publicly exported
|
|
315
|
+
const exportName = importNameFor(publicExports, annotation.filePath);
|
|
316
|
+
if (exportName) {
|
|
317
|
+
store.addLiteral(
|
|
318
|
+
implUri,
|
|
319
|
+
prefixes.expand(`${p}:importStatement`),
|
|
320
|
+
buildImportStatement(config.name, exportName),
|
|
321
|
+
);
|
|
322
|
+
}
|
|
323
|
+
|
|
262
324
|
// Add versioned link (source file pinned to the release tag)
|
|
263
325
|
if (config.repository && config.version) {
|
|
264
326
|
store.addLiteral(
|
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
|
|
2
|
+
import { tmpdir } from "node:os";
|
|
3
|
+
import { dirname, join } from "node:path";
|
|
4
|
+
import { afterEach, describe, expect, it } from "vitest";
|
|
5
|
+
import resolvePublicExports, { importNameFor } from "./resolvePublicExports.js";
|
|
6
|
+
|
|
7
|
+
const roots: string[] = [];
|
|
8
|
+
|
|
9
|
+
/** Write a throwaway package tree; returns its root. */
|
|
10
|
+
function packageTree(files: Record<string, string>): string {
|
|
11
|
+
const root = mkdtempSync(join(tmpdir(), "ds-exports-"));
|
|
12
|
+
roots.push(root);
|
|
13
|
+
for (const [path, content] of Object.entries(files)) {
|
|
14
|
+
const full = join(root, path);
|
|
15
|
+
mkdirSync(dirname(full), { recursive: true });
|
|
16
|
+
writeFileSync(full, content);
|
|
17
|
+
}
|
|
18
|
+
return root;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
afterEach(() => {
|
|
22
|
+
for (const root of roots.splice(0)) {
|
|
23
|
+
rmSync(root, { recursive: true, force: true });
|
|
24
|
+
}
|
|
25
|
+
});
|
|
26
|
+
|
|
27
|
+
describe("resolvePublicExports", () => {
|
|
28
|
+
it("follows a barrel chain to the file a default export came from", async () => {
|
|
29
|
+
const root = packageTree({
|
|
30
|
+
"src/index.ts": 'export * from "./lib/index.js";',
|
|
31
|
+
"src/lib/index.ts": 'export * from "./component/index.js";',
|
|
32
|
+
"src/lib/component/index.ts": 'export * from "./Button/index.js";',
|
|
33
|
+
"src/lib/component/Button/index.ts":
|
|
34
|
+
'export { default as Button } from "./Button.js";\nexport type * from "./types.js";',
|
|
35
|
+
"src/lib/component/Button/Button.tsx": "export default () => null;",
|
|
36
|
+
});
|
|
37
|
+
|
|
38
|
+
const exports = await resolvePublicExports(join(root, "src/index.ts"));
|
|
39
|
+
const button = join(root, "src/lib/component/Button/Button.tsx");
|
|
40
|
+
|
|
41
|
+
expect(importNameFor(exports, button)).toBe("Button");
|
|
42
|
+
});
|
|
43
|
+
|
|
44
|
+
// The case a file-name heuristic gets wrong: `Item.tsx` is only reachable as
|
|
45
|
+
// `Breadcrumbs.Item`, so `import { Item }` would not resolve for a consumer.
|
|
46
|
+
it("gives no name to a subcomponent the entry never re-exports", async () => {
|
|
47
|
+
const root = packageTree({
|
|
48
|
+
"src/index.ts": 'export * from "./component/index.js";',
|
|
49
|
+
"src/component/index.ts": 'export * from "./Breadcrumbs/index.js";',
|
|
50
|
+
"src/component/Breadcrumbs/index.ts":
|
|
51
|
+
'export { default as Breadcrumbs } from "./Breadcrumbs.js";\nexport type { ItemProps } from "./common/index.js";',
|
|
52
|
+
"src/component/Breadcrumbs/Breadcrumbs.tsx": "export default () => null;",
|
|
53
|
+
"src/component/Breadcrumbs/common/index.ts":
|
|
54
|
+
'export * from "./Item/index.js";',
|
|
55
|
+
"src/component/Breadcrumbs/common/Item/index.ts":
|
|
56
|
+
'export { default as Item } from "./Item.js";',
|
|
57
|
+
"src/component/Breadcrumbs/common/Item/Item.tsx":
|
|
58
|
+
"export default () => null;",
|
|
59
|
+
});
|
|
60
|
+
|
|
61
|
+
const exports = await resolvePublicExports(join(root, "src/index.ts"));
|
|
62
|
+
|
|
63
|
+
expect(
|
|
64
|
+
importNameFor(
|
|
65
|
+
exports,
|
|
66
|
+
join(root, "src/component/Breadcrumbs/Breadcrumbs.tsx"),
|
|
67
|
+
),
|
|
68
|
+
).toBe("Breadcrumbs");
|
|
69
|
+
expect(
|
|
70
|
+
importNameFor(
|
|
71
|
+
exports,
|
|
72
|
+
join(root, "src/component/Breadcrumbs/common/Item/Item.tsx"),
|
|
73
|
+
),
|
|
74
|
+
).toBeUndefined();
|
|
75
|
+
});
|
|
76
|
+
|
|
77
|
+
// Svelte's namespaced components build the export in the barrel rather than
|
|
78
|
+
// re-exporting it, so no edge points at the component file by itself.
|
|
79
|
+
it("attributes a locally declared export to its matching sibling file", async () => {
|
|
80
|
+
const root = packageTree({
|
|
81
|
+
"src/lib/index.ts": 'export * from "./Breadcrumbs/index.js";',
|
|
82
|
+
"src/lib/Breadcrumbs/index.ts": [
|
|
83
|
+
'import { default as BreadcrumbsRoot } from "./Breadcrumbs.svelte";',
|
|
84
|
+
'import { Item } from "./common/index.js";',
|
|
85
|
+
"const Breadcrumbs = BreadcrumbsRoot as typeof BreadcrumbsRoot & { Item: typeof Item };",
|
|
86
|
+
"Breadcrumbs.Item = Item;",
|
|
87
|
+
"export { Breadcrumbs };",
|
|
88
|
+
].join("\n"),
|
|
89
|
+
"src/lib/Breadcrumbs/Breadcrumbs.svelte": "<div></div>",
|
|
90
|
+
"src/lib/Breadcrumbs/common/index.ts": 'export * from "./Item/index.js";',
|
|
91
|
+
"src/lib/Breadcrumbs/common/Item/index.ts":
|
|
92
|
+
'export { default as Item } from "./Item.svelte";',
|
|
93
|
+
"src/lib/Breadcrumbs/common/Item/Item.svelte": "<li></li>",
|
|
94
|
+
});
|
|
95
|
+
|
|
96
|
+
const exports = await resolvePublicExports(join(root, "src/lib/index.ts"));
|
|
97
|
+
|
|
98
|
+
expect(
|
|
99
|
+
importNameFor(
|
|
100
|
+
exports,
|
|
101
|
+
join(root, "src/lib/Breadcrumbs/Breadcrumbs.svelte"),
|
|
102
|
+
),
|
|
103
|
+
).toBe("Breadcrumbs");
|
|
104
|
+
expect(
|
|
105
|
+
importNameFor(
|
|
106
|
+
exports,
|
|
107
|
+
join(root, "src/lib/Breadcrumbs/common/Item/Item.svelte"),
|
|
108
|
+
),
|
|
109
|
+
).toBeUndefined();
|
|
110
|
+
});
|
|
111
|
+
|
|
112
|
+
it("does not follow type-only edges", async () => {
|
|
113
|
+
const root = packageTree({
|
|
114
|
+
"src/index.ts": 'export type * from "./Internal/index.js";',
|
|
115
|
+
"src/Internal/index.ts":
|
|
116
|
+
'export { default as Internal } from "./Internal.js";',
|
|
117
|
+
"src/Internal/Internal.tsx": "export default () => null;",
|
|
118
|
+
});
|
|
119
|
+
|
|
120
|
+
const exports = await resolvePublicExports(join(root, "src/index.ts"));
|
|
121
|
+
|
|
122
|
+
expect(
|
|
123
|
+
importNameFor(exports, join(root, "src/Internal/Internal.tsx")),
|
|
124
|
+
).toBeUndefined();
|
|
125
|
+
});
|
|
126
|
+
|
|
127
|
+
it("honours an alias, so the published name wins over the file name", async () => {
|
|
128
|
+
const root = packageTree({
|
|
129
|
+
"src/index.ts": 'export { Inner as PublicName } from "./Inner.js";',
|
|
130
|
+
"src/Inner.tsx": "export const Inner = () => null;",
|
|
131
|
+
});
|
|
132
|
+
|
|
133
|
+
const exports = await resolvePublicExports(join(root, "src/index.ts"));
|
|
134
|
+
|
|
135
|
+
expect(importNameFor(exports, join(root, "src/Inner.tsx"))).toBe(
|
|
136
|
+
"PublicName",
|
|
137
|
+
);
|
|
138
|
+
});
|
|
139
|
+
|
|
140
|
+
it("survives a cycle between barrels", async () => {
|
|
141
|
+
const root = packageTree({
|
|
142
|
+
"src/index.ts": 'export * from "./a.js";',
|
|
143
|
+
"src/a.ts": 'export * from "./b.js";\nexport const A = 1;',
|
|
144
|
+
"src/b.ts": 'export * from "./a.js";\nexport const B = 2;',
|
|
145
|
+
});
|
|
146
|
+
|
|
147
|
+
const exports = await resolvePublicExports(join(root, "src/index.ts"));
|
|
148
|
+
|
|
149
|
+
expect(importNameFor(exports, join(root, "src/a.ts"))).toBe("A");
|
|
150
|
+
});
|
|
151
|
+
|
|
152
|
+
it("returns nothing when the entry file does not exist", async () => {
|
|
153
|
+
const root = packageTree({ "src/lib/thing.ts": "export const A = 1;" });
|
|
154
|
+
|
|
155
|
+
const exports = await resolvePublicExports(join(root, "src/index.ts"));
|
|
156
|
+
|
|
157
|
+
expect(exports.size).toBe(0);
|
|
158
|
+
});
|
|
159
|
+
});
|
|
@@ -0,0 +1,244 @@
|
|
|
1
|
+
import { existsSync } from "node:fs";
|
|
2
|
+
import { readFile } from "node:fs/promises";
|
|
3
|
+
import { dirname, join, resolve } from "node:path";
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Resolve which source files a package exports publicly, and under what names.
|
|
7
|
+
*
|
|
8
|
+
* The collector knows which FILE implements a block (the `@implements`
|
|
9
|
+
* annotation sits in it) but not what a consumer types to get it. That name is
|
|
10
|
+
* decided by the barrel chain between the package entry and the file, and it is
|
|
11
|
+
* routinely NOT the file's own name: `Button/Button.tsx` is published as
|
|
12
|
+
* `Button` through `export { default as Button }`, while
|
|
13
|
+
* `Breadcrumbs/common/Item/Item.svelte` is published as `Breadcrumbs.Item` —
|
|
14
|
+
* reachable only as a property of another component, never as a bare named
|
|
15
|
+
* import.
|
|
16
|
+
*
|
|
17
|
+
* So the walk starts at the ENTRY and follows only real value re-export edges.
|
|
18
|
+
* A file that the chain never reaches gets no name, and the caller emits no
|
|
19
|
+
* import statement for it: an absent import is honest, a guessed one sends
|
|
20
|
+
* someone to a symbol the package does not export. Type-only edges
|
|
21
|
+
* (`export type *`, `export type { … }`, `type X` inside a clause) are not
|
|
22
|
+
* followed for the same reason — they carry no value to import.
|
|
23
|
+
*/
|
|
24
|
+
|
|
25
|
+
/** Extensions a module specifier may resolve to, in preference order. */
|
|
26
|
+
const SOURCE_EXTENSIONS = [".ts", ".tsx", ".svelte", ".js", ".jsx"] as const;
|
|
27
|
+
|
|
28
|
+
/** Where a public name came from: the file that actually declares it. */
|
|
29
|
+
export type PublicExportMap = ReadonlyMap<string, ReadonlySet<string>>;
|
|
30
|
+
|
|
31
|
+
/** `export * from "…"` — but not `export type * from "…"`. */
|
|
32
|
+
const STAR_REEXPORT = /(?<!\btype\s)\bexport\s+\*\s+from\s*["']([^"']+)["']/g;
|
|
33
|
+
/** `export { … } from "…"` — the clause is parsed separately. */
|
|
34
|
+
const NAMED_REEXPORT = /\bexport\s*\{([^}]*)\}\s*from\s*["']([^"']+)["']/g;
|
|
35
|
+
/** `export { … }` with no `from` — names declared in this very file. */
|
|
36
|
+
const LOCAL_EXPORT_CLAUSE = /\bexport\s*\{([^}]*)\}\s*(?!from)[;\n]/g;
|
|
37
|
+
/** `export const|function|class X` — a value declared and exported inline. */
|
|
38
|
+
const LOCAL_DECLARATION =
|
|
39
|
+
/\bexport\s+(?:const|let|var|function\*?|class)\s+([A-Za-z_$][\w$]*)/g;
|
|
40
|
+
/** `export type { … }` / `export type X` — no value, so never followed. */
|
|
41
|
+
const TYPE_EXPORT = /\bexport\s+type\b/;
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* One `a as b` / `default as b` / `b` entry of an export clause.
|
|
45
|
+
*
|
|
46
|
+
* `local` is the name on the OTHER side of the edge (what the target module
|
|
47
|
+
* calls it), `exported` the name this module publishes it under.
|
|
48
|
+
*/
|
|
49
|
+
interface ClauseEntry {
|
|
50
|
+
readonly local: string;
|
|
51
|
+
readonly exported: string;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** Parse an export clause body, dropping its type-only entries. */
|
|
55
|
+
function parseClause(body: string): ClauseEntry[] {
|
|
56
|
+
const entries: ClauseEntry[] = [];
|
|
57
|
+
for (const raw of body.split(",")) {
|
|
58
|
+
const part = raw.trim();
|
|
59
|
+
if (part === "" || part.startsWith("type ")) {
|
|
60
|
+
continue;
|
|
61
|
+
}
|
|
62
|
+
const aliased = part.match(/^([\w$]+)\s+as\s+([\w$]+)$/);
|
|
63
|
+
if (aliased) {
|
|
64
|
+
entries.push({ local: aliased[1], exported: aliased[2] });
|
|
65
|
+
continue;
|
|
66
|
+
}
|
|
67
|
+
if (/^[\w$]+$/.test(part)) {
|
|
68
|
+
entries.push({ local: part, exported: part });
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
return entries;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* Resolve a module specifier to a file on disk.
|
|
76
|
+
*
|
|
77
|
+
* Handles the `.js`-specifier-for-a-`.ts`-file convention these packages use
|
|
78
|
+
* (`./Button.js` is written by `Button.tsx`), directory specifiers that mean
|
|
79
|
+
* the folder's barrel, and extensionless specifiers.
|
|
80
|
+
*/
|
|
81
|
+
function resolveSpecifier(fromFile: string, specifier: string): string | null {
|
|
82
|
+
if (!specifier.startsWith(".")) {
|
|
83
|
+
return null; // A package import — outside this package's own chain.
|
|
84
|
+
}
|
|
85
|
+
const base = resolve(dirname(fromFile), specifier);
|
|
86
|
+
const withoutJs = base.replace(/\.js$/, "");
|
|
87
|
+
const candidates = [
|
|
88
|
+
base,
|
|
89
|
+
...SOURCE_EXTENSIONS.map((ext) => `${withoutJs}${ext}`),
|
|
90
|
+
...SOURCE_EXTENSIONS.map((ext) => join(withoutJs, `index${ext}`)),
|
|
91
|
+
...SOURCE_EXTENSIONS.map((ext) => join(base, `index${ext}`)),
|
|
92
|
+
];
|
|
93
|
+
for (const candidate of candidates) {
|
|
94
|
+
if (existsSync(candidate) && !candidate.endsWith("/")) {
|
|
95
|
+
return candidate;
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
return null;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* The file a locally-declared name most likely stands for.
|
|
103
|
+
*
|
|
104
|
+
* A barrel that builds its export in place — svelte's `Breadcrumbs/index.ts`
|
|
105
|
+
* imports the root component, hangs `Item` off it, then `export { Breadcrumbs }`
|
|
106
|
+
* — declares the name locally, so no re-export edge points at the component
|
|
107
|
+
* file. Attributing the name to a SIBLING whose basename matches it recovers
|
|
108
|
+
* that case (`Breadcrumbs` → `Breadcrumbs.svelte`) without guessing: the match
|
|
109
|
+
* is exact, same-directory, and falls back to the declaring file when no such
|
|
110
|
+
* sibling exists.
|
|
111
|
+
*/
|
|
112
|
+
function principalSibling(declaringFile: string, name: string): string {
|
|
113
|
+
const dir = dirname(declaringFile);
|
|
114
|
+
for (const ext of SOURCE_EXTENSIONS) {
|
|
115
|
+
const sibling = join(dir, `${name}${ext}`);
|
|
116
|
+
if (existsSync(sibling)) {
|
|
117
|
+
return sibling;
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
return declaringFile;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/** The public names one module publishes, each mapped to its origin file. */
|
|
124
|
+
type ModuleExports = Map<string, string>;
|
|
125
|
+
|
|
126
|
+
/**
|
|
127
|
+
* Walk one module's exports, following re-export edges into its dependencies.
|
|
128
|
+
*
|
|
129
|
+
* `seen` guards the cycles a barrel graph can contain; a module already on the
|
|
130
|
+
* stack contributes nothing rather than recursing forever.
|
|
131
|
+
*/
|
|
132
|
+
async function exportsOf(
|
|
133
|
+
file: string,
|
|
134
|
+
cache: Map<string, ModuleExports>,
|
|
135
|
+
seen: Set<string>,
|
|
136
|
+
): Promise<ModuleExports> {
|
|
137
|
+
const cached = cache.get(file);
|
|
138
|
+
if (cached) {
|
|
139
|
+
return cached;
|
|
140
|
+
}
|
|
141
|
+
if (seen.has(file)) {
|
|
142
|
+
return new Map();
|
|
143
|
+
}
|
|
144
|
+
seen.add(file);
|
|
145
|
+
|
|
146
|
+
const result: ModuleExports = new Map();
|
|
147
|
+
let source: string;
|
|
148
|
+
try {
|
|
149
|
+
source = await readFile(file, "utf-8");
|
|
150
|
+
} catch {
|
|
151
|
+
cache.set(file, result);
|
|
152
|
+
return result;
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
for (const match of source.matchAll(STAR_REEXPORT)) {
|
|
156
|
+
const target = resolveSpecifier(file, match[1]);
|
|
157
|
+
if (!target) {
|
|
158
|
+
continue;
|
|
159
|
+
}
|
|
160
|
+
for (const [name, origin] of await exportsOf(target, cache, seen)) {
|
|
161
|
+
result.set(name, origin);
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
for (const match of source.matchAll(NAMED_REEXPORT)) {
|
|
166
|
+
if (TYPE_EXPORT.test(match[0])) {
|
|
167
|
+
continue;
|
|
168
|
+
}
|
|
169
|
+
const target = resolveSpecifier(file, match[2]);
|
|
170
|
+
if (!target) {
|
|
171
|
+
continue;
|
|
172
|
+
}
|
|
173
|
+
const inner = await exportsOf(target, cache, seen);
|
|
174
|
+
for (const { local, exported } of parseClause(match[1])) {
|
|
175
|
+
// A `default as X` edge has no named counterpart in the target, and the
|
|
176
|
+
// target file IS the origin — which is exactly the common component case.
|
|
177
|
+
result.set(exported, inner.get(local) ?? target);
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
for (const match of source.matchAll(LOCAL_EXPORT_CLAUSE)) {
|
|
182
|
+
for (const { exported } of parseClause(match[1])) {
|
|
183
|
+
result.set(exported, principalSibling(file, exported));
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
for (const match of source.matchAll(LOCAL_DECLARATION)) {
|
|
188
|
+
if (TYPE_EXPORT.test(match[0])) {
|
|
189
|
+
continue;
|
|
190
|
+
}
|
|
191
|
+
result.set(match[1], principalSibling(file, match[1]));
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
seen.delete(file);
|
|
195
|
+
cache.set(file, result);
|
|
196
|
+
return result;
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/**
|
|
200
|
+
* Map every publicly-exported source file of a package to the names it is
|
|
201
|
+
* exported under, starting from `entryFile`.
|
|
202
|
+
*
|
|
203
|
+
* A missing entry file yields an empty map rather than throwing: a package
|
|
204
|
+
* without a resolvable barrel simply contributes no import statements, which is
|
|
205
|
+
* the same outcome as one whose files are all internal.
|
|
206
|
+
*/
|
|
207
|
+
export default async function resolvePublicExports(
|
|
208
|
+
entryFile: string,
|
|
209
|
+
): Promise<PublicExportMap> {
|
|
210
|
+
const byFile = new Map<string, Set<string>>();
|
|
211
|
+
if (!existsSync(entryFile)) {
|
|
212
|
+
return byFile;
|
|
213
|
+
}
|
|
214
|
+
const rootExports = await exportsOf(entryFile, new Map(), new Set());
|
|
215
|
+
for (const [name, origin] of rootExports) {
|
|
216
|
+
const names = byFile.get(origin) ?? new Set<string>();
|
|
217
|
+
names.add(name);
|
|
218
|
+
byFile.set(origin, names);
|
|
219
|
+
}
|
|
220
|
+
return byFile;
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
/**
|
|
224
|
+
* The name to import a file by, when it has one.
|
|
225
|
+
*
|
|
226
|
+
* A file exported under several names (an alias kept for compatibility, say)
|
|
227
|
+
* resolves to the one matching its own basename, and otherwise to the first in
|
|
228
|
+
* sort order — a deterministic pick, so regenerated Turtle diffs cleanly.
|
|
229
|
+
*/
|
|
230
|
+
export function importNameFor(
|
|
231
|
+
exports: PublicExportMap,
|
|
232
|
+
file: string,
|
|
233
|
+
): string | undefined {
|
|
234
|
+
const names = exports.get(file);
|
|
235
|
+
if (!names || names.size === 0) {
|
|
236
|
+
return undefined;
|
|
237
|
+
}
|
|
238
|
+
const basename = file
|
|
239
|
+
.split("/")
|
|
240
|
+
.pop()
|
|
241
|
+
?.replace(/\.[^.]+$/, "");
|
|
242
|
+
const sorted = [...names].sort();
|
|
243
|
+
return sorted.find((name) => name === basename) ?? sorted[0];
|
|
244
|
+
}
|
package/src/collect/types.ts
CHANGED
|
@@ -55,6 +55,17 @@ export interface CollectConfig {
|
|
|
55
55
|
* Prepended to file paths when building full blob URLs.
|
|
56
56
|
*/
|
|
57
57
|
sourcePath?: string;
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* The package's public entry module, relative to the package root
|
|
61
|
+
* (default: "src/index.ts").
|
|
62
|
+
*
|
|
63
|
+
* Read to decide which implementations get a ds:importStatement: a file the
|
|
64
|
+
* barrel chain from here does not reach is not importable by name, so it gets
|
|
65
|
+
* none. A package whose entry does not resolve emits no import statements at
|
|
66
|
+
* all rather than guessing them.
|
|
67
|
+
*/
|
|
68
|
+
entry?: string;
|
|
58
69
|
}
|
|
59
70
|
|
|
60
71
|
/**
|