@bedrock-core/builder-validation 0.2.0 → 0.3.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/src/index.js CHANGED
@@ -1,13 +1,62 @@
1
+ var __addDisposableResource = (this && this.__addDisposableResource) || function (env, value, async) {
2
+ if (value !== null && value !== void 0) {
3
+ if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected.");
4
+ var dispose, inner;
5
+ if (async) {
6
+ if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined.");
7
+ dispose = value[Symbol.asyncDispose];
8
+ }
9
+ if (dispose === void 0) {
10
+ if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined.");
11
+ dispose = value[Symbol.dispose];
12
+ if (async) inner = dispose;
13
+ }
14
+ if (typeof dispose !== "function") throw new TypeError("Object not disposable.");
15
+ if (inner) dispose = function() { try { inner.call(this); } catch (e) { return Promise.reject(e); } };
16
+ env.stack.push({ value: value, dispose: dispose, async: async });
17
+ }
18
+ else if (async) {
19
+ env.stack.push({ async: true });
20
+ }
21
+ return value;
22
+ };
23
+ var __disposeResources = (this && this.__disposeResources) || (function (SuppressedError) {
24
+ return function (env) {
25
+ function fail(e) {
26
+ env.error = env.hasError ? new SuppressedError(e, env.error, "An error was suppressed during disposal.") : e;
27
+ env.hasError = true;
28
+ }
29
+ var r, s = 0;
30
+ function next() {
31
+ while (r = env.stack.pop()) {
32
+ try {
33
+ if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next);
34
+ if (r.dispose) {
35
+ var result = r.dispose.call(r.value);
36
+ if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) { fail(e); return next(); });
37
+ }
38
+ else s |= 1;
39
+ }
40
+ catch (e) {
41
+ fail(e);
42
+ }
43
+ }
44
+ if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve();
45
+ if (env.hasError) throw env.error;
46
+ }
47
+ return next();
48
+ };
49
+ })(typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
50
+ var e = new Error(message);
51
+ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
52
+ });
1
53
  import { readFile, readdir, realpath } from 'node:fs/promises';
2
- import { existsSync } from 'node:fs';
3
- import { createRequire } from 'node:module';
4
54
  import path from 'node:path';
5
- import { fileURLToPath, pathToFileURL } from 'node:url';
6
55
  import { createHash } from 'node:crypto';
7
- import { Ajv } from 'ajv';
8
- import { parse, printParseErrorCode } from 'jsonc-parser';
9
- import picomatch from 'picomatch';
10
- /** Aggregated JSON validation failure with structured diagnostics. */
56
+ import { findNodeAtOffset, getNodePath, parse, parseTree, printParseErrorCode } from 'jsonc-parser';
57
+ import { validateWithCreatorTools } from './creator-tools.js';
58
+ import { matchesDocumentType, prepareCheckedDocument } from './document-rules.js';
59
+ /** Aggregated pack content failure with structured diagnostics. */
11
60
  export class ContentValidationError extends Error {
12
61
  /** Structured validation failures collected across checked files. */
13
62
  diagnostics;
@@ -18,230 +67,224 @@ export class ContentValidationError extends Error {
18
67
  this.diagnostics = diagnostics;
19
68
  }
20
69
  }
21
- function within(root, file) {
22
- const relative = path.relative(root, file);
23
- return relative !== '..' && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative);
70
+ function record(value) {
71
+ return value !== null && typeof value === 'object' && !Array.isArray(value) ? value : undefined;
24
72
  }
