@instantdb/platform 0.22.95-experimental.surgical.20386947966.1 → 0.22.96-experimental.add-posthog-frontend.20386914944.1

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.
@@ -1,10 +1,16 @@
1
- import { indentLines, joinWithTrailingSep, sortedEntries, } from "./util.js";
2
- import { formatKey, renderEntityProperty, renderLinksObject, } from "./schemaCodegen.js";
1
+ import { indentLines, joinWithTrailingSep, sortedEntries, formatKey, } from "./util.js";
2
+ function attrDefToCodeString([name, attr]) {
3
+ var _a;
4
+ const type = ((_a = attr.metadata.derivedType) === null || _a === void 0 ? void 0 : _a.type) || attr.valueType || 'any';
5
+ const unique = attr.config.unique ? '.unique()' : '';
6
+ const index = attr.config.indexed ? '.indexed()' : '';
7
+ const required = attr.required ? '' : '.optional()';
8
+ return `${formatKey(name)}: i.${type}()${unique}${index}${required}`;
9
+ }
3
10
  function entityDefToCodeStr(name, edef) {
4
- return renderEntityProperty(name, edef.attrs, {
5
- keyOptions: { alwaysQuote: true, quote: '"' },
6
- trailingComma: true,
7
- });
11
+ const attrBlock = joinWithTrailingSep(sortedEntries(edef.attrs).map(attrDefToCodeString), ',\n', ',');
12
+ // a block of code for each entity
13
+ return `${formatKey(name)}: i.entity({${attrBlock.length ? '\n' : ''}${indentLines(attrBlock, 2)}${attrBlock.length ? '\n' : ''}})`;
8
14
  }
