@osdk/seed-compiler 0.2.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/CHANGELOG.md +12 -0
- package/README.md +80 -0
- package/bin/seed-compiler.mjs +6 -0
- package/build/browser/cli/main.js +60 -0
- package/build/browser/cli/main.js.map +1 -0
- package/build/browser/compileSeedData.js +322 -0
- package/build/browser/compileSeedData.js.map +1 -0
- package/build/browser/index.js +19 -0
- package/build/browser/index.js.map +1 -0
- package/build/browser/schema.js +51 -0
- package/build/browser/schema.js.map +1 -0
- package/build/cjs/index.cjs +248 -0
- package/build/cjs/index.cjs.map +1 -0
- package/build/cjs/index.d.cts +91 -0
- package/build/esm/cli/main.js +60 -0
- package/build/esm/cli/main.js.map +1 -0
- package/build/esm/compileSeedData.js +322 -0
- package/build/esm/compileSeedData.js.map +1 -0
- package/build/esm/index.js +19 -0
- package/build/esm/index.js.map +1 -0
- package/build/esm/schema.js +51 -0
- package/build/esm/schema.js.map +1 -0
- package/build/types/cli/main.d.ts +1 -0
- package/build/types/cli/main.d.ts.map +1 -0
- package/build/types/compileSeedData.d.ts +64 -0
- package/build/types/compileSeedData.d.ts.map +1 -0
- package/build/types/index.d.ts +3 -0
- package/build/types/index.d.ts.map +1 -0
- package/build/types/schema.d.ts +24 -0
- package/build/types/schema.d.ts.map +1 -0
- package/package.json +76 -0
|
@@ -0,0 +1,248 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
var consola = require('consola');
|
|
4
|
+
var jiti = require('jiti');
|
|
5
|
+
var fs = require('fs');
|
|
6
|
+
var path = require('path');
|
|
7
|
+
|
|
8
|
+
function _interopNamespace(e) {
|
|
9
|
+
if (e && e.__esModule) return e;
|
|
10
|
+
var n = Object.create(null);
|
|
11
|
+
if (e) {
|
|
12
|
+
Object.keys(e).forEach(function (k) {
|
|
13
|
+
if (k !== 'default') {
|
|
14
|
+
var d = Object.getOwnPropertyDescriptor(e, k);
|
|
15
|
+
Object.defineProperty(n, k, d.get ? d : {
|
|
16
|
+
enumerable: true,
|
|
17
|
+
get: function () { return e[k]; }
|
|
18
|
+
});
|
|
19
|
+
}
|
|
20
|
+
});
|
|
21
|
+
}
|
|
22
|
+
n.default = e;
|
|
23
|
+
return Object.freeze(n);
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
var fs__namespace = /*#__PURE__*/_interopNamespace(fs);
|
|
27
|
+
var path__namespace = /*#__PURE__*/_interopNamespace(path);
|
|
28
|
+
|
|
29
|
+
// src/compileSeedData.ts
|
|
30
|
+
var EXPECTED_JS_TYPE = {
|
|
31
|
+
// string-encoded primitives
|
|
32
|
+
string: "string",
|
|
33
|
+
marking: "string",
|
|
34
|
+
timestamp: "string",
|
|
35
|
+
date: "string",
|
|
36
|
+
datetime: "string",
|
|
37
|
+
long: "string",
|
|
38
|
+
decimal: "string",
|
|
39
|
+
ipAddress: "string",
|
|
40
|
+
cipherText: "string",
|
|
41
|
+
// numeric primitives
|
|
42
|
+
integer: "number",
|
|
43
|
+
byte: "number",
|
|
44
|
+
short: "number",
|
|
45
|
+
double: "number",
|
|
46
|
+
float: "number",
|
|
47
|
+
// boolean
|
|
48
|
+
boolean: "boolean"
|
|
49
|
+
};
|
|
50
|
+
var WIRE_TYPE_FORMAT = {
|
|
51
|
+
timestamp: {
|
|
52
|
+
pattern: /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-]\d{2}:\d{2})$/,
|
|
53
|
+
example: "2025-01-01T00:00:00Z"
|
|
54
|
+
},
|
|
55
|
+
date: {
|
|
56
|
+
pattern: /^\d{4}-\d{2}-\d{2}$/,
|
|
57
|
+
example: "2025-01-01"
|
|
58
|
+
},
|
|
59
|
+
datetime: {
|
|
60
|
+
pattern: /^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-]\d{2}:\d{2})?)?$/,
|
|
61
|
+
example: "2025-01-01T12:00:00Z"
|
|
62
|
+
},
|
|
63
|
+
long: {
|
|
64
|
+
// Strict decimal integer — matches Rust's str::parse::<i64>().
|
|
65
|
+
// No scientific notation, no decimal point, no whitespace.
|
|
66
|
+
pattern: /^-?\d+$/,
|
|
67
|
+
example: "9007199254740993"
|
|
68
|
+
},
|
|
69
|
+
decimal: {
|
|
70
|
+
// Numeric string with optional decimal point. Anchored.
|
|
71
|
+
// Rust stores any string (no validation), but we reject obviously invalid values.
|
|
72
|
+
pattern: /^-?\d+(\.\d+)?$/,
|
|
73
|
+
example: "123.45"
|
|
74
|
+
}
|
|
75
|
+
};
|
|
76
|
+
async function compileSeedData(seedFiles, outputPath, schema) {
|
|
77
|
+
consola.consola.info(`Compiling seed data from ${seedFiles.length} file(s)...`);
|
|
78
|
+
const outputs = [];
|
|
79
|
+
for (const seedFile of seedFiles) {
|
|
80
|
+
outputs.push(await loadSeedFile(seedFile));
|
|
81
|
+
}
|
|
82
|
+
const merged = mergeSeedOutputs(outputs, schema);
|
|
83
|
+
validateSeedOutput(merged, schema);
|
|
84
|
+
const totalObjects = Object.values(merged.objects).reduce((sum, arr) => sum + arr.length, 0);
|
|
85
|
+
const outputDir = path__namespace.dirname(outputPath);
|
|
86
|
+
await fs__namespace.promises.mkdir(outputDir, {
|
|
87
|
+
recursive: true
|
|
88
|
+
});
|
|
89
|
+
await fs__namespace.promises.writeFile(outputPath, JSON.stringify(merged, null, 2));
|
|
90
|
+
consola.consola.success(`Seed data compiled successfully (${totalObjects} objects, ${merged.links.length} links)`);
|
|
91
|
+
}
|
|
92
|
+
function mergeSeedOutputs(outputs, schemaMap) {
|
|
93
|
+
const merged = {
|
|
94
|
+
objects: {},
|
|
95
|
+
links: []
|
|
96
|
+
};
|
|
97
|
+
const seenPks = /* @__PURE__ */ new Map();
|
|
98
|
+
const seenLinks = /* @__PURE__ */ new Set();
|
|
99
|
+
for (const output of outputs) {
|
|
100
|
+
mergeObjectsInto(merged, output.objects, schemaMap, seenPks);
|
|
101
|
+
mergeLinksInto(merged, output.links, seenLinks);
|
|
102
|
+
}
|
|
103
|
+
return merged;
|
|
104
|
+
}
|
|
105
|
+
function mergeObjectsInto(merged, source, schemaMap, seenPks) {
|
|
106
|
+
for (const [apiName, objects] of Object.entries(source)) {
|
|
107
|
+
const schema = schemaMap.get(apiName);
|
|
108
|
+
if (!schema) {
|
|
109
|
+
throw new Error(`Object type '${apiName}' in seed data is not defined in the ontology`);
|
|
110
|
+
}
|
|
111
|
+
const bucket = merged.objects[apiName] ??= [];
|
|
112
|
+
const pkSet = getOrInit(seenPks, apiName, () => /* @__PURE__ */ new Set());
|
|
113
|
+
for (const obj of objects) {
|
|
114
|
+
const pk = String(obj[schema.primaryKeyApiName] ?? "");
|
|
115
|
+
if (pkSet.has(pk)) {
|
|
116
|
+
throw new Error(`Duplicate primary key '${pk}' for '${apiName}' across seed files`);
|
|
117
|
+
}
|
|
118
|
+
pkSet.add(pk);
|
|
119
|
+
bucket.push(obj);
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
function mergeLinksInto(merged, source, seenLinks) {
|
|
124
|
+
for (const link of source) {
|
|
125
|
+
const key = linkKey(link);
|
|
126
|
+
if (seenLinks.has(key)) {
|
|
127
|
+
consola.consola.warn(`Duplicate link deduplicated: ${link.linkType} from ${link.sourceObjectType}:${link.sourceKey} to ${link.targetObjectType}:${link.targetKey}`);
|
|
128
|
+
continue;
|
|
129
|
+
}
|
|
130
|
+
seenLinks.add(key);
|
|
131
|
+
merged.links.push(link);
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
function linkKey(link) {
|
|
135
|
+
return `${link.sourceObjectType}:${link.sourceKey}:${link.linkType}:${link.targetObjectType}:${link.targetKey}`;
|
|
136
|
+
}
|
|
137
|
+
function getOrInit(map, key, init) {
|
|
138
|
+
let value = map.get(key);
|
|
139
|
+
if (value === void 0) {
|
|
140
|
+
value = init();
|
|
141
|
+
map.set(key, value);
|
|
142
|
+
}
|
|
143
|
+
return value;
|
|
144
|
+
}
|
|
145
|
+
function validateSeedOutput(output, schemaMap) {
|
|
146
|
+
const errors = validateAndCollectFormatErrors(output, schemaMap);
|
|
147
|
+
if (errors.length > 0) {
|
|
148
|
+
throw new Error(formatValidationErrors(errors));
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
function validateAndCollectFormatErrors(output, schemaMap) {
|
|
152
|
+
const errors = [];
|
|
153
|
+
for (const [apiName, objects] of Object.entries(output.objects)) {
|
|
154
|
+
const schema = schemaMap.get(apiName);
|
|
155
|
+
if (!schema) {
|
|
156
|
+
throw new Error(`Object type '${apiName}' in seed data is not defined in the ontology`);
|
|
157
|
+
}
|
|
158
|
+
for (const [i, obj] of objects.entries()) {
|
|
159
|
+
for (const [key, value] of Object.entries(obj)) {
|
|
160
|
+
const wireType = schema.properties.get(key);
|
|
161
|
+
if (wireType === void 0) {
|
|
162
|
+
throw new Error(`Property '${key}' on '${apiName}' object (index ${i}) is not defined in the ontology`);
|
|
163
|
+
}
|
|
164
|
+
if (value == null) {
|
|
165
|
+
throw new Error(`Property '${key}' on '${apiName}' object (index ${i}) is null or undefined`);
|
|
166
|
+
}
|
|
167
|
+
const expectedJsType = EXPECTED_JS_TYPE[wireType];
|
|
168
|
+
if (expectedJsType !== void 0 && typeof value !== expectedJsType) {
|
|
169
|
+
throw new Error(`Property '${key}' on '${apiName}' object (index ${i}) expects ${wireType} (a ${expectedJsType}) but got ${typeof value}`);
|
|
170
|
+
}
|
|
171
|
+
const format = WIRE_TYPE_FORMAT[wireType];
|
|
172
|
+
if (!format) continue;
|
|
173
|
+
if (format.pattern.test(value)) continue;
|
|
174
|
+
errors.push({
|
|
175
|
+
objectType: apiName,
|
|
176
|
+
objectIndex: i,
|
|
177
|
+
field: key,
|
|
178
|
+
message: `property '${key}' has invalid ${wireType} format: '${String(value)}'. Expected format like '${format.example}'`
|
|
179
|
+
});
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
return errors;
|
|
184
|
+
}
|
|
185
|
+
function formatValidationErrors(errors) {
|
|
186
|
+
const grouped = /* @__PURE__ */ new Map();
|
|
187
|
+
for (const err of errors) {
|
|
188
|
+
const messages = getOrInit(grouped, err.objectType, () => []);
|
|
189
|
+
messages.push(` object[${err.objectIndex}]: ${err.message}`);
|
|
190
|
+
}
|
|
191
|
+
const body = [...grouped.entries()].map(([type, msgs]) => `${type}:
|
|
192
|
+
${msgs.join("\n")}`).join("\n\n");
|
|
193
|
+
const errorWord = errors.length === 1 ? "error" : "errors";
|
|
194
|
+
const typeWord = grouped.size === 1 ? "object type" : "object types";
|
|
195
|
+
return `Seed data validation failed (${errors.length} ${errorWord} across ${grouped.size} ${typeWord}):
|
|
196
|
+
|
|
197
|
+
${body}`;
|
|
198
|
+
}
|
|
199
|
+
async function loadSeedFile(seedFile) {
|
|
200
|
+
consola.consola.info(`Loading seed file: ${seedFile}`);
|
|
201
|
+
let seedModule;
|
|
202
|
+
try {
|
|
203
|
+
const jiti$1 = jiti.createJiti(seedFile, {
|
|
204
|
+
moduleCache: false,
|
|
205
|
+
debug: false
|
|
206
|
+
});
|
|
207
|
+
seedModule = await jiti$1.import(seedFile);
|
|
208
|
+
} catch (e) {
|
|
209
|
+
const message = e instanceof Error ? e.message : String(e);
|
|
210
|
+
throw new Error(`Seed file '${path__namespace.basename(seedFile)}' failed to compile:
|
|
211
|
+
${message}`);
|
|
212
|
+
}
|
|
213
|
+
if (!seedModule.default || typeof seedModule.default !== "object") {
|
|
214
|
+
throw new Error(`Seed file '${path__namespace.basename(seedFile)}' must have a default export. Use createSeed() from @osdk/seed-helpers.`);
|
|
215
|
+
}
|
|
216
|
+
const output = seedModule.default;
|
|
217
|
+
if (!output.objects || typeof output.objects !== "object") {
|
|
218
|
+
throw new Error(`Seed file '${path__namespace.basename(seedFile)}' default export is not a valid SeedOutput. Use createSeed() from @osdk/seed-helpers.`);
|
|
219
|
+
}
|
|
220
|
+
return {
|
|
221
|
+
...output,
|
|
222
|
+
links: output.links ?? []
|
|
223
|
+
};
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
// src/schema.ts
|
|
227
|
+
function schemaFromMetadata(metadata) {
|
|
228
|
+
const map = /* @__PURE__ */ new Map();
|
|
229
|
+
for (const [apiName, full] of Object.entries(metadata.objectTypes)) {
|
|
230
|
+
const ot = full.objectType;
|
|
231
|
+
const properties = /* @__PURE__ */ new Map();
|
|
232
|
+
for (const [propApiName, prop] of Object.entries(ot.properties)) {
|
|
233
|
+
properties.set(propApiName, prop.dataType.type);
|
|
234
|
+
}
|
|
235
|
+
map.set(apiName, {
|
|
236
|
+
properties,
|
|
237
|
+
primaryKeyApiName: ot.primaryKey
|
|
238
|
+
});
|
|
239
|
+
}
|
|
240
|
+
return map;
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
exports.compileSeedData = compileSeedData;
|
|
244
|
+
exports.mergeSeedOutputs = mergeSeedOutputs;
|
|
245
|
+
exports.schemaFromMetadata = schemaFromMetadata;
|
|
246
|
+
exports.validateSeedOutput = validateSeedOutput;
|
|
247
|
+
//# sourceMappingURL=index.cjs.map
|
|
248
|
+
//# sourceMappingURL=index.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/compileSeedData.ts","../../src/schema.ts"],"names":["consola","path","fs","jiti","createJiti"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuCA,IAAM,gBAAA,GAAmB;AAAA;AAAA,EAEvB,MAAA,EAAQ,QAAA;AAAA,EACR,OAAA,EAAS,QAAA;AAAA,EACT,SAAA,EAAW,QAAA;AAAA,EACX,IAAA,EAAM,QAAA;AAAA,EACN,QAAA,EAAU,QAAA;AAAA,EACV,IAAA,EAAM,QAAA;AAAA,EACN,OAAA,EAAS,QAAA;AAAA,EACT,SAAA,EAAW,QAAA;AAAA,EACX,UAAA,EAAY,QAAA;AAAA;AAAA,EAEZ,OAAA,EAAS,QAAA;AAAA,EACT,IAAA,EAAM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AM,UAAA,uBAAiB,GAAA,EAAI;AAC3B,IAAA,KAAA,MAAW,CAAC,aAAa,IAAI,CAAA,IAAK,OAAO,OAAA,CAAQ,EAAA,CAAG,UAAU,CAAA,EAAG;AAC/D,MAAA,UAAA,CAAW,GAAA,CAAI,WAAA,EAAa,IAAA,CAAK,QAAA,CAAS,IAAI,CAAA;AAAA,IAChD;AACA,IAAA,GAAA,CAAI,IAAI,OAAA,EAAS;AAAA,MACf,UAAA;AAAA,MACA,mBAAmB,EAAA,CAAG;AAAA,KACvB,CAAA;AAAA,EACH;AACA,EAAA,OAAO,GAAA;AACT","file":"index.cjs","sourcesContent":["/*\n * Copyright 2025 Palantir Technologies, Inc. All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { consola } from \"consola\";\nimport { createJiti } from \"jiti\";\nimport * as fs from \"node:fs\";\nimport * as path from \"node:path\";\n\n/**\n * One string-format validation failure (e.g., a timestamp value that doesn't\n * match the wire format regex). Format failures are collected across the\n * whole output and reported together at the end so users can fix many\n * content mistakes in one pass. Structural failures (unknown object type,\n * unknown property name, null value, wrong JS type) throw immediately\n * instead — they're not aggregated, so they don't need this struct.\n */\n\n/**\n * Expected runtime JS type for each cataloged wire type.\n *\n * Used to fail fast on `as any` callers that pass a value of the wrong shape\n * (e.g., `age: \"30\"` when `age` is an integer). Wire types not listed here\n * are not strictly typed by this validator — currently `attachment`,\n * `mediaReference`, `geopoint`, `geoshape`, `vector`, `array`, `struct`,\n * which have non-primitive runtime shapes that need bespoke validation.\n */\nconst EXPECTED_JS_TYPE = {\n // string-encoded primitives\n string: \"string\",\n marking: \"string\",\n timestamp: \"string\",\n date: \"string\",\n datetime: \"string\",\n long: \"string\",\n decimal: \"string\",\n ipAddress: \"string\",\n cipherText: \"string\",\n // numeric primitives\n integer: \"number\",\n byte: \"number\",\n short: \"number\",\n double: \"number\",\n float: \"number\",\n // boolean\n boolean: \"boolean\"\n};\n\n/**\n * Regex patterns for string-encoded wire types that TypeScript cannot validate.\n *\n * These patterns are aligned with the Rust backend's actual parsing behavior:\n * - timestamp: RFC 3339 parse on the Rust side — requires timezone, rejects trailing garbage\n * - date: stored as raw string, but only YYYY-MM-DD works in SQLite queries\n * - datetime: stored as raw string, same YYYY-MM-DD requirement for query correctness\n * - long: strict decimal integer parse on the Rust side — no scientific notation\n * - decimal: Rust stores any string (no validation), but we enforce numeric format\n * to prevent obviously invalid values from silently passing through\n */\nconst WIRE_TYPE_FORMAT = {\n timestamp: {\n pattern: /^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?(Z|[+-]\\d{2}:\\d{2})$/,\n example: \"2025-01-01T00:00:00Z\"\n },\n date: {\n pattern: /^\\d{4}-\\d{2}-\\d{2}$/,\n example: \"2025-01-01\"\n },\n datetime: {\n pattern: /^\\d{4}-\\d{2}-\\d{2}(T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?(Z|[+-]\\d{2}:\\d{2})?)?$/,\n example: \"2025-01-01T12:00:00Z\"\n },\n long: {\n // Strict decimal integer — matches Rust's str::parse::<i64>().\n // No scientific notation, no decimal point, no whitespace.\n pattern: /^-?\\d+$/,\n example: \"9007199254740993\"\n },\n decimal: {\n // Numeric string with optional decimal point. Anchored.\n // Rust stores any string (no validation), but we reject obviously invalid values.\n pattern: /^-?\\d+(\\.\\d+)?$/,\n example: \"123.45\"\n }\n};\n\n/**\n * Compiles one or more seed data files into a single merged JSON output.\n *\n * Pipeline: load each file → merge → validate against schema → write JSON.\n *\n * @param seedFiles - Absolute paths to seed `.mts` / `.ts` files.\n * @param outputPath - Where to write the merged seed JSON.\n * @param schema - Per-object-type schema, typically built from\n * {@link import(\"./schema.js\").schemaFromMetadata}.\n * @throws if any seed file fails to compile or has an invalid export, if any\n * object type or property name is unknown to the schema, if any\n * primary key is duplicated across files, if any property value is\n * null/undefined or has the wrong JS type, or if any string-encoded\n * value has an invalid format.\n */\nexport async function compileSeedData(seedFiles, outputPath, schema) {\n consola.info(`Compiling seed data from ${seedFiles.length} file(s)...`);\n const outputs = [];\n for (const seedFile of seedFiles) {\n outputs.push(await loadSeedFile(seedFile));\n }\n const merged = mergeSeedOutputs(outputs, schema);\n validateSeedOutput(merged, schema);\n const totalObjects = Object.values(merged.objects).reduce((sum, arr) => sum + arr.length, 0);\n const outputDir = path.dirname(outputPath);\n await fs.promises.mkdir(outputDir, {\n recursive: true\n });\n await fs.promises.writeFile(outputPath, JSON.stringify(merged, null, 2));\n consola.success(`Seed data compiled successfully (${totalObjects} objects, ${merged.links.length} links)`);\n}\n\n/**\n * Merges multiple {@link SeedOutput}s into one.\n *\n * - Objects for the same type combine additively.\n * - Duplicate primary keys across files cause an error (checked by the actual\n * PK field from the schema, not by comparing the full serialized object).\n * - Duplicate links (same source, target, and link type) are deduplicated\n * with a warning logged to the console.\n *\n * @param outputs - The individual seed outputs to merge.\n * @param schemaMap - Used to resolve the primary key field name per object type.\n * @returns A single merged SeedOutput ready for validation and writing.\n * @throws if any primary key appears in more than one file for the same type.\n */\nexport function mergeSeedOutputs(outputs, schemaMap) {\n const merged = {\n objects: {},\n links: []\n };\n const seenPks = new Map();\n const seenLinks = new Set();\n for (const output of outputs) {\n mergeObjectsInto(merged, output.objects, schemaMap, seenPks);\n mergeLinksInto(merged, output.links, seenLinks);\n }\n return merged;\n}\nfunction mergeObjectsInto(merged, source, schemaMap, seenPks) {\n for (const [apiName, objects] of Object.entries(source)) {\n const schema = schemaMap.get(apiName);\n if (!schema) {\n throw new Error(`Object type '${apiName}' in seed data is not defined in the ontology`);\n }\n const bucket = merged.objects[apiName] ??= [];\n const pkSet = getOrInit(seenPks, apiName, () => new Set());\n for (const obj of objects) {\n const pk = String(obj[schema.primaryKeyApiName] ?? \"\");\n if (pkSet.has(pk)) {\n throw new Error(`Duplicate primary key '${pk}' for '${apiName}' across seed files`);\n }\n pkSet.add(pk);\n bucket.push(obj);\n }\n }\n}\nfunction mergeLinksInto(merged, source, seenLinks) {\n for (const link of source) {\n const key = linkKey(link);\n if (seenLinks.has(key)) {\n consola.warn(`Duplicate link deduplicated: ${link.linkType}` + ` from ${link.sourceObjectType}:${link.sourceKey}` + ` to ${link.targetObjectType}:${link.targetKey}`);\n continue;\n }\n seenLinks.add(key);\n merged.links.push(link);\n }\n}\nfunction linkKey(link) {\n return `${link.sourceObjectType}:${link.sourceKey}` + `:${link.linkType}` + `:${link.targetObjectType}:${link.targetKey}`;\n}\nfunction getOrInit(map, key, init) {\n let value = map.get(key);\n if (value === undefined) {\n value = init();\n map.set(key, value);\n }\n return value;\n}\n\n/**\n * Validates the seed output against the ontology schema.\n *\n * Hard errors (thrown immediately) for any of:\n *\n * - Object types in the seed output not defined in the ontology.\n * - Property names on a seed object not defined on that type.\n * - `null`/`undefined` property values. Typed callers can't reach this\n * (the builder's `SeedProps<Q>` rejects `null`); any null at runtime is\n * a sign of `as any` or a hand-rolled output.\n * - JS type mismatches against the cataloged wire-type-to-JS-type map\n * (e.g., `age: \"30\"` when `age` is an integer, or `score: 30` when\n * `score` is a long).\n *\n * For wire types whose runtime shape this validator doesn't catalog\n * (`attachment`, `mediaReference`, `geopoint`, `geoshape`, `vector`,\n * `array`, `struct`), JS-type checking is skipped — they have non-primitive\n * shapes that would need bespoke validation. They still go through the\n * earlier object-type / property-name / null checks.\n *\n * After JS-type validation, string values are checked against the format\n * regex for their wire type (timestamp, date, datetime, long, decimal).\n * The one thing TypeScript cannot distinguish on its own is whether a\n * `string` value matches its wire format (e.g., `\"not-a-date\"` vs\n * `\"2025-01-01T00:00:00Z\"` are both valid `string` to the type system);\n * format validation fills that gap.\n *\n * @throws Error on any structural violation listed above, or listing all\n * format failures grouped by object type.\n */\nexport function validateSeedOutput(output, schemaMap) {\n const errors = validateAndCollectFormatErrors(output, schemaMap);\n if (errors.length > 0) {\n throw new Error(formatValidationErrors(errors));\n }\n}\nfunction validateAndCollectFormatErrors(output, schemaMap) {\n const errors = [];\n for (const [apiName, objects] of Object.entries(output.objects)) {\n const schema = schemaMap.get(apiName);\n if (!schema) {\n throw new Error(`Object type '${apiName}' in seed data is not defined in the ontology`);\n }\n for (const [i, obj] of objects.entries()) {\n for (const [key, value] of Object.entries(obj)) {\n const wireType = schema.properties.get(key);\n if (wireType === undefined) {\n throw new Error(`Property '${key}' on '${apiName}' object` + ` (index ${i}) is not defined in the ontology`);\n }\n if (value == null) {\n throw new Error(`Property '${key}' on '${apiName}' object` + ` (index ${i}) is null or undefined`);\n }\n const expectedJsType = EXPECTED_JS_TYPE[wireType];\n if (expectedJsType !== undefined && typeof value !== expectedJsType) {\n throw new Error(`Property '${key}' on '${apiName}' object` + ` (index ${i}) expects ${wireType} (a ${expectedJsType})` + ` but got ${typeof value}`);\n }\n const format = WIRE_TYPE_FORMAT[wireType];\n if (!format) continue;\n\n // Format regex only applies to string-encoded wire types, all of\n // which have EXPECTED_JS_TYPE === \"string\"; the cast is safe here\n // because the JS-type check above would have thrown otherwise.\n if (format.pattern.test(value)) continue;\n errors.push({\n objectType: apiName,\n objectIndex: i,\n field: key,\n message: `property '${key}' has invalid ${wireType}` + ` format: '${String(value)}'. Expected format like '${format.example}'`\n });\n }\n }\n }\n return errors;\n}\nfunction formatValidationErrors(errors) {\n const grouped = new Map();\n for (const err of errors) {\n const messages = getOrInit(grouped, err.objectType, () => []);\n messages.push(` object[${err.objectIndex}]: ${err.message}`);\n }\n const body = [...grouped.entries()].map(([type, msgs]) => `${type}:\\n${msgs.join(\"\\n\")}`).join(\"\\n\\n\");\n const errorWord = errors.length === 1 ? \"error\" : \"errors\";\n const typeWord = grouped.size === 1 ? \"object type\" : \"object types\";\n return `Seed data validation failed ` + `(${errors.length} ${errorWord} across ${grouped.size} ${typeWord}` + `):\\n\\n${body}`;\n}\n\n/**\n * Loads a single seed file via jiti and extracts its default export.\n *\n * jiti.import() fully executes the module — the `createSeed()` builder\n * function runs during import and the default export is the resulting\n * SeedOutput.\n *\n * @throws with a contextual message wrapping the original error and filename.\n */\nasync function loadSeedFile(seedFile) {\n consola.info(`Loading seed file: ${seedFile}`);\n let seedModule;\n try {\n const jiti = createJiti(seedFile, {\n moduleCache: false,\n debug: false\n });\n seedModule = await jiti.import(seedFile);\n } catch (e) {\n const message = e instanceof Error ? e.message : String(e);\n throw new Error(`Seed file '${path.basename(seedFile)}' failed to compile:\\n ${message}`);\n }\n if (!seedModule.default || typeof seedModule.default !== \"object\") {\n throw new Error(`Seed file '${path.basename(seedFile)}' must have a default export. ` + `Use createSeed() from @osdk/seed-helpers.`);\n }\n const output = seedModule.default;\n if (!output.objects || typeof output.objects !== \"object\") {\n throw new Error(`Seed file '${path.basename(seedFile)}' default export is not a valid` + ` SeedOutput. Use createSeed() from @osdk/seed-helpers.`);\n }\n\n // Normalize: links are optional in the export but required in SeedOutput.\n // Spread to avoid mutating the module's exported object.\n return {\n ...output,\n links: output.links ?? []\n };\n}","/*\n * Copyright 2025 Palantir Technologies, Inc. All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Minimal schema for one object type — only what the compiler needs.\n *\n * - `properties`: property API name → wire type (e.g. `\"timestamp\"`, `\"long\"`),\n * used by the validator to enforce property existence, JS-type expectations,\n * and string format regexes.\n * - `primaryKeyApiName`: PK field name (for cross-file duplicate detection in merge).\n */\n\n/** Maps object type API name → its schema. */\n\n/**\n * Builds a {@link SchemaMap} from an `OntologyFullMetadata` document — the\n * shape produced by the OSDK SDK generator and serialized to\n * `ontology-metadata.json` alongside the generated `@ontology/sdk` package.\n *\n * Only `objectTypes` are read; the other top-level fields (action types,\n * query types, interfaces, etc.) are not relevant to seed validation.\n */\nexport function schemaFromMetadata(metadata) {\n const map = new Map();\n for (const [apiName, full] of Object.entries(metadata.objectTypes)) {\n const ot = full.objectType;\n const properties = new Map();\n for (const [propApiName, prop] of Object.entries(ot.properties)) {\n properties.set(propApiName, prop.dataType.type);\n }\n map.set(apiName, {\n properties,\n primaryKeyApiName: ot.primaryKey\n });\n }\n return map;\n}"]}
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
import { SeedOutput } from '@osdk/seed-helpers';
|
|
2
|
+
import { OntologyFullMetadata } from '@osdk/foundry.ontologies';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Minimal schema for one object type — only what the compiler needs.
|
|
6
|
+
*
|
|
7
|
+
* - `properties`: property API name → wire type (e.g. `"timestamp"`, `"long"`),
|
|
8
|
+
* used by the validator to enforce property existence, JS-type expectations,
|
|
9
|
+
* and string format regexes.
|
|
10
|
+
* - `primaryKeyApiName`: PK field name (for cross-file duplicate detection in merge).
|
|
11
|
+
*/
|
|
12
|
+
interface ObjectTypeSchema {
|
|
13
|
+
properties: Map<string, string>;
|
|
14
|
+
primaryKeyApiName: string;
|
|
15
|
+
}
|
|
16
|
+
/** Maps object type API name → its schema. */
|
|
17
|
+
type SchemaMap = Map<string, ObjectTypeSchema>;
|
|
18
|
+
/**
|
|
19
|
+
* Builds a {@link SchemaMap} from an `OntologyFullMetadata` document — the
|
|
20
|
+
* shape produced by the OSDK SDK generator and serialized to
|
|
21
|
+
* `ontology-metadata.json` alongside the generated `@ontology/sdk` package.
|
|
22
|
+
*
|
|
23
|
+
* Only `objectTypes` are read; the other top-level fields (action types,
|
|
24
|
+
* query types, interfaces, etc.) are not relevant to seed validation.
|
|
25
|
+
*/
|
|
26
|
+
declare function schemaFromMetadata(metadata: OntologyFullMetadata): SchemaMap;
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Compiles one or more seed data files into a single merged JSON output.
|
|
30
|
+
*
|
|
31
|
+
* Pipeline: load each file → merge → validate against schema → write JSON.
|
|
32
|
+
*
|
|
33
|
+
* @param seedFiles - Absolute paths to seed `.mts` / `.ts` files.
|
|
34
|
+
* @param outputPath - Where to write the merged seed JSON.
|
|
35
|
+
* @param schema - Per-object-type schema, typically built from
|
|
36
|
+
* {@link import("./schema.js").schemaFromMetadata}.
|
|
37
|
+
* @throws if any seed file fails to compile or has an invalid export, if any
|
|
38
|
+
* object type or property name is unknown to the schema, if any
|
|
39
|
+
* primary key is duplicated across files, if any property value is
|
|
40
|
+
* null/undefined or has the wrong JS type, or if any string-encoded
|
|
41
|
+
* value has an invalid format.
|
|
42
|
+
*/
|
|
43
|
+
declare function compileSeedData(seedFiles: string[], outputPath: string, schema: SchemaMap): Promise<void>;
|
|
44
|
+
/**
|
|
45
|
+
* Merges multiple {@link SeedOutput}s into one.
|
|
46
|
+
*
|
|
47
|
+
* - Objects for the same type combine additively.
|
|
48
|
+
* - Duplicate primary keys across files cause an error (checked by the actual
|
|
49
|
+
* PK field from the schema, not by comparing the full serialized object).
|
|
50
|
+
* - Duplicate links (same source, target, and link type) are deduplicated
|
|
51
|
+
* with a warning logged to the console.
|
|
52
|
+
*
|
|
53
|
+
* @param outputs - The individual seed outputs to merge.
|
|
54
|
+
* @param schemaMap - Used to resolve the primary key field name per object type.
|
|
55
|
+
* @returns A single merged SeedOutput ready for validation and writing.
|
|
56
|
+
* @throws if any primary key appears in more than one file for the same type.
|
|
57
|
+
*/
|
|
58
|
+
declare function mergeSeedOutputs(outputs: SeedOutput[], schemaMap: SchemaMap): SeedOutput;
|
|
59
|
+
/**
|
|
60
|
+
* Validates the seed output against the ontology schema.
|
|
61
|
+
*
|
|
62
|
+
* Hard errors (thrown immediately) for any of:
|
|
63
|
+
*
|
|
64
|
+
* - Object types in the seed output not defined in the ontology.
|
|
65
|
+
* - Property names on a seed object not defined on that type.
|
|
66
|
+
* - `null`/`undefined` property values. Typed callers can't reach this
|
|
67
|
+
* (the builder's `SeedProps<Q>` rejects `null`); any null at runtime is
|
|
68
|
+
* a sign of `as any` or a hand-rolled output.
|
|
69
|
+
* - JS type mismatches against the cataloged wire-type-to-JS-type map
|
|
70
|
+
* (e.g., `age: "30"` when `age` is an integer, or `score: 30` when
|
|
71
|
+
* `score` is a long).
|
|
72
|
+
*
|
|
73
|
+
* For wire types whose runtime shape this validator doesn't catalog
|
|
74
|
+
* (`attachment`, `mediaReference`, `geopoint`, `geoshape`, `vector`,
|
|
75
|
+
* `array`, `struct`), JS-type checking is skipped — they have non-primitive
|
|
76
|
+
* shapes that would need bespoke validation. They still go through the
|
|
77
|
+
* earlier object-type / property-name / null checks.
|
|
78
|
+
*
|
|
79
|
+
* After JS-type validation, string values are checked against the format
|
|
80
|
+
* regex for their wire type (timestamp, date, datetime, long, decimal).
|
|
81
|
+
* The one thing TypeScript cannot distinguish on its own is whether a
|
|
82
|
+
* `string` value matches its wire format (e.g., `"not-a-date"` vs
|
|
83
|
+
* `"2025-01-01T00:00:00Z"` are both valid `string` to the type system);
|
|
84
|
+
* format validation fills that gap.
|
|
85
|
+
*
|
|
86
|
+
* @throws Error on any structural violation listed above, or listing all
|
|
87
|
+
* format failures grouped by object type.
|
|
88
|
+
*/
|
|
89
|
+
declare function validateSeedOutput(output: SeedOutput, schemaMap: SchemaMap): void;
|
|
90
|
+
|
|
91
|
+
export { type ObjectTypeSchema, type SchemaMap, compileSeedData, mergeSeedOutputs, schemaFromMetadata, validateSeedOutput };
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* Copyright 2025 Palantir Technologies, Inc. All rights reserved.
|
|
3
|
+
*
|
|
4
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
5
|
+
* you may not use this file except in compliance with the License.
|
|
6
|
+
* You may obtain a copy of the License at
|
|
7
|
+
*
|
|
8
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
9
|
+
*
|
|
10
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
11
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
12
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
13
|
+
* See the License for the specific language governing permissions and
|
|
14
|
+
* limitations under the License.
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
import { consola } from "consola";
|
|
18
|
+
import * as fs from "node:fs";
|
|
19
|
+
import * as path from "node:path";
|
|
20
|
+
import invariant from "tiny-invariant";
|
|
21
|
+
import yargs from "yargs";
|
|
22
|
+
import { hideBin } from "yargs/helpers";
|
|
23
|
+
import { compileSeedData } from "../compileSeedData.js";
|
|
24
|
+
import { schemaFromMetadata } from "../schema.js";
|
|
25
|
+
export default async function main(args = process.argv) {
|
|
26
|
+
const opts = await yargs(hideBin(args)).version("0.2.0" ?? "").wrap(Math.min(120, yargs().terminalWidth())).strict().help().options({
|
|
27
|
+
metadata: {
|
|
28
|
+
describe: "Path to the ontology-metadata.json file written by the SDK generator. " + "Provides primary-key field names and property wire types.",
|
|
29
|
+
type: "string",
|
|
30
|
+
demandOption: true,
|
|
31
|
+
coerce: path.resolve
|
|
32
|
+
},
|
|
33
|
+
seedDir: {
|
|
34
|
+
describe: "Directory containing seed data .mts files. All top-level .mts " + "files are compiled (sorted by filename for deterministic output).",
|
|
35
|
+
type: "string",
|
|
36
|
+
demandOption: true,
|
|
37
|
+
coerce: path.resolve
|
|
38
|
+
},
|
|
39
|
+
output: {
|
|
40
|
+
alias: "o",
|
|
41
|
+
describe: "Output path for the compiled seed data JSON.",
|
|
42
|
+
type: "string",
|
|
43
|
+
demandOption: true,
|
|
44
|
+
coerce: path.resolve
|
|
45
|
+
}
|
|
46
|
+
}).parseAsync();
|
|
47
|
+
const metadataStat = fs.statSync(opts.metadata);
|
|
48
|
+
!metadataStat.isFile() ? process.env.NODE_ENV !== "production" ? invariant(false, `--metadata '${opts.metadata}' is not a file`) : invariant(false) : void 0;
|
|
49
|
+
const metadata = JSON.parse(fs.readFileSync(opts.metadata, "utf-8"));
|
|
50
|
+
const seedDirStat = fs.statSync(opts.seedDir);
|
|
51
|
+
!seedDirStat.isDirectory() ? process.env.NODE_ENV !== "production" ? invariant(false, `--seed-dir '${opts.seedDir}' is not a directory`) : invariant(false) : void 0;
|
|
52
|
+
const seedFiles = fs.readdirSync(opts.seedDir).filter(f => f.endsWith(".mts")).sort().map(f => path.join(opts.seedDir, f));
|
|
53
|
+
if (seedFiles.length === 0) {
|
|
54
|
+
consola.warn(`No .mts seed files found in ${opts.seedDir}`);
|
|
55
|
+
return;
|
|
56
|
+
}
|
|
57
|
+
const schema = schemaFromMetadata(metadata);
|
|
58
|
+
await compileSeedData(seedFiles, opts.output, schema);
|
|
59
|
+
}
|
|
60
|
+
//# sourceMappingURL=main.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"main.js","names":["consola","fs","path","invariant","yargs","hideBin","compileSeedData","schemaFromMetadata","main","args","process","argv","opts","version","wrap","Math","min","terminalWidth","strict","help","options","metadata","describe","type","demandOption","coerce","resolve","seedDir","output","alias","parseAsync","metadataStat","statSync","isFile","env","NODE_ENV","JSON","parse","readFileSync","seedDirStat","isDirectory","seedFiles","readdirSync","filter","f","endsWith","sort","map","join","length","warn","schema"],"sources":["main.ts"],"sourcesContent":["/*\n * Copyright 2025 Palantir Technologies, Inc. All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { OntologyFullMetadata } from \"@osdk/foundry.ontologies\";\nimport { consola } from \"consola\";\nimport * as fs from \"node:fs\";\nimport * as path from \"node:path\";\nimport invariant from \"tiny-invariant\";\nimport yargs from \"yargs\";\nimport { hideBin } from \"yargs/helpers\";\nimport { compileSeedData } from \"../compileSeedData.js\";\nimport { schemaFromMetadata } from \"../schema.js\";\n\nexport default async function main(\n args: string[] = process.argv,\n): Promise<void> {\n const opts: {\n metadata: string;\n seedDir: string;\n output: string;\n } = await yargs(hideBin(args))\n .version(process.env.PACKAGE_VERSION ?? \"\")\n .wrap(Math.min(120, yargs().terminalWidth()))\n .strict()\n .help()\n .options({\n metadata: {\n describe:\n \"Path to the ontology-metadata.json file written by the SDK generator. \"\n + \"Provides primary-key field names and property wire types.\",\n type: \"string\" as const,\n demandOption: true,\n coerce: path.resolve,\n },\n seedDir: {\n describe:\n \"Directory containing seed data .mts files. All top-level .mts \"\n + \"files are compiled (sorted by filename for deterministic output).\",\n type: \"string\" as const,\n demandOption: true,\n coerce: path.resolve,\n },\n output: {\n alias: \"o\",\n describe: \"Output path for the compiled seed data JSON.\",\n type: \"string\" as const,\n demandOption: true,\n coerce: path.resolve,\n },\n })\n .parseAsync();\n\n const metadataStat = fs.statSync(opts.metadata);\n invariant(\n metadataStat.isFile(),\n `--metadata '${opts.metadata}' is not a file`,\n );\n const metadata = JSON.parse(\n fs.readFileSync(opts.metadata, \"utf-8\"),\n ) as OntologyFullMetadata;\n\n const seedDirStat = fs.statSync(opts.seedDir);\n invariant(\n seedDirStat.isDirectory(),\n `--seed-dir '${opts.seedDir}' is not a directory`,\n );\n const seedFiles = fs.readdirSync(opts.seedDir)\n .filter((f) => f.endsWith(\".mts\"))\n .sort()\n .map((f) => path.join(opts.seedDir, f));\n\n if (seedFiles.length === 0) {\n consola.warn(`No .mts seed files found in ${opts.seedDir}`);\n return;\n }\n\n const schema = schemaFromMetadata(metadata);\n await compileSeedData(seedFiles, opts.output, schema);\n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