@tailor-platform/sdk 2.17.0 → 2.18.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.
@@ -13,6 +13,11 @@ type ValidateSeedResult = {
13
13
  valid: false;
14
14
  output: string;
15
15
  error: string;
16
+ /** Where the first reported error sits, for tooling that links to source. */
17
+ location?: {
18
+ file: string;
19
+ line?: number;
20
+ };
16
21
  };
17
22
  /**
18
23
  * A JSONL seed file that received values.
@@ -1,7 +1,8 @@
1
- import{basename as e,dirname as t,join as n}from"pathe";import{pathToFileURL as r}from"node:url";import{readFile as i,readdir as a,stat as o,writeFile as s}from"node:fs/promises";import{ErrorFormatter as c,LinesDB as l,defineSchema as u,findSchemaFile as d}from"@toiroakr/lines-db";const f=[`id`];async function resolveSeedDataTarget(n){let r=await o(n);if(r.isDirectory())return{dataDir:n};if(r.isFile()&&n.endsWith(`.jsonl`))return{dataDir:t(n),tableName:e(n,`.jsonl`)};throw Error(`Invalid path: ${n}. Must be a directory or .jsonl file.`)}async function listSeedTables(t){return(await a(t)).filter(e=>e.endsWith(`.jsonl`)).map(t=>e(t,`.jsonl`)).toSorted()}function formatWarnings(e){return e.length===0?[]:[...e.map(e=>`⚠ ${e}`),``]}function formatValidationErrors(e,t){let n=new c({verbose:t}),r=[],i=new Map;for(let t of e){let e=i.get(t.file)||[];e.push(t),i.set(t.file,e)}for(let[e,t]of i){r.push(n.formatErrorHeader(t.length,e)),r.push(``);let i=t.filter(e=>e.type!==`foreignKey`||!e.foreignKeyError),a=t.filter(e=>e.type===`foreignKey`&&e.foreignKeyError);i.length>0&&r.push(n.formatValidationErrors(i.map(e=>({file:e.file,rowIndex:e.rowIndex,issues:e.issues}))));for(let e of a)e.foreignKeyError&&r.push(n.formatForeignKeyError({file:e.file,rowIndex:e.rowIndex,column:e.foreignKeyError.column,value:e.foreignKeyError.value,referencedTable:e.foreignKeyError.referencedTable,referencedColumn:e.foreignKeyError.referencedColumn}));r.push(``)}return r.join(`
1
+ import{basename as e,dirname as t,join as n}from"pathe";import{pathToFileURL as r}from"node:url";import{readFile as i,readdir as a,stat as o,writeFile as s}from"node:fs/promises";import{ErrorFormatter as c,LinesDB as l,defineSchema as u,findSchemaFile as d}from"@toiroakr/lines-db";function physicalLineOfRecord(e,t){let n=e.split(`
2
+ `),r=t;for(let[e,t]of n.entries())if(t.trim().length!==0){if(r===0)return e+1;--r}}async function firstErrorLocation(e){let t=e[0];if(t)try{let e=await i(t.file,`utf-8`);return{file:t.file,line:physicalLineOfRecord(e,t.rowIndex)}}catch{return{file:t.file}}}const f=[`id`];async function resolveSeedDataTarget(n){let r=await o(n);if(r.isDirectory())return{dataDir:n};if(r.isFile()&&n.endsWith(`.jsonl`))return{dataDir:t(n),tableName:e(n,`.jsonl`)};throw Error(`Invalid path: ${n}. Must be a directory or .jsonl file.`)}async function listSeedTables(t){return(await a(t)).filter(e=>e.endsWith(`.jsonl`)).map(t=>e(t,`.jsonl`)).toSorted()}function formatWarnings(e){return e.length===0?[]:[...e.map(e=>`⚠ ${e}`),``]}function formatValidationErrors(e,t){let n=new c({verbose:t}),r=[],i=new Map;for(let t of e){let e=i.get(t.file)||[];e.push(t),i.set(t.file,e)}for(let[e,t]of i){r.push(n.formatErrorHeader(t.length,e)),r.push(``);let i=t.filter(e=>e.type!==`foreignKey`||!e.foreignKeyError),a=t.filter(e=>e.type===`foreignKey`&&e.foreignKeyError);i.length>0&&r.push(n.formatValidationErrors(i.map(e=>({file:e.file,rowIndex:e.rowIndex,issues:e.issues}))));for(let e of a)e.foreignKeyError&&r.push(n.formatForeignKeyError({file:e.file,rowIndex:e.rowIndex,column:e.foreignKeyError.column,value:e.foreignKeyError.value,referencedTable:e.foreignKeyError.referencedTable,referencedColumn:e.foreignKeyError.referencedColumn}));r.push(``)}return r.join(`
2
3
  `)}async function validateSeedData(e){let{path:t,verbose:n=!1}=e,{dataDir:r,tableName:i}=await resolveSeedDataTarget(t),a=l.create({dataDir:r}),o;try{o=await a.initialize({tableName:i,detailedValidate:!0})}finally{await a.close()}let s=formatWarnings(o.warnings);return o.valid?(s.push(`✓ All records are valid`),{valid:!0,output:s.join(`
3
4
  `)}):{valid:!1,output:s.join(`
4
- `),error:formatValidationErrors(o.errors,n)}}function ownValue(e,t){return Object.hasOwn(e,t)?e[t]:void 0}function setField(e,t,n){Object.defineProperty(e,t,{value:n,enumerable:!0,writable:!0,configurable:!0})}function isBlank(e){return e==null?!0:typeof e!=`object`||Array.isArray(e)?!1:Object.values(e).every(isBlank)}function splitLines(e){return e===``?[]:e.split(`
5
+ `),error:formatValidationErrors(o.errors,n),location:await firstErrorLocation(o.errors)}}function ownValue(e,t){return Object.hasOwn(e,t)?e[t]:void 0}function setField(e,t,n){Object.defineProperty(e,t,{value:n,enumerable:!0,writable:!0,configurable:!0})}function isBlank(e){return e==null?!0:typeof e!=`object`||Array.isArray(e)?!1:Object.values(e).every(isBlank)}function splitLines(e){return e===``?[]:e.split(`
5
6
  `).map((e,t,n)=>{let r=t===n.length-1?``:`
6
7
  `,i=e.endsWith(`\r`)?e.slice(0,-1):e,a=e.endsWith(`\r`)?`\r`:``,o;if(i.trim()!==``)try{let e=JSON.parse(i);o=typeof e==`object`&&e&&!Array.isArray(e)?e:void 0}catch{o=void 0}return{text:i,eol:`${a}${r}`,row:o}})}function serializeRow(e,t){let n=new Map(t.map((e,t)=>[e,t])),rankOf=e=>n.get(e)??t.length;return JSON.stringify(Object.fromEntries(Object.entries(e).toSorted(([e],[t])=>rankOf(e)-rankOf(t))))}async function loadSeedHook(e,t){let n=await d(e,t);if(!n)return;let i=(await import(r(n).href)).hook;if(typeof i!=`function`)throw Error(`${n} does not export \`hook\`. Run \`tailor generate\` to regenerate the seed schema files.`);return i}async function fillSeedData(e){let{path:t,fields:r=f}=e;if(r.length===0)throw Error(`No fields to fill. Name at least one field.`);let{dataDir:a,tableName:o}=await resolveSeedDataTarget(t),c=o?[o]:await listSeedTables(a),l=[],u=[],d=new Set,p=[];for(let e of c){let t=await loadSeedHook(a,e);if(!t){l.push(`No schema file for ${e}, so nothing can be filled in there`);continue}p.push({table:e,hook:t})}let m=[];for(let{table:e,hook:t}of p){let o=n(a,`${e}.jsonl`),s=splitLines(await i(o,`utf-8`)),c=new Set,f=[],p=0,h=[];for(let[e,n]of s.entries()){let i=n.row;if(!i){n.text.trim()!==``&&f.push(e+1);continue}let a=t(i);h=Object.keys(a);let o=r.filter(e=>!isBlank(ownValue(a,e))&&(d.add(e),isBlank(ownValue(i,e))));if(o.length!==0){for(let e of o)setField(i,e,a[e]),c.add(e);n.text=serializeRow(i,h),p+=1}}f.length>0&&l.push(`${o}: line(s) ${f.join(`, `)} are not JSON objects, so nothing was filled in there`),p!==0&&(m.push({file:o,content:s.map(e=>`${e.text}${e.eol}`).join(``)}),u.push({table:e,file:o,fields:[...c],count:p}))}for(let{file:e,content:t}of m)await s(e,t);let h=r.filter(e=>!d.has(e));c.length>0&&h.length>0&&l.push(`No seed data produces a value for: ${h.join(`, `)}`);let g=formatWarnings(l);return g.push(u.length===0?`✓ Nothing to fill`:u.map(({file:e,fields:t,count:n})=>`\u2713 ${e}: filled ${t.join(`, `)} in ${n} row(s)`).join(`
7
8
  `)),{output:g.join(`
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":[],"sources":["../../src/seed/index.ts"],"sourcesContent":["/**\n * Seed integration module for generated seed code.\n *\n * Re-exports `@toiroakr/lines-db` through a single import path\n * to avoid phantom dependency issues with pnpm, and provides\n * seed-specific utility functions used by the code generator.\n */\n\nimport { readdir, readFile, stat, writeFile } from \"node:fs/promises\";\nimport { pathToFileURL } from \"node:url\";\nimport { LinesDB, ErrorFormatter, findSchemaFile } from \"@toiroakr/lines-db\";\n// `pathe`, not `node:path`: the file paths reported back are printed and returned\n// to the caller, and these stay separator-stable across platforms.\nimport { basename, dirname, join } from \"pathe\";\nimport type { JsonObject, ValidationErrorDetail } from \"@toiroakr/lines-db\";\n\nexport { defineSchema } from \"@toiroakr/lines-db\";\nexport type { ForeignKeyDefinition, IndexDefinition } from \"@toiroakr/lines-db\";\n\n/** Fields `fillSeedData` writes when the caller names none. */\nconst DEFAULT_FILL_FIELDS = [\"id\"];\n\ntype SeedDataTarget = {\n dataDir: string;\n tableName?: string;\n};\n\ntype ValidateSeedDataOptions = {\n /** Resolved absolute path to a data directory or a .jsonl file */\n path: string;\n /** Show verbose error output */\n verbose?: boolean;\n};\n\ntype ValidateSeedResult =\n | { valid: true; output: string }\n | { valid: false; output: string; error: string };\n\n/**\n * A JSONL seed file that received values.\n */\ntype FilledSeedFile = {\n /** Name of the seeded table, matching the JSONL file name */\n table: string;\n /** Absolute path to the updated JSONL file */\n file: string;\n /** Fields that were written back to the file */\n fields: string[];\n /** How many rows were missing at least one of those fields */\n count: number;\n};\n\ntype FillSeedDataOptions = {\n /** Resolved absolute path to a data directory or a .jsonl file */\n path: string;\n /** Fields to fill. Defaults to `id`. */\n fields?: readonly string[];\n};\n\ntype FillSeedDataResult = {\n output: string;\n filled: FilledSeedFile[];\n};\n\nasync function resolveSeedDataTarget(resolvedPath: string): Promise<SeedDataTarget> {\n const stats = await stat(resolvedPath);\n if (stats.isDirectory()) {\n return { dataDir: resolvedPath };\n }\n if (stats.isFile() && resolvedPath.endsWith(\".jsonl\")) {\n return { dataDir: dirname(resolvedPath), tableName: basename(resolvedPath, \".jsonl\") };\n }\n throw new Error(`Invalid path: ${resolvedPath}. Must be a directory or .jsonl file.`);\n}\n\nasync function listSeedTables(dataDir: string): Promise<string[]> {\n const entries = await readdir(dataDir);\n return entries\n .filter((entry) => entry.endsWith(\".jsonl\"))\n .map((entry) => basename(entry, \".jsonl\"))\n .toSorted();\n}\n\nfunction formatWarnings(warnings: string[]): string[] {\n if (warnings.length === 0) {\n return [];\n }\n return [...warnings.map((warning) => `⚠ ${warning}`), \"\"];\n}\n\nfunction formatValidationErrors(errors: ValidationErrorDetail[], verbose: boolean): string {\n const formatter = new ErrorFormatter({ verbose });\n const errorLines: string[] = [];\n const errorsByFile = new Map<string, ValidationErrorDetail[]>();\n for (const error of errors) {\n const fileErrors = errorsByFile.get(error.file) || [];\n fileErrors.push(error);\n errorsByFile.set(error.file, fileErrors);\n }\n for (const [file, fileErrors] of errorsByFile) {\n errorLines.push(formatter.formatErrorHeader(fileErrors.length, file));\n errorLines.push(\"\");\n const validationErrors = fileErrors.filter(\n (e) => e.type !== \"foreignKey\" || !e.foreignKeyError,\n );\n const foreignKeyErrors = fileErrors.filter((e) => e.type === \"foreignKey\" && e.foreignKeyError);\n if (validationErrors.length > 0) {\n errorLines.push(\n formatter.formatValidationErrors(\n validationErrors.map((e) => ({\n file: e.file,\n rowIndex: e.rowIndex,\n issues: e.issues,\n })),\n ),\n );\n }\n for (const fkError of foreignKeyErrors) {\n if (fkError.foreignKeyError) {\n errorLines.push(\n formatter.formatForeignKeyError({\n file: fkError.file,\n rowIndex: fkError.rowIndex,\n column: fkError.foreignKeyError.column,\n value: fkError.foreignKeyError.value,\n referencedTable: fkError.foreignKeyError.referencedTable,\n referencedColumn: fkError.foreignKeyError.referencedColumn,\n }),\n );\n }\n }\n errorLines.push(\"\");\n }\n\n return errorLines.join(\"\\n\");\n}\n\n/**\n * Validate JSONL seed data against schema definitions.\n * Resolves the given path (directory or `.jsonl` file), validates the rows it\n * holds, and returns formatted output and error messages.\n * @param options - Validation options including path and verbose flag\n * @returns Validation result with output messages and optional error details\n */\nexport async function validateSeedData(\n options: ValidateSeedDataOptions,\n): Promise<ValidateSeedResult> {\n const { path: resolvedPath, verbose = false } = options;\n const { dataDir, tableName } = await resolveSeedDataTarget(resolvedPath);\n\n const db = LinesDB.create({ dataDir });\n let result;\n try {\n result = await db.initialize({ tableName, detailedValidate: true });\n } finally {\n await db.close();\n }\n\n const outputLines = formatWarnings(result.warnings);\n\n if (result.valid) {\n outputLines.push(\"✓ All records are valid\");\n return { valid: true, output: outputLines.join(\"\\n\") };\n }\n\n return {\n valid: false,\n output: outputLines.join(\"\\n\"),\n error: formatValidationErrors(result.errors, verbose),\n };\n}\n\n// A row's own value for a field, or undefined when the row has none.\nfunction ownValue(row: Record<string, unknown>, field: string): unknown {\n return Object.hasOwn(row, field) ? row[field] : undefined;\n}\n\n// Not `row[field] = value`: a field named `__proto__` goes through the inherited\n// setter, which leaves no own property for the serializer to read back.\nfunction setField(row: JsonObject, field: string, value: JsonObject[string]): void {\n Object.defineProperty(row, field, {\n value,\n enumerable: true,\n writable: true,\n configurable: true,\n });\n}\n\nfunction isBlank(value: unknown): boolean {\n if (value === undefined || value === null) {\n return true;\n }\n if (typeof value !== \"object\" || Array.isArray(value)) {\n return false;\n }\n // A nested field the row never had comes back as an object whose keys carry no\n // value of their own, and writing that into the line fills nothing in.\n return Object.values(value).every(isBlank);\n}\n\n/** A JSONL line, kept as text so an untouched line is written back verbatim. */\ntype SeedLine = {\n text: string;\n /** Line separator the file used after this line, kept so CRLF survives. */\n eol: string;\n row: JsonObject | undefined;\n};\n\nfunction splitLines(content: string): SeedLine[] {\n if (content === \"\") {\n return [];\n }\n return content.split(\"\\n\").map((raw, index, all) => {\n const eol = index === all.length - 1 ? \"\" : \"\\n\";\n const text = raw.endsWith(\"\\r\") ? raw.slice(0, -1) : raw;\n const carriage = raw.endsWith(\"\\r\") ? \"\\r\" : \"\";\n let row: JsonObject | undefined;\n if (text.trim() !== \"\") {\n try {\n const parsed: unknown = JSON.parse(text);\n row =\n parsed !== null && typeof parsed === \"object\" && !Array.isArray(parsed)\n ? (parsed as JsonObject)\n : undefined;\n } catch {\n row = undefined;\n }\n }\n return { text, eol: `${carriage}${eol}`, row };\n });\n}\n\n// Keys go in the order the hook produced them, which is the order the table\n// declares its fields. Keys the table does not declare follow the declared ones.\nfunction serializeRow(row: JsonObject, fieldOrder: string[]): string {\n const rank = new Map(fieldOrder.map((field, index) => [field, index]));\n const rankOf = (key: string): number => rank.get(key) ?? fieldOrder.length;\n return JSON.stringify(\n Object.fromEntries(Object.entries(row).toSorted(([a], [b]) => rankOf(a) - rankOf(b))),\n );\n}\n\ntype SeedHook = (row: unknown) => Record<string, unknown>;\n\nasync function loadSeedHook(dataDir: string, table: string): Promise<SeedHook | undefined> {\n const schemaPath = await findSchemaFile(dataDir, table);\n if (!schemaPath) {\n return undefined;\n }\n const loaded: unknown = await import(pathToFileURL(schemaPath).href);\n const hook = (loaded as { hook?: unknown }).hook;\n if (typeof hook !== \"function\") {\n throw new Error(\n `${schemaPath} does not export \\`hook\\`. Run \\`tailor generate\\` to regenerate the seed schema files.`,\n );\n }\n return hook as SeedHook;\n}\n\n/**\n * Fill in the values a record gets on create for the JSONL seed data rows that\n * are missing them, so a row can be referenced by `id` or carry a timestamp\n * before it is ever seeded.\n *\n * The values come from the table's own create-time behavior — its `id`, its field\n * defaults, and its create hooks — applied to each row on its own. Nothing is\n * validated, so a row can be filled while the data around it is still\n * incomplete: that is what lets you get the ids you need in order to write the\n * rows that reference them. Run `validateSeedData` when the data is ready.\n *\n * Only the named fields are written, and only into a row that has no value for\n * them, so a value already in the file is never replaced. A line that gains\n * nothing is written back exactly as it was, byte for byte; a line that does get\n * a value is re-serialized with its keys in the order the table declares its\n * fields, so a filled-in `id` lands at the front. A field the table gives no\n * value to — one it does not declare, or one the platform assigns such as a\n * serial field — is skipped, so one field list covers a whole data directory.\n *\n * The values are read from the schema files generated next to the data, and all\n * of them are read before anything is written: a file that predates the current\n * generator stops the run with nothing filled in anywhere.\n * @param options - Fill options including path and fields\n * @returns Which files received which fields\n */\nexport async function fillSeedData(options: FillSeedDataOptions): Promise<FillSeedDataResult> {\n const { path: resolvedPath, fields = DEFAULT_FILL_FIELDS } = options;\n if (fields.length === 0) {\n throw new Error(\"No fields to fill. Name at least one field.\");\n }\n const { dataDir, tableName } = await resolveSeedDataTarget(resolvedPath);\n const tables = tableName ? [tableName] : await listSeedTables(dataDir);\n\n const warnings: string[] = [];\n const filled: FilledSeedFile[] = [];\n const producedFields = new Set<string>();\n\n // Every hook loads before anything is written, so a schema file that predates\n // `tailor generate` stops the run instead of leaving half the files filled.\n const hooks: { table: string; hook: SeedHook }[] = [];\n for (const table of tables) {\n const hook = await loadSeedHook(dataDir, table);\n if (!hook) {\n warnings.push(`No schema file for ${table}, so nothing can be filled in there`);\n continue;\n }\n hooks.push({ table, hook });\n }\n\n // Every line is decided before any file is written, so a hook that throws on\n // one table cannot leave another one already rewritten.\n const writes: { file: string; content: string }[] = [];\n for (const { table, hook } of hooks) {\n const file = join(dataDir, `${table}.jsonl`);\n const lines = splitLines(await readFile(file, \"utf-8\"));\n\n const written = new Set<string>();\n const unreadable: number[] = [];\n let count = 0;\n let fieldOrder: string[] = [];\n for (const [index, line] of lines.entries()) {\n const row = line.row;\n if (!row) {\n if (line.text.trim() !== \"\") {\n unreadable.push(index + 1);\n }\n continue;\n }\n const hooked = hook(row);\n fieldOrder = Object.keys(hooked);\n const gained = fields.filter((field) => {\n const value = ownValue(hooked, field);\n if (isBlank(value)) {\n return false;\n }\n producedFields.add(field);\n return isBlank(ownValue(row, field));\n });\n if (gained.length === 0) {\n continue;\n }\n for (const field of gained) {\n setField(row, field, hooked[field] as JsonObject[string]);\n written.add(field);\n }\n line.text = serializeRow(row, fieldOrder);\n count += 1;\n }\n\n if (unreadable.length > 0) {\n warnings.push(\n `${file}: line(s) ${unreadable.join(\", \")} are not JSON objects, so nothing was filled in there`,\n );\n }\n\n if (count === 0) {\n continue;\n }\n writes.push({ file, content: lines.map((line) => `${line.text}${line.eol}`).join(\"\") });\n filled.push({ table, file, fields: [...written], count });\n }\n\n for (const { file, content } of writes) {\n await writeFile(file, content);\n }\n\n const unproducedFields = fields.filter((field) => !producedFields.has(field));\n if (tables.length > 0 && unproducedFields.length > 0) {\n warnings.push(`No seed data produces a value for: ${unproducedFields.join(\", \")}`);\n }\n\n const outputLines = formatWarnings(warnings);\n outputLines.push(\n filled.length === 0\n ? \"\\u2713 Nothing to fill\"\n : filled\n .map(\n ({ file, fields: tableFields, count }) =>\n `\\u2713 ${file}: filled ${tableFields.join(\", \")} in ${count} row(s)`,\n )\n .join(\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,EAEnB,EAAK,KAAO,aAAa,EAAK,CAAU,EACxC,GAAS,CAFT,CAGF,CAEI,EAAW,OAAS,GACtB,EAAS,KACP,GAAG,EAAK,YAAY,EAAW,KAAK,IAAI,EAAE,sDAC5C,EAGE,IAAU,IAGd,EAAO,KAAK,CAAE,OAAM,QAAS,EAAM,IAAK,GAAS,GAAG,EAAK,OAAO,EAAK,KAAK,CAAC,CAAC,KAAK,EAAE,CAAE,CAAC,EACtF,EAAO,KAAK,CAAE,QAAO,OAAM,OAAQ,CAAC,GAAG,CAAO,EAAG,OAAM,CAAC,EAC1D,CAEA,IAAK,GAAM,CAAE,OAAM,aAAa,EAC9B,MAAM,EAAU,EAAM,CAAO,EAG/B,IAAM,EAAmB,EAAO,OAAQ,GAAU,CAAC,EAAe,IAAI,CAAK,CAAC,EACxE,EAAO,OAAS,GAAK,EAAiB,OAAS,GACjD,EAAS,KAAK,sCAAsC,EAAiB,KAAK,IAAI,GAAG,EAGnF,IAAM,EAAc,eAAe,CAAQ,EAY3C,OAXA,EAAY,KACV,EAAO,SAAW,EACd,oBACA,EACG,KACE,CAAE,OAAM,OAAQ,EAAa,WAC5B,UAAU,EAAK,WAAW,EAAY,KAAK,IAAI,EAAE,MAAM,EAAM,QACjE,CAAC,CACA,KAAK;CAAI,CAClB,EAEO,CAAE,OAAQ,EAAY,KAAK;CAAI,EAAG,QAAO,CAClD"}
1
+ {"version":3,"file":"index.mjs","names":[],"sources":["../../src/seed/record-lines.ts","../../src/seed/index.ts"],"sourcesContent":["import { readFile } from \"node:fs/promises\";\nimport type { ValidationErrorDetail } from \"@toiroakr/lines-db\";\n\n/**\n * Resolve the 1-based physical line a JSONL record occupies.\n *\n * The seed reader drops blank and whitespace-only lines before indexing its\n * records, so a record's index is not its line number once a file contains\n * one. Reported locations have to point at the line a reader would open.\n * @param content - Raw JSONL file contents\n * @param recordIndex - 0-based index among the file's non-blank lines\n * @returns 1-based physical line, or undefined when the file holds no such record\n */\nexport function physicalLineOfRecord(content: string, recordIndex: number): number | undefined {\n const lines = content.split(\"\\n\");\n let remaining = recordIndex;\n for (const [index, line] of lines.entries()) {\n if (line.trim().length === 0) continue;\n if (remaining === 0) return index + 1;\n remaining -= 1;\n }\n return undefined;\n}\n\n/**\n * Locate the first reported error in its own file.\n *\n * Errors are reported per record, so the index is mapped back to a physical\n * line; a file that cannot be re-read yields the file alone rather than a\n * guessed line.\n * @param errors - Validation errors in the order the validator reported them\n * @returns Location of the first error, or undefined when there is none\n */\nexport async function firstErrorLocation(\n errors: readonly ValidationErrorDetail[],\n): Promise<{ file: string; line?: number } | undefined> {\n const first = errors[0];\n if (!first) return undefined;\n try {\n const content = await readFile(first.file, \"utf-8\");\n return { file: first.file, line: physicalLineOfRecord(content, first.rowIndex) };\n } catch {\n return { file: first.file };\n }\n}\n","/**\n * Seed integration module for generated seed code.\n *\n * Re-exports `@toiroakr/lines-db` through a single import path\n * to avoid phantom dependency issues with pnpm, and provides\n * seed-specific utility functions used by the code generator.\n */\n\nimport { readdir, readFile, stat, writeFile } from \"node:fs/promises\";\nimport { pathToFileURL } from \"node:url\";\nimport { LinesDB, ErrorFormatter, findSchemaFile } from \"@toiroakr/lines-db\";\n// `pathe`, not `node:path`: the file paths reported back are printed and returned\n// to the caller, and these stay separator-stable across platforms.\nimport { basename, dirname, join } from \"pathe\";\nimport { firstErrorLocation } from \"./record-lines\";\nimport type { JsonObject, ValidationErrorDetail } from \"@toiroakr/lines-db\";\n\nexport { defineSchema } from \"@toiroakr/lines-db\";\nexport type { ForeignKeyDefinition, IndexDefinition } from \"@toiroakr/lines-db\";\n\n/** Fields `fillSeedData` writes when the caller names none. */\nconst DEFAULT_FILL_FIELDS = [\"id\"];\n\ntype SeedDataTarget = {\n dataDir: string;\n tableName?: string;\n};\n\ntype ValidateSeedDataOptions = {\n /** Resolved absolute path to a data directory or a .jsonl file */\n path: string;\n /** Show verbose error output */\n verbose?: boolean;\n};\n\ntype ValidateSeedResult =\n | { valid: true; output: string }\n | {\n valid: false;\n output: string;\n error: string;\n /** Where the first reported error sits, for tooling that links to source. */\n location?: { file: string; line?: number };\n };\n\n/**\n * A JSONL seed file that received values.\n */\ntype FilledSeedFile = {\n /** Name of the seeded table, matching the JSONL file name */\n table: string;\n /** Absolute path to the updated JSONL file */\n file: string;\n /** Fields that were written back to the file */\n fields: string[];\n /** How many rows were missing at least one of those fields */\n count: number;\n};\n\ntype FillSeedDataOptions = {\n /** Resolved absolute path to a data directory or a .jsonl file */\n path: string;\n /** Fields to fill. Defaults to `id`. */\n fields?: readonly string[];\n};\n\ntype FillSeedDataResult = {\n output: string;\n filled: FilledSeedFile[];\n};\n\nasync function resolveSeedDataTarget(resolvedPath: string): Promise<SeedDataTarget> {\n const stats = await stat(resolvedPath);\n if (stats.isDirectory()) {\n return { dataDir: resolvedPath };\n }\n if (stats.isFile() && resolvedPath.endsWith(\".jsonl\")) {\n return { dataDir: dirname(resolvedPath), tableName: basename(resolvedPath, \".jsonl\") };\n }\n throw new Error(`Invalid path: ${resolvedPath}. Must be a directory or .jsonl file.`);\n}\n\nasync function listSeedTables(dataDir: string): Promise<string[]> {\n const entries = await readdir(dataDir);\n return entries\n .filter((entry) => entry.endsWith(\".jsonl\"))\n .map((entry) => basename(entry, \".jsonl\"))\n .toSorted();\n}\n\nfunction formatWarnings(warnings: string[]): string[] {\n if (warnings.length === 0) {\n return [];\n }\n return [...warnings.map((warning) => `⚠ ${warning}`), \"\"];\n}\n\nfunction formatValidationErrors(errors: ValidationErrorDetail[], verbose: boolean): string {\n const formatter = new ErrorFormatter({ verbose });\n const errorLines: string[] = [];\n const errorsByFile = new Map<string, ValidationErrorDetail[]>();\n for (const error of errors) {\n const fileErrors = errorsByFile.get(error.file) || [];\n fileErrors.push(error);\n errorsByFile.set(error.file, fileErrors);\n }\n for (const [file, fileErrors] of errorsByFile) {\n errorLines.push(formatter.formatErrorHeader(fileErrors.length, file));\n errorLines.push(\"\");\n const validationErrors = fileErrors.filter(\n (e) => e.type !== \"foreignKey\" || !e.foreignKeyError,\n );\n const foreignKeyErrors = fileErrors.filter((e) => e.type === \"foreignKey\" && e.foreignKeyError);\n if (validationErrors.length > 0) {\n errorLines.push(\n formatter.formatValidationErrors(\n validationErrors.map((e) => ({\n file: e.file,\n rowIndex: e.rowIndex,\n issues: e.issues,\n })),\n ),\n );\n }\n for (const fkError of foreignKeyErrors) {\n if (fkError.foreignKeyError) {\n errorLines.push(\n formatter.formatForeignKeyError({\n file: fkError.file,\n rowIndex: fkError.rowIndex,\n column: fkError.foreignKeyError.column,\n value: fkError.foreignKeyError.value,\n referencedTable: fkError.foreignKeyError.referencedTable,\n referencedColumn: fkError.foreignKeyError.referencedColumn,\n }),\n );\n }\n }\n errorLines.push(\"\");\n }\n\n return errorLines.join(\"\\n\");\n}\n\n/**\n * Validate JSONL seed data against schema definitions.\n * Resolves the given path (directory or `.jsonl` file), validates the rows it\n * holds, and returns formatted output and error messages.\n * @param options - Validation options including path and verbose flag\n * @returns Validation result with output messages and optional error details\n */\nexport async function validateSeedData(\n options: ValidateSeedDataOptions,\n): Promise<ValidateSeedResult> {\n const { path: resolvedPath, verbose = false } = options;\n const { dataDir, tableName } = await resolveSeedDataTarget(resolvedPath);\n\n const db = LinesDB.create({ dataDir });\n let result;\n try {\n result = await db.initialize({ tableName, detailedValidate: true });\n } finally {\n await db.close();\n }\n\n const outputLines = formatWarnings(result.warnings);\n\n if (result.valid) {\n outputLines.push(\"✓ All records are valid\");\n return { valid: true, output: outputLines.join(\"\\n\") };\n }\n\n return {\n valid: false,\n output: outputLines.join(\"\\n\"),\n error: formatValidationErrors(result.errors, verbose),\n location: await firstErrorLocation(result.errors),\n };\n}\n\n// A row's own value for a field, or undefined when the row has none.\nfunction ownValue(row: Record<string, unknown>, field: string): unknown {\n return Object.hasOwn(row, field) ? row[field] : undefined;\n}\n\n// Not `row[field] = value`: a field named `__proto__` goes through the inherited\n// setter, which leaves no own property for the serializer to read back.\nfunction setField(row: JsonObject, field: string, value: JsonObject[string]): void {\n Object.defineProperty(row, field, {\n value,\n enumerable: true,\n writable: true,\n configurable: true,\n });\n}\n\nfunction isBlank(value: unknown): boolean {\n if (value === undefined || value === null) {\n return true;\n }\n if (typeof value !== \"object\" || Array.isArray(value)) {\n return false;\n }\n // A nested field the row never had comes back as an object whose keys carry no\n // value of their own, and writing that into the line fills nothing in.\n return Object.values(value).every(isBlank);\n}\n\n/** A JSONL line, kept as text so an untouched line is written back verbatim. */\ntype SeedLine = {\n text: string;\n /** Line separator the file used after this line, kept so CRLF survives. */\n eol: string;\n row: JsonObject | undefined;\n};\n\nfunction splitLines(content: string): SeedLine[] {\n if (content === \"\") {\n return [];\n }\n return content.split(\"\\n\").map((raw, index, all) => {\n const eol = index === all.length - 1 ? \"\" : \"\\n\";\n const text = raw.endsWith(\"\\r\") ? raw.slice(0, -1) : raw;\n const carriage = raw.endsWith(\"\\r\") ? \"\\r\" : \"\";\n let row: JsonObject | undefined;\n if (text.trim() !== \"\") {\n try {\n const parsed: unknown = JSON.parse(text);\n row =\n parsed !== null && typeof parsed === \"object\" && !Array.isArray(parsed)\n ? (parsed as JsonObject)\n : undefined;\n } catch {\n row = undefined;\n }\n }\n return { text, eol: `${carriage}${eol}`, row };\n });\n}\n\n// Keys go in the order the hook produced them, which is the order the table\n// declares its fields. Keys the table does not declare follow the declared ones.\nfunction serializeRow(row: JsonObject, fieldOrder: string[]): string {\n const rank = new Map(fieldOrder.map((field, index) => [field, index]));\n const rankOf = (key: string): number => rank.get(key) ?? fieldOrder.length;\n return JSON.stringify(\n Object.fromEntries(Object.entries(row).toSorted(([a], [b]) => rankOf(a) - rankOf(b))),\n );\n}\n\ntype SeedHook = (row: unknown) => Record<string, unknown>;\n\nasync function loadSeedHook(dataDir: string, table: string): Promise<SeedHook | undefined> {\n const schemaPath = await findSchemaFile(dataDir, table);\n if (!schemaPath) {\n return undefined;\n }\n const loaded: unknown = await import(pathToFileURL(schemaPath).href);\n const hook = (loaded as { hook?: unknown }).hook;\n if (typeof hook !== \"function\") {\n throw new Error(\n `${schemaPath} does not export \\`hook\\`. Run \\`tailor generate\\` to regenerate the seed schema files.`,\n );\n }\n return hook as SeedHook;\n}\n\n/**\n * Fill in the values a record gets on create for the JSONL seed data rows that\n * are missing them, so a row can be referenced by `id` or carry a timestamp\n * before it is ever seeded.\n *\n * The values come from the table's own create-time behavior — its `id`, its field\n * defaults, and its create hooks — applied to each row on its own. Nothing is\n * validated, so a row can be filled while the data around it is still\n * incomplete: that is what lets you get the ids you need in order to write the\n * rows that reference them. Run `validateSeedData` when the data is ready.\n *\n * Only the named fields are written, and only into a row that has no value for\n * them, so a value already in the file is never replaced. A line that gains\n * nothing is written back exactly as it was, byte for byte; a line that does get\n * a value is re-serialized with its keys in the order the table declares its\n * fields, so a filled-in `id` lands at the front. A field the table gives no\n * value to — one it does not declare, or one the platform assigns such as a\n * serial field — is skipped, so one field list covers a whole data directory.\n *\n * The values are read from the schema files generated next to the data, and all\n * of them are read before anything is written: a file that predates the current\n * generator stops the run with nothing filled in anywhere.\n * @param options - Fill options including path and fields\n * @returns Which files received which fields\n */\nexport async function fillSeedData(options: FillSeedDataOptions): Promise<FillSeedDataResult> {\n const { path: resolvedPath, fields = DEFAULT_FILL_FIELDS } = options;\n if (fields.length === 0) {\n throw new Error(\"No fields to fill. Name at least one field.\");\n }\n const { dataDir, tableName } = await resolveSeedDataTarget(resolvedPath);\n const tables = tableName ? [tableName] : await listSeedTables(dataDir);\n\n const warnings: string[] = [];\n const filled: FilledSeedFile[] = [];\n const producedFields = new Set<string>();\n\n // Every hook loads before anything is written, so a schema file that predates\n // `tailor generate` stops the run instead of leaving half the files filled.\n const hooks: { table: string; hook: SeedHook }[] = [];\n for (const table of tables) {\n const hook = await loadSeedHook(dataDir, table);\n if (!hook) {\n warnings.push(`No schema file for ${table}, so nothing can be filled in there`);\n continue;\n }\n hooks.push({ table, hook });\n }\n\n // Every line is decided before any file is written, so a hook that throws on\n // one table cannot leave another one already rewritten.\n const writes: { file: string; content: string }[] = [];\n for (const { table, hook } of hooks) {\n const file = join(dataDir, `${table}.jsonl`);\n const lines = splitLines(await readFile(file, \"utf-8\"));\n\n const written = new Set<string>();\n const unreadable: number[] = [];\n let count = 0;\n let fieldOrder: string[] = [];\n for (const [index, line] of lines.entries()) {\n const row = line.row;\n if (!row) {\n if (line.text.trim() !== \"\") {\n unreadable.push(index + 1);\n }\n continue;\n }\n const hooked = hook(row);\n fieldOrder = Object.keys(hooked);\n const gained = fields.filter((field) => {\n const value = ownValue(hooked, field);\n if (isBlank(value)) {\n return false;\n }\n producedFields.add(field);\n return isBlank(ownValue(row, field));\n });\n if (gained.length === 0) {\n continue;\n }\n for (const field of gained) {\n setField(row, field, hooked[field] as JsonObject[string]);\n written.add(field);\n }\n line.text = serializeRow(row, fieldOrder);\n count += 1;\n }\n\n if (unreadable.length > 0) {\n warnings.push(\n `${file}: line(s) ${unreadable.join(\", \")} are not JSON objects, so nothing was filled in there`,\n );\n }\n\n if (count === 0) {\n continue;\n }\n writes.push({ file, content: lines.map((line) => `${line.text}${line.eol}`).join(\"\") });\n filled.push({ table, file, fields: [...written], count });\n }\n\n for (const { file, content } of writes) {\n await writeFile(file, content);\n }\n\n const unproducedFields = fields.filter((field) => !producedFields.has(field));\n if (tables.length > 0 && unproducedFields.length > 0) {\n warnings.push(`No seed data produces a value for: ${unproducedFields.join(\", \")}`);\n }\n\n const outputLines = formatWarnings(warnings);\n outputLines.push(\n filled.length === 0\n ? \"\\u2713 Nothing to fill\"\n : filled\n .map(\n ({ file, fields: tableFields, count }) =>\n `\\u2713 ${file}: filled ${tableFields.join(\", \")} in ${count} row(s)`,\n )\n .join(\"\\n\"),\n );\n\n return { output: outputLines.join(\"\\n\"), filled };\n}\n"],"mappings":"0RAaA,SAAgB,qBAAqB,EAAiB,EAAyC,CAC7F,IAAM,EAAQ,EAAQ,MAAM;CAAI,EAC5B,EAAY,EAChB,IAAK,GAAM,CAAC,EAAO,KAAS,EAAM,QAAQ,EACpC,KAAK,KAAK,C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flows that already echo their own `::error::` around the CLI keep working;
96
96
  those messages describe the workflow's own checks, which can fail even when the CLI succeeds.
97
97
 
98
- Annotations do not yet carry `file=`/`line=` source locations, and `generate` and `deploy` do not
99
- group their per-service progress.
98
+ When the failure has a known source, the annotation carries it: `seed validate` reports the
99
+ offending JSONL file and line, and a rejected config reports its file — or, when the config or a
100
+ file it imports cannot be parsed, that file and the line it failed on. Locations are written
101
+ relative to `GITHUB_WORKSPACE`; a file outside it is annotated without a location rather than with
102
+ a path the runner cannot resolve.
103
+
104
+ For a JSONL file containing a blank line, the annotation's line and the line printed in the report
105
+ text differ: the annotation counts every line in the file, while the printed line counts only the
106
+ records. The annotation points at the row as an editor numbers it.
107
+
108
+ `generate` and `deploy` do not group their per-service progress.
100
109
 
101
110
  ## Common Options
102
111
 
@@ -284,8 +284,12 @@ export default defineConfig({
284
284
 
285
285
  Migration files are versioned independently of the SDK package. This SDK writes format version `6` and reads versions `1` through `6`. It normalizes supported older formats in memory; it never rewrites applied migration files on disk. Format version `6` records renames of members inside nested fields (`memberRenames`); older SDK versions refuse to read it rather than deploying such a migration without the copy step.
286
286
 
287
+ Supported histories also preserve the behavior of field hooks and validators saved by older SDKs, including access to the record and boolean validators with a separate error message. Legacy update hooks retain existing values for omitted fields; explicitly supplied values, including `null`, take precedence. This applies to both snapshots and diffs, including nested fields. Your existing migration files can remain as generated.
288
+
287
289
  If a future SDK can no longer replay an old migration format, re-baseline while using an SDK version that still supports the complete history, commit the new baseline, deploy it to every environment, and then upgrade the SDK. A file from a newer unsupported format instead requires upgrading the SDK first. The CLI rejects both cases with guidance rather than attempting a best-effort replay.
288
290
 
291
+ The SDK used for this transition must read the old history and write a baseline format that the target SDK accepts. Keep that SDK version pinned until every environment has adopted the new baseline. File-format support does not guarantee compatibility for arbitrary imports in a custom `migrate.ts`; keep its dependencies pinned and test customized scripts when upgrading.
292
+
289
293
  There is no migration-file conversion command. Keeping applied files unchanged preserves the record of what ran, while `migration rebaseline` provides the escape hatch when the supported replay window changes.
290
294
 
291
295
  ## Migration Script Anatomy
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tailor-platform/sdk",
3
- "version": "2.17.0",
3
+ "version": "2.18.0",
4
4
  "description": "Tailor Platform SDK - The SDK to work with Tailor Platform",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -151,7 +151,7 @@
151
151
  "dependencies": {
152
152
  "@0no-co/graphql.web": "1.3.4",
153
153
  "@badgateway/oauth2-client": "3.3.1",
154
- "@bufbuild/protobuf": "2.14.1",
154
+ "@bufbuild/protobuf": "2.15.0",
155
155
  "@bufbuild/protovalidate": "1.2.0",
156
156
  "@connectrpc/connect": "2.2.0",
157
157
  "@connectrpc/connect-node": "2.2.0",
@@ -164,7 +164,7 @@
164
164
  "@opentelemetry/resources": "2.11.0",
165
165
  "@opentelemetry/sdk-trace-node": "2.11.0",
166
166
  "@opentelemetry/semantic-conventions": "1.43.0",
167
- "@oxc-project/types": "0.148.0",
167
+ "@oxc-project/types": "0.149.0",
168
168
  "@politty/zod": "0.2.1",
169
169
  "@secretlint/core": "13.0.5",
170
170
  "@secretlint/secretlint-rule-preset-recommend": "13.0.5",
@@ -185,20 +185,20 @@
185
185
  "inflection": "3.0.2",
186
186
  "kysely": "0.29.5",
187
187
  "mime-types": "3.0.2",
188
- "open": "11.0.2",
189
- "oxc-parser": "0.148.0",
188
+ "open": "11.0.3",
189
+ "oxc-parser": "0.149.0",
190
190
  "p-limit": "7.3.2",
191
191
  "pathe": "2.0.3",
192
192
  "pgsql-ast-parser": "12.0.2",
193
193
  "pkg-types": "2.3.3",
194
- "rolldown": "1.2.7",
194
+ "rolldown": "1.2.8",
195
195
  "semver": "7.8.5",
196
196
  "sql-highlight": "6.1.0",
197
197
  "std-env": "4.2.0",
198
198
  "ts-cron-validator": "1.1.5",
199
199
  "type-fest": "5.9.0",
200
200
  "xdg-basedir": "5.1.0",
201
- "zod": "4.5.4"
201
+ "zod": "4.6.4"
202
202
  },
203
203
  "devDependencies": {
204
204
  "@electric-sql/pglite": "0.5.8",
@@ -211,8 +211,8 @@
211
211
  "@typescript/native-preview": "7.0.0-dev.20260707.2",
212
212
  "@vitest/coverage-v8": "5.0.0",
213
213
  "eslint-plugin-zod": "4.12.1",
214
- "oxfmt": "0.66.0",
215
- "oxlint": "1.81.0",
214
+ "oxfmt": "0.67.0",
215
+ "oxlint": "1.82.0",
216
216
  "oxlint-tsgolint": "7.0.2001",
217
217
  "sonda": "0.14.0",
218
218
  "tsdown": "0.23.0",