@tldraw/tlschema
Version:
tldraw infinite canvas SDK (schema).
8 lines (7 loc) • 1.64 kB
Source Map (JSON)
{
"version": 3,
"sources": ["../../src/misc/id-validator.ts"],
"sourcesContent": ["import type { RecordId, UnknownRecord } from '@tldraw/store'\nimport { T } from '@tldraw/validate'\n\n/**\n * Creates a validator for typed record IDs that ensures they follow the correct\n * format with the specified prefix. Record IDs in tldraw follow the pattern\n * \"prefix:identifier\" where the prefix indicates the record type.\n *\n * @param prefix - The required prefix for the ID (e.g., 'shape', 'page', 'asset')\n * @returns A validator that checks the ID format and returns the typed ID\n * @public\n * @example\n * ```ts\n * const shapeIdValidator = idValidator<TLShapeId>('shape')\n * const validId = shapeIdValidator.validate('shape:abc123') // Returns 'shape:abc123' as TLShapeId\n *\n * const pageIdValidator = idValidator<TLPageId>('page')\n * const pageId = pageIdValidator.validate('page:main') // Returns 'page:main' as TLPageId\n *\n * // This would throw an error:\n * // shapeIdValidator.validate('page:abc123') // Error: shape ID must start with \"shape:\"\n * ```\n */\nexport function idValidator<Id extends RecordId<UnknownRecord>>(\n\tprefix: Id['__type__']['typeName']\n): T.Validator<Id> {\n\treturn T.string.refine((id) => {\n\t\tif (!id.startsWith(`${prefix}:`)) {\n\t\t\tthrow new Error(`${prefix} ID must start with \"${prefix}:\"`)\n\t\t}\n\t\treturn id as Id\n\t})\n}\n"],
"mappings": "AACA,SAAS,SAAS;AAsBX,SAAS,YACf,QACkB;AAClB,SAAO,EAAE,OAAO,OAAO,CAAC,OAAO;AAC9B,QAAI,CAAC,GAAG,WAAW,GAAG,MAAM,GAAG,GAAG;AACjC,YAAM,IAAI,MAAM,GAAG,MAAM,wBAAwB,MAAM,IAAI;AAAA,IAC5D;AACA,WAAO;AAAA,EACR,CAAC;AACF;",
"names": []
}