25
- /**
26
- * Validate JSON syntax and apply content schemas according to the selected mode.
27
- * @param options Project inputs, settings and optional integrations for this operation.
28
- * @returns Per-file coverage and diagnostics. Syntax errors and strict schema errors throw ContentValidationError.
29
- */
30
- export async function validatePackContent(options) {
31
- const mode = options.mode ?? 'warn';
32
- const skip = mode === 'skip';
33
- const require = createRequire(import.meta.url);
34
- const root = skip ? '' : await realpath(options.schemaRoot ?? path.dirname(require.resolve('@minecraft/bedrock-schemas/catalog.json')));
35
- const catalogFile = path.join(root, 'catalog.json');
36
- const catalog = skip ? { schemas: [] } : JSON.parse(await readFile(catalogFile, 'utf8'));
37
- const metadataFile = path.join(root, 'package.json');
38
- const metadata = skip ? { version: '' } : JSON.parse(await readFile(metadataFile, 'utf8'));
39
- const catalogInputs = skip ? [] : [catalogFile, metadataFile];
40
- const validators = new Map();
41
- const unavailable = new Map();
42
- const documents = new Map();
43
- const referencesByFile = new Map();
44
- const ajv = skip ? undefined : new Ajv({ allErrors: true, strict: false, validateFormats: false, logger: false });
45
- async function load(file, inputs) {
46
- options.signal?.throwIfAborted();
47
- file = await realpath(file);
48
- if (!within(root, file)) {
49
- throw new Error(`Schema reference must stay inside its package: ${file}`);
50
- }
51
- inputs.add(file);
52
- const previous = documents.get(file);
53
- if (previous) {
54
- for (const reference of referencesByFile.get(file) ?? []) {
55
- if (!inputs.has(reference)) {
56
- await load(reference, inputs);
57
- }
58
- }
59
- return previous;
60
- }
61
- const document = JSON.parse(await readFile(file, 'utf8'));
62
- const references = new Set();
63
- if (!options.schemaRoot && metadata.version === '1.26.50'
64
- && file === path.join(root, 'schemas/rp/textures/terrain_texture.schema.json')) {
65
- // Vanilla terrain atlases use single texture paths as well as arrays.
66
- // https://github.com/Mojang/bedrock-samples/blob/main/resource_pack/textures/terrain_texture.json
67
- const properties = document.properties;
68
- const entry = properties.texture_data.additionalProperties;
69
- entry.properties.textures = { anyOf: [{ type: 'string' }, entry.properties.textures] };
70
- }
71
- if (!options.schemaRoot && metadata.version === '1.26.50') {
72
- if (file === path.join(root, 'schemas/rp/sounds/index.schema.json')) {
73
- // Sound definitions accept bare paths and objects with a file name and playback settings.
74
- const fields = document.properties;
75
- const events = fields.sound_definitions.additionalProperties;
76
- const sounds = events.properties.sounds;
77
- sounds.items = { anyOf: [{ type: 'string', minLength: 1 }, { ...sounds.items, required: ['name'] }] };
78
- }
79
- if (file === path.join(root, 'schemas/bp/entities/entity_minecraft_spell_effects.schema.json')) {
80
- // Effects accept numeric seconds or the documented infinite duration.
81
- // https://learn.microsoft.com/minecraft/creator/reference/content/entityreference/examples/entitycomponents/minecraftcomponent_spell_effects
82
- const fields = document.properties;
83
- const additions = fields.add_effects;
84
- const item = additions.items;
85
- const properties = item.properties;
86
- properties.duration = { anyOf: [properties.duration, { const: 'infinite' }] };
87
- }
88
- if (['description.schema.json', 'description_2.schema.json'].some(name => file === path.join(root, 'schemas/rp/entity', name))) {
89
- // Client entities can mix unconditional controllers and conditional entries.
90
- const fields = document.properties;
91
- const controllers = fields.render_controllers;
92
- const alternatives = controllers.anyOf;
93
- const items = alternatives.filter(entry => entry.type === 'array').map(entry => entry.items);
94
- alternatives.push({ type: 'array', items: { anyOf: items } });
95
- }
96
- if (file.startsWith(path.join(root, 'schemas/rp/models') + path.sep)) {
97
- // Geometry vectors accept numeric coordinates and Molang expressions.
98
- const vectors = new Set(['visible_bounds_offset', 'pivot', 'rotation', 'origin', 'size', 'uv', 'uv_size', 'translation', 'scale']);
99
- const visit = (value, vector = false) => {
100
- if (Array.isArray(value)) {
101
- value.forEach(entry => visit(entry, vector));
102
- }
103
- else if (value && typeof value === 'object') {
104
- const node = value;
105
- const items = node.items;
106
- if (vector && node.type === 'array' && items?.type === 'string') {
107
- items.type = ['string', 'number'];
108
- }
109
- for (const [key, entry] of Object.entries(node)) {
110
- visit(entry, vector || vectors.has(key));
111
- }
112
- }
113
- };
114
- visit(document);
73
+ function documentInputs(category, document, literal) {
74
+ const root = record(document);
75
+ const entity = category === 'rp/entity' ? record(root?.['minecraft:client_entity']) : undefined;
76
+ const description = record(entity?.description);
77
+ const controllers = description?.render_controllers;
78
+ const batchSize = 256;
79
+ if (!Array.isArray(controllers) || controllers.length <= batchSize) {
80
+ return [{ category, literal: literal(document), controllerOffset: 0 }];
81
+ }
82
+ // This unbounded list has independently typed entries. Slices keep the
83
+ // literal union manageable and preserve the surrounding document context.
84
+ return Array.from({ length: Math.ceil(controllers.length / batchSize) }, (_, index) => {
85
+ const controllerOffset = index * batchSize;
86
+ const slice = controllers.slice(controllerOffset, controllerOffset + batchSize);
87
+ return {
88
+ category, controllerOffset,
89
+ literal: literal({ ...root, 'minecraft:client_entity': { ...entity, description: { ...description, render_controllers: slice } } }),
90
+ };
91
+ });
92
+ }
93
+ function entityUpgradeDiagnostics(document, pack, file) {
94
+ const root = record(document);
95
+ const entity = record(root?.['minecraft:entity']);
96
+ const version = record(record(entity?.description)?.entity_version);
97
+ const steps = version?.upgrades;
98
+ if (!Array.isArray(steps)) {
99
+ return [];
100
+ }
101
+ const diagnostics = [];
102
+ const pointer = '/minecraft:entity/description/entity_version';
103
+ const report = (suffix, message) => diagnostics.push({ kind: 'type', pack, file, pointer: pointer + suffix, message });
104
+ const handlers = record(entity?.upgrades) ?? {};
105
+ const seen = new Set();
106
+ const formatVersion = typeof root?.format_version === 'string' ? /^(\d+)\.(\d+)(?:\.(\d+))?$/.exec(root.format_version) : null;
107
+ if (formatVersion) {
108
+ const [, major, minor, patch = '0'] = formatVersion;
109
+ if (Number(major) < 1 || (Number(major) === 1 && (Number(minor) < 26 || (Number(minor) === 26 && Number(patch) < 20)))) {
110
+ report('', 'Entity versioning requires format_version 1.26.20 or later.');
111
+ }
112
+ }
113
+ for (const [index, value] of steps.entries()) {
114
+ const step = record(value);
115
+ const to = step?.upgrade_to;
116
+ const name = step?.name;
117
+ if (typeof to === 'number') {
118
+ if (!Number.isInteger(to) || to < 1 || to > steps.length || seen.has(to)) {
119
+ report(`/upgrades/${index}/upgrade_to`, `Upgrade versions must use each integer from 1 through ${steps.length} exactly once.`);
115
120
  }
121
+ seen.add(to);
116
122
  }
117
- function normalize(value) {
118
- if (Array.isArray(value)) {
119
- value.forEach(normalize);
123
+ if (typeof name === 'string' && (!name.length || !Object.hasOwn(handlers, name))) {
124
+ report(`/upgrades/${index}/name`, 'Upgrade name must identify a handler in minecraft:entity.upgrades.');
125
+ }
126
+ }
127
+ return diagnostics;
128
+ }
129
+ async function checkBatch(entries, options, types, revision) {
130
+ if (!entries.length) {
131
+ return [];
132
+ }
133
+ const pending = [];
134
+ const lookup = entries.map((entry) => {
135
+ let markReady;
136
+ const ready = new Promise((resolve) => {
137
+ markReady = resolve;
138
+ });
139
+ const collect = () => new Promise((resolve, reject) => {
140
+ pending.push({ entry, resolve, reject });
141
+ markReady();
142
+ });
143
+ const { pack, file, source, category } = entry;
144
+ const cached = Promise.resolve().then(() => options.reuse
145
+ ? options.reuse(source, category ? types.inputs : [], createHash('sha256').update(JSON.stringify([revision, pack, file, category ?? null])).digest('hex'), collect)
146
+ : collect()).finally(markReady);
147
+ return { ready, cached };
148
+ });
149
+ const settled = Promise.allSettled(lookup.map(entry => entry.cached));
150
+ // Wait for cache hits and collect all misses before checking the batch.
151
+ await Promise.all(lookup.map(entry => entry.ready));
152
+ try {
153
+ const parsed = await Promise.all(pending.map(async ({ entry: { pack, file, source, category } }) => {
154
+ options.signal?.throwIfAborted();
155
+ const errors = [];
156
+ const document = parse((await readFile(source, 'utf8')).replace(/^\uFEFF/, ''), errors, { allowTrailingComma: true });
157
+ const diagnostics = errors.map(error => ({
158
+ kind: 'syntax',
159
+ pack,
160
+ file,
161
+ pointer: '',
162
+ message: `${printParseErrorCode(error.error)} at offset ${error.offset}`,
163
+ }));
164
+ const result = { pack, file, diagnostics };
165
+ if (types && category && !errors.length && matchesDocumentType(category, document)) {
166
+ result.category = category;
167
+ prepareCheckedDocument(category, document, (pointer, message) => {
168
+ diagnostics.push({ kind: 'type', pack, file, pointer, message });
169
+ });
170
+ if (category === 'bp/entities') {
171
+ diagnostics.push(...entityUpgradeDiagnostics(document, pack, file));
172
+ }
173
+ return { result, inputs: documentInputs(category, document, types.literal) };
120
174
  }
121
- else if (value && typeof value === 'object') {
122
- const node = value;
123
- delete node.$id;
124
- if (typeof node.$ref === 'string' && !node.$ref.startsWith('#')) {
125
- let target = new URL(node.$ref, pathToFileURL(file));
126
- if (target.protocol !== 'file:') {
127
- throw new Error(`Remote schema references are unsupported: ${target.href}`);
175
+ return { result };
176
+ }));
177
+ const typed = parsed.flatMap(({ result, inputs }) => inputs?.map(input => ({ result, input })) ?? []);
178
+ const findings = types?.check(typed.map(entry => entry.input), options.signal) ?? [];
179
+ for (const [index, { result, input }] of typed.entries()) {
180
+ const issues = findings[index];
181
+ if (issues.length) {
182
+ const tree = parseTree(input.literal);
183
+ for (const { code, message, offset } of issues) {
184
+ const node = tree && offset >= 0 ? findNodeAtOffset(tree, offset, true) : undefined;
185
+ const segments = node ? getNodePath(node) : [];
186
+ if (input.controllerOffset && segments[0] === 'minecraft:client_entity' && segments[1] === 'description' && segments[2] === 'render_controllers' && typeof segments[3] === 'number') {
187
+ segments[3] += input.controllerOffset;
128
188
  }
129
- // The pinned Mojang block schemas use the legacy Molang object's alternate filename.
130
- if (!options.schemaRoot && metadata.version === '1.26.50'
131
- && fileURLToPath(target) === path.join(root, 'schemas/common/expression.schema.json') && !existsSync(fileURLToPath(target))) {
132
- const fragment = target.hash;
133
- target = pathToFileURL(path.join(root, 'schemas/common/molang_expression.schema.json'));
134
- target.hash = fragment;
189
+ const pointer = segments.map(segment => '/' + String(segment).replaceAll('~', '~0').replaceAll('/', '~1')).join('');
190
+ const formatted = `TS${code} ${message}`;
191
+ if (!input.controllerOffset || !result.diagnostics.some(issue => issue.code === code && issue.pointer === pointer && issue.message === formatted)) {
192
+ result.diagnostics.push({ kind: 'type', code, pack: result.pack, file: result.file, pointer, message: formatted });
135
193
  }
136
- node.$ref = target.href;
137
- target.hash = '';
138
- references.add(fileURLToPath(target));
139
194
  }
140
- Object.values(node).forEach(normalize);
141
195
  }
142
196
  }
143
- normalize(document);
144
- document.$id = pathToFileURL(file).href;
145
- documents.set(file, document);
146
- referencesByFile.set(file, references);
147
- for (const reference of references) {
148
- await load(reference, inputs);
197
+ for (const [index, { resolve }] of pending.entries()) {
198
+ resolve(parsed[index].result);
149
199
  }
150
- return document;
151
200
  }
152
- async function validator(file, compiler) {
153
- const previous = validators.get(file);
154
- if (previous) {
155
- return previous;
156
- }
157
- const inputs = new Set(catalogInputs);
158
- const document = await load(file, inputs);
159
- for (const schema of documents.values()) {
160
- // Register the complete graph before compiling cyclic or shared references.
161
- if (!compiler.schemas[schema.$id]) {
162
- compiler.addSchema(schema);
163
- }
201
+ catch (error) {
202
+ for (const { reject } of pending) {
203
+ reject(error);
164
204
  }
165
- const validate = compiler.getSchema(document.$id) ?? compiler.compile(document);
166
- const result = { validate, inputs: [...inputs] };
167
- validators.set(file, result);
168
- return result;
169
205
  }
170
- const revision = createHash('sha256').update(await readFile(new URL(import.meta.url))).digest('hex');
171
- const files = [];
172
- for (const pack of options.packs) {
173
- const packRoot = await realpath(pack.path);
174
- const prefix = pack.kind === 'behavior' ? 'bp/' : pack.kind === 'resource' ? 'rp/' : undefined;
175
- const entries = prefix ? catalog.schemas.filter(entry => entry.url.startsWith(`./schemas/${prefix}`)) : [];
176
- async function visit(directory) {
177
- for (const entry of (await readdir(directory, { withFileTypes: true })).sort((a, b) => a.name.localeCompare(b.name))) {
206
+ return (await settled).map((entry) => {
207
+ if (entry.status === 'rejected') {
208
+ throw entry.reason;
209
+ }
210
+ return entry.value;
211
+ });
212
+ }
213
+ /** Check final pack JSON syntax and the native document types for its Bedrock target. */
214
+ export async function validatePackContent(options) {
215
+ const env_1 = { stack: [], error: void 0, hasError: false };
216
+ try {
217
+ const mode = options.mode ?? 'warn';
218
+ const backend = mode === 'skip' ? undefined : await import('./types-release.js');
219
+ const api = __addDisposableResource(env_1, backend && new backend.API(), false);
220
+ let types;
221
+ let typesIssue;
222
+ if (backend && api) {
223
+ try {
224
+ types = await backend.openTypesRelease(api, options);
225
+ }
226
+ catch (error) {
178
227
  options.signal?.throwIfAborted();
179
- const source = path.join(directory, entry.name);
180
- const relative = path.relative(packRoot, source).replaceAll('\\', '/');
181
- if (entry.isSymbolicLink()) {
182
- throw new Error(`Pack content cannot use links: ${pack.id}/${relative}`);
183
- }
184
- if (entry.isDirectory()) {
185
- await visit(source);
186
- continue;
187
- }
188
- if (!entry.isFile() || !/\.json$/i.test(entry.name) || relative === 'manifest.json') {
189
- continue;
190
- }
191
- // Exact filenames take precedence over folder-wide catalog patterns.
192
- const matches = entries.filter(item => item.fileMatch?.some(pattern => picomatch.isMatch(relative, pattern)));
193
- matches.sort((a, b) => (a.fileMatch?.join().includes('/**/') ? 1 : 0) - (b.fileMatch?.join().includes('/**/') ? 1 : 0));
194
- const selected = matches[0];
195
- let compiled;
196
- let schemaIssue = selected ? unavailable.get(selected.url) : undefined;
197
- if (ajv && pack.kind === 'resource' && relative === 'texts/languages.json') {
198
- const file = fileURLToPath(new URL('../schemas/languages.schema.json', import.meta.url));
199
- compiled = { validate: ajv.compile(JSON.parse(await readFile(file, 'utf8'))), inputs: [file, ...catalogInputs] };
200
- }
201
- else if (ajv && selected && !schemaIssue) {
202
- try {
203
- compiled = await validator(path.resolve(root, selected.url), ajv);
228
+ typesIssue = error instanceof Error ? error.message : String(error);
229
+ }
230
+ }
231
+ const implementation = [
232
+ new URL(import.meta.url),
233
+ new URL('./document-rules' + path.extname(new URL(import.meta.url).pathname), import.meta.url),
234
+ ...(backend?.typeImplementation ?? []),
235
+ ];
236
+ const revision = options.reuse
237
+ ? createHash('sha256').update(backend?.checkerVersion ?? '').update(Buffer.concat(await Promise.all(implementation.map(file => readFile(file))))).digest('hex')
238
+ : '';
239
+ const files = [];
240
+ const batch = [];
241
+ for (const pack of options.packs) {
242
+ const root = await realpath(pack.path);
243
+ async function visit(directory) {
244
+ for (const entry of (await readdir(directory, { withFileTypes: true })).sort((a, b) => a.name.localeCompare(b.name))) {
245
+ options.signal?.throwIfAborted();
246
+ const source = path.join(directory, entry.name);
247
+ const file = path.relative(root, source).replaceAll('\\', '/');
248
+ if (entry.isSymbolicLink()) {
249
+ throw new Error(`Pack content cannot use links: ${pack.id}/${file}`);
204
250
  }
205
- catch (error) {
206
- options.signal?.throwIfAborted();
207
- // A broken upstream schema cannot establish content validity.
208
- schemaIssue = `Schema unavailable: ${error instanceof Error ? error.message : String(error)}`;
209
- unavailable.set(selected.url, schemaIssue);
251
+ if (entry.isDirectory()) {
252
+ await visit(source);
210
253
  }
211
- }
212
- const inputs = compiled?.inputs ?? catalogInputs;
213
- async function check() {
214
- const errors = [];
215
- const document = parse(await readFile(source, 'utf8'), errors, { allowTrailingComma: true });
216
- const diagnostics = errors.map(error => ({
217
- kind: 'syntax',
218
- pack: pack.id,
219
- file: relative,
220
- pointer: '',
221
- message: `${printParseErrorCode(error.error)} at offset ${error.offset}`,
222
- }));
223
- if (!errors.length && compiled && !compiled.validate(document)) {
224
- for (const error of compiled.validate.errors ?? []) {
225
- diagnostics.push({ kind: 'schema', pack: pack.id, file: relative, pointer: error.instancePath, message: error.message ?? error.keyword });
254
+ else if (entry.isFile() && /\.json$/i.test(entry.name) && file !== 'manifest.json') {
255
+ batch.push({ pack: pack.id, file, source, category: types?.category(pack.kind, file) });
256
+ if (batch.length === 128) {
257
+ files.push(...await checkBatch(batch.splice(0), options, types, revision));
226
258
  }
227
259
  }
228
- return {
229
- pack: pack.id,
230
- file: relative,
231
- ...(compiled && selected ? { schema: selected.url } : {}),
232
- ...(schemaIssue ? { schemaIssue } : {}),
233
- diagnostics,
234
- };
235
260
  }
236
- const fileRevision = createHash('sha256').update(JSON.stringify({ revision, pack: pack.id, relative, skip, schema: selected?.url, schemaIssue })).digest('hex');
237
- files.push(await (options.reuse?.(source, inputs, fileRevision, check) ?? check()));
238
261
  }
262
+ await visit(root);
239
263
  }
240
- await visit(packRoot);
264
+ files.push(...await checkBatch(batch, options, types, revision));
265
+ const diagnostics = files.flatMap(file => file.diagnostics).filter(issue => mode !== 'warn' || issue.kind !== 'type');
266
+ if (typesIssue && mode === 'strict') {
267
+ diagnostics.push({ kind: 'type', pack: 'project', file: '', pointer: '', message: typesIssue });
268
+ }
269
+ if (diagnostics.length) {
270
+ throw new ContentValidationError(diagnostics);
271
+ }
272
+ const result = { typesVersion: types?.version ?? '', files, ...(typesIssue ? { typesIssue } : {}) };
273
+ if (options.creatorTools) {
274
+ const creatorToolsOptions = { projectRoot: options.projectRoot, ...options.creatorTools };
275
+ result.creatorTools = await validateWithCreatorTools(options.packs, creatorToolsOptions, options.signal, options.targetVersion);
276
+ const errors = result.creatorTools.diagnostics.filter(issue => issue.severity === 'error');
277
+ if (creatorToolsOptions.mode === 'strict' && errors.length) {
278
+ throw new ContentValidationError(errors);
279
+ }
280
+ }
281
+ return result;
282
+ }
283
+ catch (e_1) {
284
+ env_1.error = e_1;
285
+ env_1.hasError = true;
241
286
  }
242
- const diagnostics = files.flatMap(file => file.diagnostics).filter(issue => mode !== 'warn' || issue.kind !== 'schema');
243
- if (diagnostics.length) {
244
- throw new ContentValidationError(diagnostics);
287
+ finally {
288
+ __disposeResources(env_1);
245
289
  }
246
- return { schemaVersion: metadata.version, files };
247
290
  }
@@ -0,0 +1,20 @@
1
+ import type { API } from 'typescript-native/sync';
2
+ import { documentLiteral } from './document-types.ts';
3
+ export { API } from 'typescript-native/sync';
4
+ export interface TypeSelection {
5
+ /** Project directory from which to resolve its installed Bedrock types. */
6
+ projectRoot?: string;
7
+ /** Bedrock release track required from the installed types. */
8
+ targetVersion?: string;
9
+ /** Explicit installed types package directory, relative to the project or absolute. */
10
+ typesRoot?: string;
11
+ }
12
+ export declare const checkerVersion: string;
13
+ export declare const typeImplementation: URL[];
14
+ export declare function openTypesRelease(api: API, { projectRoot, targetVersion, typesRoot }: TypeSelection): Promise<{
15
+ version: string;
16
+ inputs: string[];
17
+ category(kind: 'behavior' | 'resource' | 'other', file: string): string | undefined;
18
+ check: (pending: readonly import("./document-types.ts").DocumentInput[], signal?: AbortSignal) => import("./document-types.ts").TypeFinding[][];
19
+ literal: typeof documentLiteral;
20
+ }>;
@@ -0,0 +1,76 @@
1
+ import { readFile, readdir } from 'node:fs/promises';
2
+ import { createRequire } from 'node:module';
3
+ import path from 'node:path';
4
+ import { version } from 'typescript-native';
5
+ import { createDocumentChecker, declaredCategories, documentCategory, documentLiteral } from './document-types.js';
6
+ export { API } from 'typescript-native/sync';
7
+ const packageName = '@bedrock-core/bedrock-types';
8
+ export const checkerVersion = version;
9
+ export const typeImplementation = [
10
+ new URL(import.meta.url),
11
+ new URL('./document-types' + path.extname(new URL(import.meta.url).pathname), import.meta.url),
12
+ ];
13
+ function track(version) {
14
+ return version.replace(/^1\./, '').split(/[.-]/).slice(0, 2).join('.');
15
+ }
16
+ function resolvePackage(require) {
17
+ try {
18
+ return require.resolve(packageName + '/package.json');
19
+ }
20
+ catch (error) {
21
+ if (error.code !== 'MODULE_NOT_FOUND') {
22
+ throw error;
23
+ }
24
+ }
25
+ }
26
+ async function declarationInputs(directory) {
27
+ const inputs = [];
28
+ for (const entry of (await readdir(directory, { withFileTypes: true })).sort((a, b) => a.name.localeCompare(b.name))) {
29
+ const file = path.join(directory, entry.name);
30
+ if (entry.isDirectory()) {
31
+ inputs.push(...await declarationInputs(file));
32
+ }
33
+ else if (entry.name.endsWith('.d.ts') || entry.name === 'package.json') {
34
+ inputs.push(file);
35
+ }
36
+ }
37
+ return inputs;
38
+ }
39
+ export async function openTypesRelease(api, { projectRoot, targetVersion, typesRoot }) {
40
+ const project = path.resolve(projectRoot ?? process.cwd());
41
+ const manifests = typesRoot
42
+ ? [path.resolve(project, typesRoot, 'package.json')]
43
+ : [resolvePackage(createRequire(path.join(project, 'package.json'))), resolvePackage(createRequire(import.meta.url))];
44
+ const versions = [];
45
+ for (const manifest of new Set(manifests)) {
46
+ if (!manifest) {
47
+ continue;
48
+ }
49
+ const metadata = JSON.parse(await readFile(manifest, 'utf8'));
50
+ if (metadata.name !== packageName || typeof metadata.version !== 'string') {
51
+ throw new Error('Invalid Bedrock types package metadata in ' + manifest);
52
+ }
53
+ versions.push(metadata.version);
54
+ if (targetVersion && track(metadata.version) !== track(targetVersion)) {
55
+ continue;
56
+ }
57
+ const distribution = path.join(path.dirname(manifest), 'dist');
58
+ const categories = declaredCategories(api, path.join(distribution, 'documents.d.ts'));
59
+ const inputs = [manifest, ...await declarationInputs(distribution)];
60
+ return {
61
+ version: metadata.version,
62
+ inputs,
63
+ category(kind, file) {
64
+ if (kind !== 'other') {
65
+ const category = documentCategory(kind, file);
66
+ return categories.has(category) ? category : undefined;
67
+ }
68
+ },
69
+ check: createDocumentChecker(api, distribution),
70
+ literal: documentLiteral,
71
+ };
72
+ }
73
+ const target = targetVersion ? ' for Bedrock ' + targetVersion : '';
74
+ const installed = versions.length ? ` Found ${versions.join(', ')}.` : '';
75
+ throw new Error(`Install a matching ${packageName} release${target}.${installed}`);
76
+ }
package/package.json CHANGED
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "name": "@bedrock-core/builder-validation",
3
- "version": "0.2.0",
3
+ "version": "0.3.0",
4
4
  "type": "module",
5
- "description": "Standalone pack content validation against Mojang's Bedrock schema catalog",
5
+ "description": "Standalone pack content validation against native Bedrock document types",
6
6
  "exports": {
7
7
  ".": {
8
8
  "types": "./dist/src/index.d.ts",
@@ -13,13 +13,9 @@
13
13
  "node": ">=26.13.0"
14
14
  },
15
15
  "dependencies": {
16
- "@minecraft/bedrock-schemas": "1.26.50",
17
- "ajv": "8.17.1",
16
+ "@bedrock-core/bedrock-types": "26.50.5",
18
17
  "jsonc-parser": "3.3.1",
19
- "picomatch": "^4.0.2"
20
- },
21
- "devDependencies": {
22
- "@types/picomatch": "^4.0.2"
18
+ "typescript-native": "npm:typescript@7.1.0-beta"
23
19
  },
24
20
  "license": "MIT",
25
21
  "files": [
@@ -1,8 +0,0 @@
1
- {
2
- "$schema": "http://json-schema.org/draft-07/schema#",
3
- "title": "Resource pack language catalog",
4
- "description": "The locale array in texts/languages.json, as documented by the Bedrock Wiki text guide.",
5
- "type": "array",
6
- "items": { "type": "string", "minLength": 1 },
7
- "uniqueItems": true
8
- }