@fedify/vocab-tools 2.5.0-dev.2687 → 2.5.0-dev.2726

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/src/fs.test.ts DELETED
@@ -1,31 +0,0 @@
1
- import { deepStrictEqual } from "node:assert";
2
- import { mkdir, mkdtemp, writeFile } from "node:fs/promises";
3
- import { tmpdir } from "node:os";
4
- import { join } from "node:path";
5
- import { test } from "node:test";
6
- import { readDirRecursive } from "./fs.ts";
7
-
8
- test("readDirRecursive()", async () => {
9
- // Create a temporary directory that has fixtures in it:
10
- const dir = await mkdtemp(join(tmpdir(), "fedify-test-"));
11
- await mkdir(join(dir, "a"));
12
- await writeFile(join(dir, "a", "aa.txt"), "aa");
13
- await writeFile(join(dir, "a", "ab.txt"), "aa");
14
- await mkdir(join(dir, "a", "aa"));
15
- await writeFile(join(dir, "a", "aa", "aaa.txt"), "aaa");
16
- await mkdir(join(dir, "b"));
17
- await writeFile(join(dir, "b", "ba.txt"), "ba");
18
- await writeFile(join(dir, "b", "bb.txt"), "bb");
19
-
20
- // Read the directory recursively:
21
- deepStrictEqual(
22
- new Set(await Array.fromAsync(readDirRecursive(dir))),
23
- new Set([
24
- join("a", "aa", "aaa.txt"),
25
- join("a", "aa.txt"),
26
- join("a", "ab.txt"),
27
- join("b", "ba.txt"),
28
- join("b", "bb.txt"),
29
- ]),
30
- );
31
- });
package/src/fs.ts DELETED
@@ -1,21 +0,0 @@
1
- import { readdir } from "node:fs/promises";
2
- import { join } from "node:path";
3
-
4
- /**
5
- * Recursively read a directory, yielding the paths of all files. File paths
6
- * are relative to the directory, and directories are not yielded.
7
- * @param dir The directory to read.
8
- * @returns An async iterable of file paths.
9
- */
10
- export async function* readDirRecursive(dir: string): AsyncIterable<string> {
11
- for (const entry of await readdir(dir, { withFileTypes: true })) {
12
- if (entry.isDirectory()) {
13
- const path = join(dir, entry.name);
14
- for await (const subentry of readDirRecursive(path)) {
15
- yield join(entry.name, subentry);
16
- }
17
- } else {
18
- yield entry.name;
19
- }
20
- }
21
- }
package/src/generate.ts DELETED
@@ -1,24 +0,0 @@
1
- import { open } from "node:fs/promises";
2
- import { generateClasses } from "./class.ts";
3
- import { loadSchemaFiles } from "./schema.ts";
4
-
5
- export default async function generateVocab(
6
- schemaDir: string,
7
- generatedPath: string,
8
- ): Promise<void> {
9
- const types = await loadSchemaFiles(schemaDir);
10
- const encoder = new TextEncoder();
11
-
12
- const file = await open(generatedPath, "w");
13
- const writer = file.createWriteStream();
14
-
15
- for await (const code of generateClasses(types)) {
16
- writer.write(encoder.encode(code));
17
- }
18
-
19
- await new Promise<void>((resolve, reject) => {
20
- writer.once("finish", () => file.close().then(resolve, reject));
21
- writer.once("error", reject);
22
- writer.end();
23
- });
24
- }
package/src/inspector.ts DELETED
@@ -1,117 +0,0 @@
1
- import { getFieldName } from "./field.ts";
2
- import type { TypeSchema } from "./schema.ts";
3
- import { hasSingularAccessor, isNonFunctionalProperty } from "./schema.ts";
4
- import { emitOverride } from "./type.ts";
5
-
6
- export async function* generateInspector(
7
- typeUri: string,
8
- types: Record<string, TypeSchema>,
9
- ): AsyncIterable<string> {
10
- const type = types[typeUri];
11
- yield `
12
- protected ${emitOverride(
13
- typeUri,
14
- types,
15
- )} _getCustomInspectProxy(): Record<string, unknown> {
16
- `;
17
- if (type.extends == null) {
18
- yield `
19
- const proxy: Record<string, unknown> = {};
20
- if (this.id != null) {
21
- proxy.id = {
22
- [Symbol.for("Deno.customInspect")]: (
23
- inspect: (value: unknown, options: unknown) => string,
24
- options: unknown,
25
- ): string => "URL " + inspect(inspectIri(this.id!), options),
26
- [Symbol.for("nodejs.util.inspect.custom")]: (
27
- _depth: number,
28
- options: unknown,
29
- inspect: (value: unknown, options: unknown) => string,
30
- ): string => "URL " + inspect(inspectIri(this.id!), options),
31
- };
32
- }
33
- `;
34
- } else {
35
- yield "const proxy: Record<string, unknown> = super._getCustomInspectProxy();";
36
- }
37
- for (const property of type.properties) {
38
- const fieldName = await getFieldName(property.uri);
39
- const localName = await getFieldName(property.uri, "");
40
- yield `
41
- const ${localName} = this.${fieldName}
42
- // deno-lint-ignore no-explicit-any
43
- .map((v: any) => v instanceof URL
44
- ? {
45
- [Symbol.for("Deno.customInspect")]: (
46
- inspect: (value: unknown, options: unknown) => string,
47
- options: unknown,
48
- ): string => "URL " + inspect(inspectIri(v), options),
49
- [Symbol.for("nodejs.util.inspect.custom")]: (
50
- _depth: number,
51
- options: unknown,
52
- inspect: (value: unknown, options: unknown) => string,
53
- ): string => "URL " + inspect(inspectIri(v), options),
54
- }
55
- : v);
56
- `;
57
- if (hasSingularAccessor(property)) {
58
- yield `
59
- if (${localName}.length == 1) {
60
- proxy.${property.singularName} = ${localName}[0];
61
- }
62
- `;
63
- }
64
- if (isNonFunctionalProperty(property)) {
65
- yield `
66
- if (${localName}.length > 1
67
- || !(${JSON.stringify(property.singularName)} in proxy)
68
- && ${localName}.length > 0) {
69
- proxy.${property.pluralName} = ${localName};
70
- }
71
- `;
72
- }
73
- }
74
- yield `
75
- return proxy;
76
- }
77
- `;
78
- }
79
-
80
- /**
81
- * Generates code that must appear *after* the class closing brace: prototype
82
- * assignments for the Deno and Node.js custom-inspect hooks.
83
- *
84
- * These are emitted outside the class body because computed property names
85
- * using `Symbol.for()` are incompatible with `isolatedDeclarations` mode.
86
- */
87
- export async function* generateInspectorPostClass(
88
- typeUri: string,
89
- types: Record<string, TypeSchema>,
90
- ): AsyncIterable<string> {
91
- const type = types[typeUri];
92
- const className = type.name;
93
- yield `
94
- // deno-lint-ignore no-explicit-any
95
- (${className}.prototype as any)[Symbol.for("Deno.customInspect")] =
96
- function (
97
- this: ${className},
98
- inspect: (value: unknown, options: unknown) => string,
99
- options: unknown,
100
- ): string {
101
- const proxy = this._getCustomInspectProxy();
102
- return ${JSON.stringify(type.name + " ")} + inspect(proxy, options);
103
- };
104
-
105
- // deno-lint-ignore no-explicit-any
106
- (${className}.prototype as any)[Symbol.for("nodejs.util.inspect.custom")] =
107
- function (
108
- this: ${className},
109
- _depth: number,
110
- options: unknown,
111
- inspect: (value: unknown, options: unknown) => string,
112
- ): string {
113
- const proxy = this._getCustomInspectProxy();
114
- return ${JSON.stringify(type.name + " ")} + inspect(proxy, options);
115
- };
116
- `;
117
- }
package/src/mod.ts DELETED
@@ -1,8 +0,0 @@
1
- export { default as generateVocab } from "./generate.ts";
2
- export {
3
- loadSchemaFiles,
4
- type PropertyPreprocessorSchema,
5
- type PropertySchema,
6
- type TypeSchema,
7
- } from "./schema.ts";
8
- export { areAllScalarTypes } from "./type.ts";
@@ -1,198 +0,0 @@
1
- /** Emits module-private sparse property-array validation and copying helpers. */
2
- export function generatePropertyArrayHelpers(): string {
3
- return `
4
- interface VocabSparseArraySnapshot {
5
- length: number;
6
- indices: number[];
7
- }
8
-
9
- interface VocabArrayValidation {
10
- valid: boolean;
11
- sparse: boolean;
12
- }
13
-
14
- type VocabArrayCopy<T> = { ok: true; array: T[] } | { ok: false };
15
-
16
- // Most fields have no trusted prefix. Keep that metadata on the existing Set
17
- // so empty fields need neither another object nor another instance slot.
18
- const vocabTrustPrefix: unique symbol = Symbol("vocabulary trust prefix");
19
- type VocabTrustSet = Set<number> & { [vocabTrustPrefix]?: number };
20
-
21
- function vocabSetTrustPrefix(trust: VocabTrustSet, prefix: number): void {
22
- if (prefix > 0) trust[vocabTrustPrefix] = prefix;
23
- }
24
-
25
- function vocabCopyTrustSet(
26
- trust: VocabTrustSet,
27
- destination: VocabTrustSet,
28
- ): VocabTrustSet {
29
- // clone() already constructed the destination. Reuse its empty Set only
30
- // when constructor defaults cannot contribute trust to the copied field.
31
- const copy: VocabTrustSet = trust !== destination && trust.size === 0 &&
32
- destination.size === 0 && destination[vocabTrustPrefix] == null
33
- ? destination : new Set(trust);
34
- const prefix = trust[vocabTrustPrefix];
35
- if (prefix != null && prefix > 0) copy[vocabTrustPrefix] = prefix;
36
- return copy;
37
- }
38
-
39
- // These thresholds select an optimization, not a limit on property arrays.
40
- const vocabSparseArrayMinimumLength = 4096;
41
- const vocabSparseArrayProbeCount = 8;
42
- const vocabSparseArrayPresentProbeLimit = 4;
43
- const vocabArrayPrototype = Array.prototype;
44
- const vocabObjectPrototype = globalThis.Object.prototype;
45
- const vocabArrayDescriptors = ["constructor", "every", "slice"].map(
46
- key => globalThis.Object.getOwnPropertyDescriptor(vocabArrayPrototype, key),
47
- );
48
- const vocabArraySpeciesDescriptor = globalThis.Object.getOwnPropertyDescriptor(
49
- Array, Symbol.species,
50
- );
51
-
52
- function vocabSameArrayDescriptor(
53
- actual: PropertyDescriptor | undefined,
54
- expected: PropertyDescriptor | undefined,
55
- ): boolean {
56
- return actual?.value === expected?.value && actual?.get === expected?.get &&
57
- actual?.set === expected?.set && actual?.writable === expected?.writable &&
58
- actual?.enumerable === expected?.enumerable &&
59
- actual?.configurable === expected?.configurable;
60
- }
61
-
62
- function vocabArrayIndex(key: string): number | undefined {
63
- const index = Number(key);
64
- return Number.isInteger(index) && index >= 0 && index < 0xffffffff &&
65
- String(index) === key
66
- ? index
67
- : undefined;
68
- }
69
-
70
- function vocabSparseArraySnapshot(
71
- array: unknown[],
72
- ): VocabSparseArraySnapshot | undefined {
73
- if (!Array.isArray(array)) return undefined;
74
- const length = array.length;
75
- // Small dense fields take no prototype or key-enumeration overhead.
76
- if (length < vocabSparseArrayMinimumLength) return undefined;
77
- if (!Number.isInteger(length) || length > 0xffffffff ||
78
- globalThis.Object.getPrototypeOf(array) !== vocabArrayPrototype ||
79
- globalThis.Object.getPrototypeOf(vocabArrayPrototype) !==
80
- vocabObjectPrototype ||
81
- globalThis.Object.getPrototypeOf(vocabObjectPrototype) !== null) {
82
- return undefined;
83
- }
84
- const methods = ["constructor", "every", "slice"];
85
- for (let i = 0; i < methods.length; i++) {
86
- const key = methods[i];
87
- if (globalThis.Object.hasOwn(array, key) ||
88
- !vocabSameArrayDescriptor(
89
- globalThis.Object.getOwnPropertyDescriptor(vocabArrayPrototype, key),
90
- vocabArrayDescriptors[i],
91
- )) return undefined;
92
- }
93
- if (!vocabSameArrayDescriptor(
94
- globalThis.Object.getOwnPropertyDescriptor(Array, Symbol.species),
95
- vocabArraySpeciesDescriptor,
96
- )) return undefined;
97
-
98
- // Descriptor probes do not invoke element getters. Plainly dense arrays
99
- // keep native iteration without enumerating all their keys.
100
- let present = 0;
101
- for (let i = 0; i < vocabSparseArrayProbeCount; i++) {
102
- const index = Math.floor(i * (length - 1) / (vocabSparseArrayProbeCount - 1));
103
- if (globalThis.Object.getOwnPropertyDescriptor(array, index) != null &&
104
- ++present >= vocabSparseArrayPresentProbeLimit) return undefined;
105
- }
106
- for (const prototype of [vocabArrayPrototype, vocabObjectPrototype]) {
107
- for (const key of globalThis.Object.getOwnPropertyNames(prototype)) {
108
- if (vocabArrayIndex(key) != null) return undefined;
109
- }
110
- }
111
- const indices: number[] = [];
112
- for (const key of globalThis.Object.getOwnPropertyNames(array)) {
113
- const index = vocabArrayIndex(key);
114
- if (index != null && index < length) indices.push(index);
115
- }
116
- if (indices.length >= length / 2) return undefined;
117
- for (const index of indices) {
118
- const descriptor = globalThis.Object.getOwnPropertyDescriptor(array, index);
119
- if (descriptor == null || !("value" in descriptor)) return undefined;
120
- }
121
- // Ordinary array keys already have canonical index order. This guard is
122
- // not a Proxy detector; reflection traps and errors remain observable.
123
- return { length, indices };
124
- }
125
-
126
- function vocabValidatePropertyArray<T>(
127
- array: T[],
128
- test: (value: T) => boolean,
129
- ): VocabArrayValidation {
130
- const snapshot = vocabSparseArraySnapshot(array);
131
- if (snapshot == null) return { valid: array.every(test), sparse: false };
132
- for (const index of snapshot.indices) {
133
- if (globalThis.Object.hasOwn(array, index) && !test(array[index])) {
134
- return { valid: false, sparse: true };
135
- }
136
- }
137
- return { valid: true, sparse: true };
138
- }
139
-
140
- function vocabDefineArrayEntry<T>(array: T[], index: number, value: T): void {
141
- globalThis.Object.defineProperty(array, index, {
142
- value, writable: true, enumerable: true, configurable: true,
143
- });
144
- }
145
-
146
- function vocabCopySparsePropertyArray<T>(
147
- array: T[],
148
- snapshot: VocabSparseArraySnapshot,
149
- test?: (value: T) => boolean,
150
- ): VocabArrayCopy<T> {
151
- const copy: T[] = [];
152
- // Seed dictionary storage before low indices or the final length can
153
- // allocate storage for every hole. The temporary entry stays private.
154
- if (snapshot.indices[snapshot.indices.length - 1] !== snapshot.length - 1) {
155
- globalThis.Object.defineProperty(copy, snapshot.length - 1, {
156
- value: undefined, writable: true, enumerable: true, configurable: true,
157
- });
158
- delete copy[snapshot.length - 1];
159
- }
160
- for (const index of snapshot.indices) {
161
- if (!globalThis.Object.hasOwn(array, index)) continue;
162
- const value = array[index];
163
- if (test != null && !test(value)) return { ok: false };
164
- vocabDefineArrayEntry(copy, index, value);
165
- }
166
- // A validation callback may have deleted the last snapshot entry.
167
- if (copy.length < snapshot.length) {
168
- globalThis.Object.defineProperty(copy, snapshot.length - 1, {
169
- value: undefined, writable: true, enumerable: true, configurable: true,
170
- });
171
- delete copy[snapshot.length - 1];
172
- }
173
- copy.length = snapshot.length;
174
- return { ok: true, array: copy };
175
- }
176
-
177
- function vocabCopyPropertyArray<T>(array: T[]): T[] {
178
- const snapshot = vocabSparseArraySnapshot(array);
179
- if (snapshot == null) return array.slice();
180
- const copied = vocabCopySparsePropertyArray(array, snapshot);
181
- // Without a predicate the private copy cannot fail validation.
182
- return (copied as { ok: true; array: T[] }).array;
183
- }
184
-
185
- function vocabCopyValidatedPropertyArray<T>(
186
- array: T[],
187
- test: (value: T) => boolean,
188
- previous: VocabArrayValidation,
189
- ): VocabArrayCopy<T> {
190
- const snapshot = vocabSparseArraySnapshot(array);
191
- if (snapshot != null) return vocabCopySparsePropertyArray(array, snapshot, test);
192
- // Sparse validation may have changed the next input's density, descriptors
193
- // or prototype. Validate that native-copy input before falling back.
194
- if (previous.sparse && !array.every(test)) return { ok: false };
195
- return { ok: true, array: array.slice() };
196
- }
197
- `;
198
- }