9
15
  export function identEtype(ident) {
10
16
  return ident[1];
@@ -48,7 +54,7 @@ function roomDefToCodeStr(room) {
48
54
  ret += `\n${indentLines(entityDefToCodeStr('presence', room.presence), 4)},`;
49
55
  }
50
56
  if (room.topics) {
51
- ret += `\n ${formatKey('topics', { alwaysQuote: true, quote: '"' })}: {`;
57
+ ret += `\n "topics": {`;
52
58
  for (const [topicName, topicConfig] of Object.entries(room.topics)) {
53
59
  ret += `\n${indentLines(entityDefToCodeStr(topicName, topicConfig), 6)},`;
54
60
  }
@@ -60,7 +66,7 @@ function roomDefToCodeStr(room) {
60
66
  function roomsCodeStr(rooms) {
61
67
  let ret = '{';
62
68
  for (const [roomType, roomDef] of Object.entries(rooms)) {
63
- ret += `\n ${formatKey(roomType, { alwaysQuote: true, quote: '"' })}: ${roomDefToCodeStr(roomDef)},`;
69
+ ret += `\n ${formatKey(roomType)}: ${roomDefToCodeStr(roomDef)},`;
64
70
  }
65
71
  ret += ret === '{' ? '}' : '\n}';
66
72
  return ret;
@@ -83,11 +89,7 @@ export function generateSchemaTypescriptFile(prevSchema, newSchema, instantModul
83
89
  // Take a look at this schema, and if everything looks good,
84
90
  // run \`push schema\` again to enforce the types.`
85
91
  : '';
86
- const linksEntriesCode = renderLinksObject(newSchema.links, {
87
- keyOptions: { alwaysQuote: true, quote: '"' },
88
- stringQuote: '"',
89
- style: 'json',
90
- });
92
+ const linksEntriesCode = JSON.stringify(newSchema.links, null, 2).trim();
91
93
  // rooms
92
94
  const rooms = (prevSchema === null || prevSchema === void 0 ? void 0 : prevSchema.rooms) || {};
93
95
  const roomsCode = roomsCodeStr(rooms);
@@ -1 +1 @@
1
- {"version":3,"file":"schema.js","sourceRoot":"","sources":["../../src/schema.ts"],"names":[],"mappings":"AAaA,OAAO,EACL,WAAW,EACX,mBAAmB,EACnB,aAAa,GAEd,MAAM,WAAW,CAAC;AACnB,OAAO,EACL,SAAS,EACT,oBAAoB,EACpB,iBAAiB,GAClB,MAAM,oBAAoB,CAAC;AAiP5B,SAAS,kBAAkB,CACzB,IAAY,EACZ,IAIC;IAED,OAAO,oBAAoB,CAAC,IAAI,EAAE,IAAI,CAAC,KAAK,EAAE;QAC5C,UAAU,EAAE,EAAE,WAAW,EAAE,IAAI,EAAE,KAAK,EAAE,GAAG,EAAE;QAC7C,aAAa,EAAE,IAAI;KACpB,CAAC,CAAC;AACL,CAAC;AAED,MAAM,UAAU,UAAU,CAAC,KAAqB;IAC9C,OAAO,KAAK,CAAC,CAAC,CAAC,CAAC;AAClB,CAAC;AAED,MAAM,UAAU,UAAU,CAAC,KAAq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\n CardinalityKind,\n DataAttrDef,\n EntityDef,\n InstantDBAttr,\n InstantDBCheckedDataType,\n InstantDBIdent,\n InstantSchemaDef,\n LinkAttrDef,\n RoomsDef,\n} from '@instantdb/core';\n\nimport {\n indentLines,\n joinWithTrailingSep,\n sortedEntries,\n GenericSchemaDef,\n} from './util.ts';\nimport {\n formatKey,\n renderEntityProperty,\n renderLinksObject,\n} from './schemaCodegen.ts';\n\nexport type InstantAPIPlatformSchema = {\n refs: Record<string, InstantDBAttr>;\n blobs: Record<string, Record<string, InstantDBAttr>>;\n};\n\nexport type InstantAPISchemaPlanAddAttrStep = {\n type: 'add-attr';\n friendlyDescription: string;\n attr: InstantDBAttr;\n};\n\nexport type InstantAPISchemaPlanDeleteAttrStep = {\n type: 'delete-attr';\n friendlyDescription: string;\n attrId: string;\n};\n\nexport type InstantAPISchemaPlanUpdateAttrStep = {\n type: 'update-attr';\n friendlyDescription: string;\n attr: InstantDBAttr;\n};\n\nexport type InstantAPISchemaPlanIndexStep = {\n type: 'index';\n friendlyDescription: string;\n attrId: string;\n forwardIdentity: InstantDBIdent;\n};\n\nexport type InstantAPISchemaPlanRemoveIndexStep = {\n type: 'remove-index';\n friendlyDescription: string;\n attrId: string;\n forwardIdentity: InstantDBIdent;\n};\n\nexport type InstantAPISchemaPlanUniqueStep = {\n type: 'unique';\n friendlyDescription: string;\n attrId: string;\n forwardIdentity: InstantDBIdent;\n};\n\nexport type InstantAPISchemaPlanRemoveUniqueStep = {\n type: 'remove-unique';\n friendlyDescription: string;\n attrId: string;\n forwardIdentity: InstantDBIdent;\n};\n\nexport type InstantAPISchemaPlanRequiredStep = {\n type: 'required';\n friendlyDescription: string;\n attrId: string;\n forwardIdentity: InstantDBIdent;\n};\n\nexport type InstantAPISchemaPlanRemoveRequiredStep = {\n type: 'remove-required';\n friendlyDescription: string;\n attrId: string;\n forwardIdentity: InstantDBIdent;\n};\n\nexport type InstantAPISchemaPlanCheckDataTypeStep = {\n type: 'check-data-type';\n friendlyDescription: string;\n attrId: string;\n forwardIdentity: InstantDBIdent;\n checkedDataType: InstantDBCheckedDataType;\n};\n\nexport type InstantAPISchemaPlanRemoveDataTypeStep = {\n type: 'remove-data-type';\n friendlyDescription: string;\n attrId: string;\n forwardIdentity: InstantDBIdent;\n};\n\ntype InstantBackgroundSchemaBaseJob = {\n id: string;\n createdAt: Date;\n updatedAt: Date;\n status: 'completed' | 'waiting' | 'processing' | 'errored';\n workEstimate: number | null;\n workCompleted: number | null;\n error?:\n | 'invalid-triple-error'\n | 'invalid-attr-state-error'\n | 'triple-not-unique-error'\n | 'triple-too-large-error'\n | 'missing-required-error'\n | 'unexpected-error';\n invalidTriplesSample?: {\n entityId: string;\n value: any;\n jsonType:\n | 'string'\n | 'number'\n | 'boolean'\n | 'null'\n | 'object'\n | 'array'\n | 'date';\n }[];\n};\n\ntype InstantBackgroundSchemaBaseJobWithInvalidTriples =\n InstantBackgroundSchemaBaseJob & {\n invalidTriplesSample?: {\n entityId: string;\n value: any;\n jsonType:\n | 'string'\n | 'number'\n | 'boolean'\n | 'null'\n | 'object'\n | 'array'\n | 'date';\n }[];\n };\n\nexport interface InstantBackgroundSchemaRemoveDataTypeJob\n extends InstantBackgroundSchemaBaseJob {\n type: 'remove-data-type';\n}\n\nexport interface InstantBackgroundSchemaCheckDataTypeJob\n extends InstantBackgroundSchemaBaseJobWithInvalidTriples {\n type: 'check-data-type';\n checkedDataType: InstantDBCheckedDataType;\n}\n\nexport interface InstantBackgroundSchemaAddIndexJob\n extends InstantBackgroundSchemaBaseJobWithInvalidTriples {\n type: 'index';\n}\n\nexport interface InstantBackgroundSchemaRemoveIndexJob\n extends InstantBackgroundSchemaBaseJob {\n type: 'remove-index';\n}\n\nexport interface InstantBackgroundSchemaAddUniqueJob\n extends InstantBackgroundSchemaBaseJobWithInvalidTriples {\n type: 'unique';\n invalidUniqueValue?: any;\n}\n\nexport interface InstantBackgroundSchemaRemoveUniqueJob\n extends InstantBackgroundSchemaBaseJob {\n type: 'remove-unique';\n}\n\nexport interface InstantBackgroundSchemaAddRequiredJob\n extends InstantBackgroundSchemaBaseJobWithInvalidTriples {\n type: 'required';\n}\n\nexport interface InstantBackgroundSchemaRemoveRequiredJob\n extends InstantBackgroundSchemaBaseJob {\n type: 'remove-required';\n}\n\nexport type InstantAPISchemaPlanStep =\n | InstantAPISchemaPlanAddAttrStep\n | InstantAPISchemaPlanDeleteAttrStep\n | InstantAPISchemaPlanUpdateAttrStep\n | InstantAPISchemaPlanIndexStep\n | InstantAPISchemaPlanRemoveIndexStep\n | InstantAPISchemaPlanUniqueStep\n | InstantAPISchemaPlanRemoveUniqueStep\n | InstantAPISchemaPlanRequiredStep\n | InstantAPISchemaPlanRemoveRequiredStep\n | InstantAPISchemaPlanCheckDataTypeStep\n | InstantAPISchemaPlanRemoveDataTypeStep;\n\ntype BackgroundJobByStep = {\n index: InstantBackgroundSchemaAddIndexJob;\n 'remove-index': InstantBackgroundSchemaRemoveIndexJob;\n unique: InstantBackgroundSchemaAddUniqueJob;\n 'remove-unique': InstantBackgroundSchemaRemoveUniqueJob;\n required: InstantBackgroundSchemaAddRequiredJob;\n 'remove-required': InstantBackgroundSchemaRemoveRequiredJob;\n 'check-data-type': InstantBackgroundSchemaCheckDataTypeJob;\n 'remove-data-type': InstantBackgroundSchemaRemoveDataTypeJob;\n};\n\n// Adds the proper flavor of the backgroundJob type to the steps\n// that run in the background\nexport type WithBackgroundJob<P extends { type: string }> =\n P['type'] extends keyof BackgroundJobByStep\n ? P & { backgroundJob: BackgroundJobByStep[P['type']] }\n : P;\n\nexport type InstantAPISchemaPushAddAttrStep =\n WithBackgroundJob<InstantAPISchemaPlanAddAttrStep>;\n\nexport type InstantAPISchemaPushUpdateAttrStep =\n WithBackgroundJob<InstantAPISchemaPlanUpdateAttrStep>;\n\nexport type InstantAPISchemaPushIndexStep =\n WithBackgroundJob<InstantAPISchemaPlanIndexStep>;\n\nexport type InstantAPISchemaPushRemoveIndexStep =\n WithBackgroundJob<InstantAPISchemaPlanRemoveIndexStep>;\n\nexport type InstantAPISchemaPushUniqueStep =\n WithBackgroundJob<InstantAPISchemaPlanUniqueStep>;\n\nexport type InstantAPISchemaPushRemoveUniqueStep =\n WithBackgroundJob<InstantAPISchemaPlanRemoveUniqueStep>;\n\nexport type InstantAPISchemaPushRequiredStep =\n WithBackgroundJob<InstantAPISchemaPlanRequiredStep>;\n\nexport type InstantAPISchemaPushRemoveRequiredStep =\n WithBackgroundJob<InstantAPISchemaPlanRemoveRequiredStep>;\n\nexport type InstantAPISchemaPushCheckDataTypeStep =\n WithBackgroundJob<InstantAPISchemaPlanCheckDataTypeStep>;\n\nexport type InstantAPISchemaPushRemoveDataTypeStep =\n WithBackgroundJob<InstantAPISchemaPlanRemoveDataTypeStep>;\n\nexport type InstantAPISchemaPushStep =\n | InstantAPISchemaPushAddAttrStep\n | InstantAPISchemaPushUpdateAttrStep\n | InstantAPISchemaPushIndexStep\n | InstantAPISchemaPushRemoveIndexStep\n | InstantAPISchemaPushUniqueStep\n | InstantAPISchemaPushRemoveUniqueStep\n | InstantAPISchemaPushRequiredStep\n | InstantAPISchemaPushRemoveRequiredStep\n | InstantAPISchemaPushCheckDataTypeStep\n | InstantAPISchemaPushRemoveDataTypeStep;\n\nfunction entityDefToCodeStr(\n name: string,\n edef: EntityDef<\n AttrsDefs,\n Record<string, LinkAttrDef<CardinalityKind, string>>,\n any\n >,\n) {\n return renderEntityProperty(name, edef.attrs, {\n keyOptions: { alwaysQuote: true, quote: '\"' },\n trailingComma: true,\n });\n}\n\nexport function identEtype(ident: InstantDBIdent) {\n return ident[1];\n}\n\nexport function identLabel(ident: InstantDBIdent) {\n return ident[2];\n}\n\nexport function identName(ident: InstantDBIdent) {\n return `${identEtype(ident)}.${identLabel(ident)}`;\n}\n\nexport function attrFwdLabel(attr: InstantDBAttr) {\n return attr['forward-identity']?.[2];\n}\n\nexport function attrFwdEtype(attr: InstantDBAttr) {\n return attr['forward-identity']?.[1];\n}\n\nexport function attrRevLabel(attr: InstantDBAttr) {\n return attr['reverse-identity']?.[2];\n}\n\nexport function attrRevEtype(attr: InstantDBAttr) {\n return attr['reverse-identity']?.[1];\n}\n\nexport function attrFwdName(attr: InstantDBAttr) {\n return `${attrFwdEtype(attr)}.${attrFwdLabel(attr)}`;\n}\n\nexport function attrRevName(attr: InstantDBAttr) {\n if (attr['reverse-identity']) {\n return `${attrRevEtype(attr)}.${attrRevLabel(attr)}`;\n }\n}\n\nfunction easyPlural(strn: string, n: number) {\n return n === 1 ? strn : strn + 's';\n}\n\nfunction roomDefToCodeStr(room: RoomsDef[string]) {\n let ret = '{';\n\n if (room.presence) {\n ret += `\\n${indentLines(entityDefToCodeStr('presence', room.presence), 4)},`;\n }\n\n if (room.topics) {\n ret += `\\n ${formatKey('topics', { alwaysQuote: true, quote: '\"' })}: {`;\n\n for (const [topicName, topicConfig] of Object.entries(room.topics)) {\n ret += `\\n${indentLines(entityDefToCodeStr(topicName, topicConfig), 6)},`;\n }\n ret += `\\n }`;\n }\n\n ret += ret === '{' ? '}' : '\\n }';\n\n return ret;\n}\n\nfunction roomsCodeStr(rooms: RoomsDef) {\n let ret = '{';\n\n for (const [roomType, roomDef] of Object.entries(rooms)) {\n ret += `\\n ${formatKey(roomType, { alwaysQuote: true, quote: '\"' })}: ${roomDefToCodeStr(roomDef)},`;\n }\n ret += ret === '{' ? '}' : '\\n}';\n\n return ret;\n}\n\nexport function generateSchemaTypescriptFile(\n prevSchema: GenericSchemaDef | null | undefined,\n newSchema: GenericSchemaDef,\n instantModuleName: string,\n): string {\n // entities\n const entitiesEntriesCode = joinWithTrailingSep(\n sortedEntries(newSchema.entities).map(([etype, entityDef]) =>\n entityDefToCodeStr(etype, entityDef),\n ),\n ',\\n',\n ',',\n );\n\n const inferredAttrs: DataAttrDef<string, boolean, boolean>[] = [];\n\n for (const entity of Object.values(newSchema.entities)) {\n for (const attr of Object.values(entity.attrs)) {\n if ((attr.metadata.derivedType as any)?.origin === 'inferred') {\n inferredAttrs.push(attr);\n }\n }\n }\n\n const entitiesObjCode = `{\\n${indentLines(entitiesEntriesCode, 2)}\\n}`;\n\n const entitiesComment =\n inferredAttrs.length > 0\n ? `// We inferred ${inferredAttrs.length} ${easyPlural('attribute', inferredAttrs.length)}!\n// Take a look at this schema, and if everything looks good,\n// run \\`push schema\\` again to enforce the types.`\n : '';\n\n const linksEntriesCode = renderLinksObject(newSchema.links, {\n keyOptions: { alwaysQuote: true, quote: '\"' },\n stringQuote: '\"',\n style: 'json',\n });\n\n // rooms\n const rooms = prevSchema?.rooms || {};\n const roomsCode = roomsCodeStr(rooms);\n const kv = (k: string, v: string, comment?: string) => {\n const res = comment ? `${comment}\\n${k}: ${v}` : `${k}: ${v}`;\n return indentLines(res, 2);\n };\n\n const code = `// Docs: https://www.instantdb.com/docs/modeling-data\n\nimport { i } from \"${instantModuleName ?? '@instantdb/core'}\";\n\nconst _schema = i.schema({\n${kv('entities', entitiesObjCode, entitiesComment)},\n${kv('links', linksEntriesCode)},\n${kv('rooms', roomsCode)}\n});\n\n// This helps Typescript display nicer intellisense\ntype _AppSchema = typeof _schema;\ninterface AppSchema extends _AppSchema {}\nconst schema: AppSchema = _schema;\n\nexport type { AppSchema }\nexport default schema;\n`;\n\n return code;\n}\n\nexport class SchemaValidationError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'SchemaValidationError';\n }\n}\n\nexport const validateSchema = (\n schema: GenericSchemaDef,\n systemCatalogIdentNames: Record<string, Set<string>>,\n) => {\n const entityNames = Object.keys(schema.entities);\n\n for (const [etype, entityDef] of Object.entries(schema.entities)) {\n if (!etype.startsWith('$')) continue;\n if (!systemCatalogIdentNames[etype]) {\n throw new SchemaValidationError(\n 'The $ keyword is reserved for system namespaces.' +\n `\\nYou can't create '${etype}'. Perhaps call it '${etype.slice(1)}' instead?`,\n );\n }\n for (const [attrName, attrDef] of Object.entries(entityDef.attrs)) {\n if (systemCatalogIdentNames[etype].has(attrName)) {\n continue;\n }\n if (attrDef.required) {\n throw new SchemaValidationError(\n `The '${etype}' namespace is managed by the system and can't modify required constraints yet.` +\n `\\nMake sure to set ${etype}.${attrName} as optional.` +\n `\\n i.e { ${attrName}: i.${attrDef.valueType}().optional() }`,\n );\n }\n }\n }\n\n for (const link of Object.values(schema.links)) {\n if (\n systemCatalogIdentNames[link.forward.on] &&\n !systemCatalogIdentNames[link.forward.on].has(link.forward.label) &&\n link.forward.required\n ) {\n throw new SchemaValidationError(\n `The ${link.forward.on} namespace is managed by the system and can't modify required constraints yet.` +\n `\\nMake sure to set ${link.forward.on}${link.forward.label} as 'optional'.` +\n `\\n i.e { 'on': '${link.forward.on}', 'label': ${link.forward.label}, 'required': false }`,\n );\n }\n\n if (link.forward.has === 'many' && link.forward.onDelete === 'cascade') {\n throw new SchemaValidationError(\n `${link.forward.on}${link.forward.label} -> ${link.reverse.on}${link.reverse.label} has onDelete: \"cascade\" with has: \"many\"`,\n );\n }\n if (link.reverse.has === 'many' && link.reverse.onDelete === 'cascade') {\n throw new SchemaValidationError(\n `${link.forward.on}${link.forward.label} -> ${link.reverse.on}${link.reverse.label} has onDelete: \"cascade\" with has: \"many\"`,\n );\n }\n\n const linkDisplay = `${link.forward.on}${link.forward.label} -> ${link.reverse.on}${link.reverse.label}`;\n if (!entityNames.includes(link.forward.on)) {\n throw new SchemaValidationError(\n `${linkDisplay} connects to non existing entity \"${link.forward.on}\".`,\n );\n }\n if (!entityNames.includes(link.reverse.on)) {\n throw new SchemaValidationError(\n `${linkDisplay} connects to non existing entity \"${link.forward.on}\".`,\n );\n }\n }\n};\n"]}
1
+ {"version":3,"file":"schema.js","sourceRoot":"","sources":["../../src/schema.ts"],"names":[],"mappings":"AAaA,OAAO,EACL,WAAW,EACX,mBAAmB,EACnB,aAAa,EACb,SAAS,GAEV,MAAM,WAAW,CAAC;AAiPnB,SAAS,mBAAmB,CAAC,CAAC,IAAI,EAAE,IAAI,CAGvC;;IACC,MAAM,IAAI,GACR,CAAA,MAAC,IAAI,CAAC,QAAQ,C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,IAAI,qBAAqB,CAC7B,GAAG,IAAI,CAAC,OAAO,CAAC,EAAE,GAAG,IAAI,CAAC,OAAO,CAAC,KAAK,OAAO,IAAI,CAAC,OAAO,CAAC,EAAE,GAAG,IAAI,CAAC,OAAO,CAAC,KAAK,2CAA2C,CAC9H,CAAC;QACJ,CAAC;QAED,MAAM,WAAW,GAAG,GAAG,IAAI,CAAC,OAAO,CAAC,EAAE,GAAG,IAAI,CAAC,OAAO,CAAC,KAAK,OAAO,IAAI,CAAC,OAAO,CAAC,EAAE,GAAG,IAAI,CAAC,OAAO,CAAC,KAAK,EAAE,CAAC;QACzG,IAAI,CAAC,WAAW,CAAC,QAAQ,CAAC,IAAI,CAAC,OAAO,CAAC,EAAE,CAAC,EAAE,CAAC;YAC3C,MAAM,IAAI,qBAAqB,CAC7B,GAAG,WAAW,qCAAqC,IAAI,CAAC,OAAO,CAAC,EAAE,IAAI,CACvE,CAAC;QACJ,CAAC;QACD,IAAI,CAAC,WAAW,CAAC,QAAQ,CAAC,IAAI,CAAC,OAAO,CAAC,EAAE,CAAC,EAAE,CAAC;YAC3C,MAAM,IAAI,qBAAqB,CAC7B,GAAG,WAAW,qCAAqC,IAAI,CAAC,OAAO,CAAC,EAAE,IAAI,CACvE,CAAC;QACJ,CAAC;IACH,CAAC;AACH,CAAC,CAAC","sourcesContent":["import {\n AttrsDefs,\n CardinalityKind,\n DataAttrDef,\n EntityDef,\n InstantDBAttr,\n InstantDBCheckedDataType,\n InstantDBIdent,\n InstantSchemaDef,\n LinkAttrDef,\n RoomsDef,\n} from '@instantdb/core';\n\nimport {\n indentLines,\n joinWithTrailingSep,\n sortedEntries,\n formatKey,\n GenericSchemaDef,\n} from './util.ts';\n\nexport type InstantAPIPlatformSchema = {\n refs: Record<string, InstantDBAttr>;\n blobs: Record<string, Record<string, InstantDBAttr>>;\n};\n\nexport type InstantAPISchemaPlanAddAttrStep = {\n type: 'add-attr';\n friendlyDescription: string;\n attr: InstantDBAttr;\n};\n\nexport type InstantAPISchemaPlanDeleteAttrStep = {\n type: 'delete-attr';\n friendlyDescription: string;\n attrId: string;\n};\n\nexport type InstantAPISchemaPlanUpdateAttrStep = {\n type: 'update-attr';\n friendlyDescription: string;\n attr: InstantDBAttr;\n};\n\nexport type InstantAPISchemaPlanIndexStep = {\n type: 'index';\n friendlyDescription: string;\n attrId: string;\n forwardIdentity: InstantDBIdent;\n};\n\nexport type InstantAPISchemaPlanRemoveIndexStep = {\n type: 'remove-index';\n friendlyDescription: string;\n attrId: string;\n forwardIdentity: InstantDBIdent;\n};\n\nexport type InstantAPISchemaPlanUniqueStep = {\n type: 'unique';\n friendlyDescription: string;\n attrId: string;\n forwardIdentity: InstantDBIdent;\n};\n\nexport type InstantAPISchemaPlanRemoveUniqueStep = {\n type: 'remove-unique';\n friendlyDescription: string;\n attrId: string;\n forwardIdentity: InstantDBIdent;\n};\n\nexport type InstantAPISchemaPlanRequiredStep = {\n type: 'required';\n friendlyDescription: string;\n attrId: string;\n forwardIdentity: InstantDBIdent;\n};\n\nexport type InstantAPISchemaPlanRemoveRequiredStep = {\n type: 'remove-required';\n friendlyDescription: string;\n attrId: string;\n forwardIdentity: InstantDBIdent;\n};\n\nexport type InstantAPISchemaPlanCheckDataTypeStep = {\n type: 'check-data-type';\n friendlyDescription: string;\n attrId: string;\n forwardIdentity: InstantDBIdent;\n checkedDataType: InstantDBCheckedDataType;\n};\n\nexport type InstantAPISchemaPlanRemoveDataTypeStep = {\n type: 'remove-data-type';\n friendlyDescription: string;\n attrId: string;\n forwardIdentity: InstantDBIdent;\n};\n\ntype InstantBackgroundSchemaBaseJob = {\n id: string;\n createdAt: Date;\n updatedAt: Date;\n status: 'completed' | 'waiting' | 'processing' | 'errored';\n workEstimate: number | null;\n workCompleted: number | null;\n error?:\n | 'invalid-triple-error'\n | 'invalid-attr-state-error'\n | 'triple-not-unique-error'\n | 'triple-too-large-error'\n | 'missing-required-error'\n | 'unexpected-error';\n invalidTriplesSample?: {\n entityId: string;\n value: any;\n jsonType:\n | 'string'\n | 'number'\n | 'boolean'\n | 'null'\n | 'object'\n | 'array'\n | 'date';\n }[];\n};\n\ntype InstantBackgroundSchemaBaseJobWithInvalidTriples =\n InstantBackgroundSchemaBaseJob & {\n invalidTriplesSample?: {\n entityId: string;\n value: any;\n jsonType:\n | 'string'\n | 'number'\n | 'boolean'\n | 'null'\n | 'object'\n | 'array'\n | 'date';\n }[];\n };\n\nexport interface InstantBackgroundSchemaRemoveDataTypeJob\n extends InstantBackgroundSchemaBaseJob {\n type: 'remove-data-type';\n}\n\nexport interface InstantBackgroundSchemaCheckDataTypeJob\n extends InstantBackgroundSchemaBaseJobWithInvalidTriples {\n type: 'check-data-type';\n checkedDataType: InstantDBCheckedDataType;\n}\n\nexport interface InstantBackgroundSchemaAddIndexJob\n extends InstantBackgroundSchemaBaseJobWithInvalidTriples {\n type: 'index';\n}\n\nexport interface InstantBackgroundSchemaRemoveIndexJob\n extends InstantBackgroundSchemaBaseJob {\n type: 'remove-index';\n}\n\nexport interface InstantBackgroundSchemaAddUniqueJob\n extends InstantBackgroundSchemaBaseJobWithInvalidTriples {\n type: 'unique';\n invalidUniqueValue?: any;\n}\n\nexport interface InstantBackgroundSchemaRemoveUniqueJob\n extends InstantBackgroundSchemaBaseJob {\n type: 'remove-unique';\n}\n\nexport interface InstantBackgroundSchemaAddRequiredJob\n extends InstantBackgroundSchemaBaseJobWithInvalidTriples {\n type: 'required';\n}\n\nexport interface InstantBackgroundSchemaRemoveRequiredJob\n extends InstantBackgroundSchemaBaseJob {\n type: 'remove-required';\n}\n\nexport type InstantAPISchemaPlanStep =\n | InstantAPISchemaPlanAddAttrStep\n | InstantAPISchemaPlanDeleteAttrStep\n | InstantAPISchemaPlanUpdateAttrStep\n | InstantAPISchemaPlanIndexStep\n | InstantAPISchemaPlanRemoveIndexStep\n | InstantAPISchemaPlanUniqueStep\n | InstantAPISchemaPlanRemoveUniqueStep\n | InstantAPISchemaPlanRequiredStep\n | InstantAPISchemaPlanRemoveRequiredStep\n | InstantAPISchemaPlanCheckDataTypeStep\n | InstantAPISchemaPlanRemoveDataTypeStep;\n\ntype BackgroundJobByStep = {\n index: InstantBackgroundSchemaAddIndexJob;\n 'remove-index': InstantBackgroundSchemaRemoveIndexJob;\n unique: InstantBackgroundSchemaAddUniqueJob;\n 'remove-unique': InstantBackgroundSchemaRemoveUniqueJob;\n required: InstantBackgroundSchemaAddRequiredJob;\n 'remove-required': InstantBackgroundSchemaRemoveRequiredJob;\n 'check-data-type': InstantBackgroundSchemaCheckDataTypeJob;\n 'remove-data-type': InstantBackgroundSchemaRemoveDataTypeJob;\n};\n\n// Adds the proper flavor of the backgroundJob type to the steps\n// that run in the background\nexport type WithBackgroundJob<P extends { type: string }> =\n P['type'] extends keyof BackgroundJobByStep\n ? P & { backgroundJob: BackgroundJobByStep[P['type']] }\n : P;\n\nexport type InstantAPISchemaPushAddAttrStep =\n WithBackgroundJob<InstantAPISchemaPlanAddAttrStep>;\n\nexport type InstantAPISchemaPushUpdateAttrStep =\n WithBackgroundJob<InstantAPISchemaPlanUpdateAttrStep>;\n\nexport type InstantAPISchemaPushIndexStep =\n WithBackgroundJob<InstantAPISchemaPlanIndexStep>;\n\nexport type InstantAPISchemaPushRemoveIndexStep =\n WithBackgroundJob<InstantAPISchemaPlanRemoveIndexStep>;\n\nexport type InstantAPISchemaPushUniqueStep =\n WithBackgroundJob<InstantAPISchemaPlanUniqueStep>;\n\nexport type InstantAPISchemaPushRemoveUniqueStep =\n WithBackgroundJob<InstantAPISchemaPlanRemoveUniqueStep>;\n\nexport type InstantAPISchemaPushRequiredStep =\n WithBackgroundJob<InstantAPISchemaPlanRequiredStep>;\n\nexport type InstantAPISchemaPushRemoveRequiredStep =\n WithBackgroundJob<InstantAPISchemaPlanRemoveRequiredStep>;\n\nexport type InstantAPISchemaPushCheckDataTypeStep =\n WithBackgroundJob<InstantAPISchemaPlanCheckDataTypeStep>;\n\nexport type InstantAPISchemaPushRemoveDataTypeStep =\n WithBackgroundJob<InstantAPISchemaPlanRemoveDataTypeStep>;\n\nexport type InstantAPISchemaPushStep =\n | InstantAPISchemaPushAddAttrStep\n | InstantAPISchemaPushUpdateAttrStep\n | InstantAPISchemaPushIndexStep\n | InstantAPISchemaPushRemoveIndexStep\n | InstantAPISchemaPushUniqueStep\n | InstantAPISchemaPushRemoveUniqueStep\n | InstantAPISchemaPushRequiredStep\n | InstantAPISchemaPushRemoveRequiredStep\n | InstantAPISchemaPushCheckDataTypeStep\n | InstantAPISchemaPushRemoveDataTypeStep;\n\nfunction attrDefToCodeString([name, attr]: [\n string,\n DataAttrDef<string, boolean, boolean>,\n]) {\n const type =\n (attr.metadata.derivedType as any)?.type || attr.valueType || 'any';\n const unique = attr.config.unique ? '.unique()' : '';\n const index = attr.config.indexed ? '.indexed()' : '';\n const required = attr.required ? '' : '.optional()';\n return `${formatKey(name)}: i.${type}()${unique}${index}${required}`;\n}\n\nfunction entityDefToCodeStr(\n name: string,\n edef: EntityDef<\n AttrsDefs,\n Record<string, LinkAttrDef<CardinalityKind, string>>,\n any\n >,\n) {\n const attrBlock = joinWithTrailingSep(\n sortedEntries(edef.attrs).map(attrDefToCodeString),\n ',\\n',\n ',',\n );\n\n // a block of code for each entity\n return `${formatKey(name)}: i.entity({${attrBlock.length ? '\\n' : ''}${indentLines(attrBlock, 2)}${attrBlock.length ? '\\n' : ''}})`;\n}\n\nexport function identEtype(ident: InstantDBIdent) {\n return ident[1];\n}\n\nexport function identLabel(ident: InstantDBIdent) {\n return ident[2];\n}\n\nexport function identName(ident: InstantDBIdent) {\n return `${identEtype(ident)}.${identLabel(ident)}`;\n}\n\nexport function attrFwdLabel(attr: InstantDBAttr) {\n return attr['forward-identity']?.[2];\n}\n\nexport function attrFwdEtype(attr: InstantDBAttr) {\n return attr['forward-identity']?.[1];\n}\n\nexport function attrRevLabel(attr: InstantDBAttr) {\n return attr['reverse-identity']?.[2];\n}\n\nexport function attrRevEtype(attr: InstantDBAttr) {\n return attr['reverse-identity']?.[1];\n}\n\nexport function attrFwdName(attr: InstantDBAttr) {\n return `${attrFwdEtype(attr)}.${attrFwdLabel(attr)}`;\n}\n\nexport function attrRevName(attr: InstantDBAttr) {\n if (attr['reverse-identity']) {\n return `${attrRevEtype(attr)}.${attrRevLabel(attr)}`;\n }\n}\n\nfunction easyPlural(strn: string, n: number) {\n return n === 1 ? strn : strn + 's';\n}\n\nfunction roomDefToCodeStr(room: RoomsDef[string]) {\n let ret = '{';\n\n if (room.presence) {\n ret += `\\n${indentLines(entityDefToCodeStr('presence', room.presence), 4)},`;\n }\n\n if (room.topics) {\n ret += `\\n \"topics\": {`;\n\n for (const [topicName, topicConfig] of Object.entries(room.topics)) {\n ret += `\\n${indentLines(entityDefToCodeStr(topicName, topicConfig), 6)},`;\n }\n ret += `\\n }`;\n }\n\n ret += ret === '{' ? '}' : '\\n }';\n\n return ret;\n}\n\nfunction roomsCodeStr(rooms: RoomsDef) {\n let ret = '{';\n\n for (const [roomType, roomDef] of Object.entries(rooms)) {\n ret += `\\n ${formatKey(roomType)}: ${roomDefToCodeStr(roomDef)},`;\n }\n ret += ret === '{' ? '}' : '\\n}';\n\n return ret;\n}\n\nexport function generateSchemaTypescriptFile(\n prevSchema: GenericSchemaDef | null | undefined,\n newSchema: GenericSchemaDef,\n instantModuleName: string,\n): string {\n // entities\n const entitiesEntriesCode = joinWithTrailingSep(\n sortedEntries(newSchema.entities).map(([etype, entityDef]) =>\n entityDefToCodeStr(etype, entityDef),\n ),\n ',\\n',\n ',',\n );\n\n const inferredAttrs: DataAttrDef<string, boolean, boolean>[] = [];\n\n for (const entity of Object.values(newSchema.entities)) {\n for (const attr of Object.values(entity.attrs)) {\n if ((attr.metadata.derivedType as any)?.origin === 'inferred') {\n inferredAttrs.push(attr);\n }\n }\n }\n\n const entitiesObjCode = `{\\n${indentLines(entitiesEntriesCode, 2)}\\n}`;\n\n const entitiesComment =\n inferredAttrs.length > 0\n ? `// We inferred ${inferredAttrs.length} ${easyPlural('attribute', inferredAttrs.length)}!\n// Take a look at this schema, and if everything looks good,\n// run \\`push schema\\` again to enforce the types.`\n : '';\n\n const linksEntriesCode = JSON.stringify(newSchema.links, null, 2).trim();\n\n // rooms\n const rooms = prevSchema?.rooms || {};\n const roomsCode = roomsCodeStr(rooms);\n const kv = (k: string, v: string, comment?: string) => {\n const res = comment ? `${comment}\\n${k}: ${v}` : `${k}: ${v}`;\n return indentLines(res, 2);\n };\n\n const code = `// Docs: https://www.instantdb.com/docs/modeling-data\n\nimport { i } from \"${instantModuleName ?? '@instantdb/core'}\";\n\nconst _schema = i.schema({\n${kv('entities', entitiesObjCode, entitiesComment)},\n${kv('links', linksEntriesCode)},\n${kv('rooms', roomsCode)}\n});\n\n// This helps Typescript display nicer intellisense\ntype _AppSchema = typeof _schema;\ninterface AppSchema extends _AppSchema {}\nconst schema: AppSchema = _schema;\n\nexport type { AppSchema }\nexport default schema;\n`;\n\n return code;\n}\n\nexport class SchemaValidationError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'SchemaValidationError';\n }\n}\n\nexport const validateSchema = (\n schema: GenericSchemaDef,\n systemCatalogIdentNames: Record<string, Set<string>>,\n) => {\n const entityNames = Object.keys(schema.entities);\n\n for (const [etype, entityDef] of Object.entries(schema.entities)) {\n if (!etype.startsWith('$')) continue;\n if (!systemCatalogIdentNames[etype]) {\n throw new SchemaValidationError(\n 'The $ keyword is reserved for system namespaces.' +\n `\\nYou can't create '${etype}'. Perhaps call it '${etype.slice(1)}' instead?`,\n );\n }\n for (const [attrName, attrDef] of Object.entries(entityDef.attrs)) {\n if (systemCatalogIdentNames[etype].has(attrName)) {\n continue;\n }\n if (attrDef.required) {\n throw new SchemaValidationError(\n `The '${etype}' namespace is managed by the system and can't modify required constraints yet.` +\n `\\nMake sure to set ${etype}.${attrName} as optional.` +\n `\\n i.e { ${attrName}: i.${attrDef.valueType}().optional() }`,\n );\n }\n }\n }\n\n for (const link of Object.values(schema.links)) {\n if (\n systemCatalogIdentNames[link.forward.on] &&\n !systemCatalogIdentNames[link.forward.on].has(link.forward.label) &&\n link.forward.required\n ) {\n throw new SchemaValidationError(\n `The ${link.forward.on} namespace is managed by the system and can't modify required constraints yet.` +\n `\\nMake sure to set ${link.forward.on}${link.forward.label} as 'optional'.` +\n `\\n i.e { 'on': '${link.forward.on}', 'label': ${link.forward.label}, 'required': false }`,\n );\n }\n\n if (link.forward.has === 'many' && link.forward.onDelete === 'cascade') {\n throw new SchemaValidationError(\n `${link.forward.on}${link.forward.label} -> ${link.reverse.on}${link.reverse.label} has onDelete: \"cascade\" with has: \"many\"`,\n );\n }\n if (link.reverse.has === 'many' && link.reverse.onDelete === 'cascade') {\n throw new SchemaValidationError(\n `${link.forward.on}${link.forward.label} -> ${link.reverse.on}${link.reverse.label} has onDelete: \"cascade\" with has: \"many\"`,\n );\n }\n\n const linkDisplay = `${link.forward.on}${link.forward.label} -> ${link.reverse.on}${link.reverse.label}`;\n if (!entityNames.includes(link.forward.on)) {\n throw new SchemaValidationError(\n `${linkDisplay} connects to non existing entity \"${link.forward.on}\".`,\n );\n }\n if (!entityNames.includes(link.reverse.on)) {\n throw new SchemaValidationError(\n `${linkDisplay} connects to non existing entity \"${link.forward.on}\".`,\n );\n }\n }\n};\n"]}