@instantdb/platform 0.22.99-experimental.add-user-perm-rules.20792844601.1 → 0.22.99

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.
Files changed (48) hide show
  1. package/.turbo/turbo-build.log +8 -8
  2. package/dist/commonjs/ProgressPromise.js +45 -58
  3. package/dist/commonjs/ProgressPromise.js.map +1 -1
  4. package/dist/commonjs/api.js +366 -412
  5. package/dist/commonjs/api.js.map +1 -1
  6. package/dist/commonjs/migrationUtils.js +16 -4
  7. package/dist/commonjs/migrationUtils.js.map +1 -1
  8. package/dist/commonjs/migrations.js +10 -21
  9. package/dist/commonjs/migrations.js.map +1 -1
  10. package/dist/commonjs/oauth.js +52 -55
  11. package/dist/commonjs/oauth.js.map +1 -1
  12. package/dist/commonjs/oauthCommon.js +2 -0
  13. package/dist/commonjs/oauthCommon.js.map +1 -1
  14. package/dist/commonjs/perms.js +1 -1
  15. package/dist/commonjs/perms.js.map +1 -1
  16. package/dist/commonjs/schema.js +8 -14
  17. package/dist/commonjs/schema.js.map +1 -1
  18. package/dist/commonjs/serverOAuth.js +55 -68
  19. package/dist/commonjs/serverOAuth.js.map +1 -1
  20. package/dist/commonjs/typescript-schema.js +1 -2
  21. package/dist/commonjs/typescript-schema.js.map +1 -1
  22. package/dist/commonjs/util.js +1 -1
  23. package/dist/commonjs/util.js.map +1 -1
  24. package/dist/esm/ProgressPromise.js +45 -58
  25. package/dist/esm/ProgressPromise.js.map +1 -1
  26. package/dist/esm/api.js +366 -412
  27. package/dist/esm/api.js.map +1 -1
  28. package/dist/esm/migrationUtils.js +16 -4
  29. package/dist/esm/migrationUtils.js.map +1 -1
  30. package/dist/esm/migrations.js +10 -21
  31. package/dist/esm/migrations.js.map +1 -1
  32. package/dist/esm/oauth.js +52 -55
  33. package/dist/esm/oauth.js.map +1 -1
  34. package/dist/esm/oauthCommon.js +2 -0
  35. package/dist/esm/oauthCommon.js.map +1 -1
  36. package/dist/esm/perms.js +1 -1
  37. package/dist/esm/perms.js.map +1 -1
  38. package/dist/esm/schema.js +8 -14
  39. package/dist/esm/schema.js.map +1 -1
  40. package/dist/esm/serverOAuth.js +55 -68
  41. package/dist/esm/serverOAuth.js.map +1 -1
  42. package/dist/esm/typescript-schema.js +1 -2
  43. package/dist/esm/typescript-schema.js.map +1 -1
  44. package/dist/esm/util.js +1 -1
  45. package/dist/esm/util.js.map +1 -1
  46. package/dist/standalone/index.js +690 -660
  47. package/dist/standalone/index.umd.cjs +16 -16
  48. package/package.json +3 -3
@@ -1 +1 @@
1
- {"version":3,"file":"schema.js","sourceRoot":"","sources":["../../src/schema.ts"],"names":[],"mappings":";;;AAkSA,gCAEC;AAED,gCAEC;AAED,8BAEC;AAED,oCAEC;AAED,oCAEC;AAED,oCAEC;AAED,oCAEC;AAED,kCAEC;AAED,kCAIC;AAsCD,oEA+DC;AA9ZD,uCAMmB;AAiPnB,SAAS,mBAAmB,CAAC,CAAC,IAAI,EAAE,IAAI,CAGvC;;IACC,MAAM,IAAI,GACR,CAAA,MAAC,IAAI,CAAC,QAAQ,CAAC,WAAmB,0CAAE,IAAI,KAAI,IAAI,CAAC,SAAS,IAAI,KAAK,CAAC;IACtE,MAAM,MAAM,GAAG,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,CAAC,WAAW,CAAC,CAAC,CAAC,EAAE,CAAC;IACrD,MAAM,KAAK,GAAG,IAAI,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,CAAC,YAAY,CAAC,CAAC,CAAC,EAAE,CAAC;IACtD,MAAM,QAAQ,GAAG,IAAI,CAAC,QAAQ,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,aAAa,CAAC;IACpD,OAAO,GAAG,IAAA,mBAAS,EAAC,IAAI,CAAC,OAAO,IAAI,KAAK,MAAM,GAAG,KAAK,GAAG,QAAQ,EAAE,CAAC;AACvE,CAAC;AAED,SAAS,kBAAkB,CACzB,IAAY,EACZ,IAIC;IAED,MA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C,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;AAhEW,QAAA,cAAc,kBAgEzB","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"]}
1
+ {"version":3,"file":"schema.js","sourceRoot":"","sources":["../../src/schema.ts"],"names":[],"mappings":";;;AAkSA,gCAEC;AAED,gCAEC;AAED,8BAEC;AAED,oCAEC;AAED,oCAEC;AAED,oCAEC;AAED,oCAEC;AAED,kCAEC;AAED,kCAIC;AAsCD,oEA+DC;AA9ZD,uCAMmB;AAiPnB,SAAS,mBAAmB,CAAC,CAAC,IAAI,EAAE,IAAI,CAGvC;IACC,MAAM,IAAI,GACP,IAAI,CAAC,QAAQ,CAAC,WAAmB,EAAE,IAAI,IAAI,IAAI,CAAC,SAAS,IAAI,KAAK,CAAC;IACtE,MAAM,MAAM,GAAG,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,CAAC,WAAW,CAAC,CAAC,CAAC,EAAE,CAAC;IACrD,MAAM,KAAK,GAAG,IAAI,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,CAAC,YAAY,CAAC,CAAC,CAAC,EAAE,CAAC;IACtD,MAAM,QAAQ,GAAG,IAAI,CAAC,QAAQ,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,aAAa,CAAC;IACpD,OAAO,GAAG,IAAA,mBAAS,EAAC,IAAI,CAAC,OAAO,IAAI,KAAK,MAAM,GAAG,KAAK,GAAG,QAAQ,EAAE,CAAC;AACvE,CAAC;AAED,SAAS,kBAAkB,CACzB,IAAY,EACZ,IAIC;IAED,MAAM,SAAS,GAAG,IAAA,6BAAmB,EACnC,IAAA,uBAAa,EAAC,IAAI,CAAC,KAAK,CAAC,CAAC,GAAG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qB,CAC7B,GAAG,WAAW,qCAAqC,IAAI,CAAC,OAAO,CAAC,EAAE,IAAI,CACvE,CAAC;QACJ,CAAC;IACH,CAAC;AACH,CAAC,CAAC;AAhEW,QAAA,cAAc,kBAgEzB","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"]}
@@ -1,78 +1,65 @@
1
1
  "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
2
  Object.defineProperty(exports, "__esModule", { value: true });
12
3
  exports.exchangeCodeForToken = exchangeCodeForToken;
13
4
  exports.exchangeRefreshToken = exchangeRefreshToken;
14
5
  const oauthCommon_ts_1 = require("./oauthCommon.js");
15
- function exchangeCodeForToken(_a) {
16
- return __awaiter(this, arguments, void 0, function* ({ code, clientId, clientSecret, redirectUri, apiURI = 'https://api.instantdb.com', }) {
17
- const res = yield fetch(`${apiURI}/platform/oauth/token`, {
18
- method: 'POST',
19
- headers: { 'Content-type': 'application/json' },
20
- body: JSON.stringify({
21
- grant_type: 'authorization_code',
22
- code,
23
- redirect_uri: redirectUri,
24
- client_id: clientId,
25
- client_secret: clientSecret,
26
- }),
27
- });
28
- if (!res.ok) {
29
- const text = yield res.text();
30
- let error;
31
- try {
32
- const json = JSON.parse(text);
33
- error = {
34
- error: json.error,
35
- errorDescription: json.error_description,
36
- message: `OAuth error: ${json.error || 'server_error'}`,
37
- };
38
- }
39
- catch (e) {
40
- error = {
41
- error: 'server_error',
42
- message: 'OAuth error: server_error',
43
- };
44
- }
45
- throw new oauthCommon_ts_1.InstantOAuthError(error);
46
- }
47
- const json = (yield res.json());
48
- return {
49
- accessToken: json.access_token,
50
- expiresAt: new Date(Date.now() + (json.expires_in - 30) * 1000),
51
- refreshToken: json.refresh_token,
52
- scopes: json.scopes,
53
- tokenType: json.token_type,
54
- };
6
+ async function exchangeCodeForToken({ code, clientId, clientSecret, redirectUri, apiURI = 'https://api.instantdb.com', }) {
7
+ const res = await fetch(`${apiURI}/platform/oauth/token`, {
8
+ method: 'POST',
9
+ headers: { 'Content-type': 'application/json' },
10
+ body: JSON.stringify({
11
+ grant_type: 'authorization_code',
12
+ code,
13
+ redirect_uri: redirectUri,
14
+ client_id: clientId,
15
+ client_secret: clientSecret,
16
+ }),
55
17
  });
18
+ if (!res.ok) {
19
+ const text = await res.text();
20
+ let error;
21
+ try {
22
+ const json = JSON.parse(text);
23
+ error = {
24
+ error: json.error,
25
+ errorDescription: json.error_description,
26
+ message: `OAuth error: ${json.error || 'server_error'}`,
27
+ };
28
+ }
29
+ catch (e) {
30
+ error = {
31
+ error: 'server_error',
32
+ message: 'OAuth error: server_error',
33
+ };
34
+ }
35
+ throw new oauthCommon_ts_1.InstantOAuthError(error);
36
+ }
37
+ const json = (await res.json());
38
+ return {
39
+ accessToken: json.access_token,
40
+ expiresAt: new Date(Date.now() + (json.expires_in - 30) * 1000),
41
+ refreshToken: json.refresh_token,
42
+ scopes: json.scopes,
43
+ tokenType: json.token_type,
44
+ };
56
45
  }
57
- function exchangeRefreshToken(_a) {
58
- return __awaiter(this, arguments, void 0, function* ({ clientId, clientSecret, refreshToken, apiURI = 'https://api.instantdb.com', }) {
59
- const res = yield fetch(`${apiURI}/platform/oauth/token`, {
60
- method: 'POST',
61
- headers: { 'Content-Type': 'application/json' },
62
- body: JSON.stringify({
63
- grant_type: 'refresh_token',
64
- refresh_token: refreshToken,
65
- client_id: clientId,
66
- client_secret: clientSecret,
67
- }),
68
- });
69
- const json = (yield res.json());
70
- return {
71
- accessToken: json.access_token,
72
- expiresAt: new Date((json.expires_in - 30) * 1000),
73
- scopes: json.scopes,
74
- tokenType: json.token_type,
75
- };
46
+ async function exchangeRefreshToken({ clientId, clientSecret, refreshToken, apiURI = 'https://api.instantdb.com', }) {
47
+ const res = await fetch(`${apiURI}/platform/oauth/token`, {
48
+ method: 'POST',
49
+ headers: { 'Content-Type': 'application/json' },
50
+ body: JSON.stringify({
51
+ grant_type: 'refresh_token',
52
+ refresh_token: refreshToken,
53
+ client_id: clientId,
54
+ client_secret: clientSecret,
55
+ }),
76
56
  });
57
+ const json = (await res.json());
58
+ return {
59
+ accessToken: json.access_token,
60
+ expiresAt: new Date((json.expires_in - 30) * 1000),
61
+ scopes: json.scopes,
62
+ tokenType: json.token_type,
63
+ };
77
64
  }
78
65
  //# sourceMappingURL=serverOAuth.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"serverOAuth.js","sourceRoot":"","sources":["../../src/serverOAuth.ts"],"names":[],"mappings":";;;;;;;;;;;AAEA,oDAmEC;AAED,oDAwCC;AA/GD,qDAAqD;AAErD,SAAsB,oBAAoB;yDAAC,EACzC,IAAI,EACJ,QAAQ,EACR,YAAY,EACZ,WAAW,EACX,MAAM,GAAG,2BAA2B,GAOrC;QAOC,MAAM,GAAG,GAAG,MAAM,KAAK,CAAC,GAAG,MAAM,uBAAuB,EAAE;YACxD,MAAM,EAAE,MAAM;YACd,OAAO,EAAE,EAAE,cAAc,EAAE,kBAAkB,EAAE;YAC/C,IAAI,EAAE,IAAI,CAAC,SAAS,CAAC;gBACnB,UAAU,EAAE,oBAAoB;gBAChC,IAAI;gBACJ,YAAY,EAAE,WAAW;gBACzB,SAAS,EAAE,QAAQ;gBACnB,aAAa,EAAE,YAAY;aAC5B,CAAC;SACH,CAAC,CAAC;QAEH,IAAI,CAAC,GAAG,CAAC,EAAE,EAAE,CAAC;YACZ,MAAM,IAAI,GAAG,MAAM,GAAG,CAAC,IAAI,EAAE,CAAC;YAC9B,IAAI,KAAK,CAAC;YAEV,IAAI,CAAC;gBACH,MAAM,IAAI,GAAG,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;gBAC9B,KAAK,GAAG;oBACN,KAAK,EA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L,WAAW,EAAE,IAAI,CAAC,YAAY;YAC9B,SAAS,EAAE,IAAI,IAAI,CAAC,CAAC,IAAI,CAAC,UAAU,GAAG,EAAE,CAAC,GAAG,IAAI,CAAC;YAClD,MAAM,EAAE,IAAI,CAAC,MAAM;YACnB,SAAS,EAAE,IAAI,CAAC,UAAU;SAC3B,CAAC;IACJ,CAAC;CAAA","sourcesContent":["import { InstantOAuthError } from './oauthCommon.ts';\n\nexport async function exchangeCodeForToken({\n code,\n clientId,\n clientSecret,\n redirectUri,\n apiURI = 'https://api.instantdb.com',\n}: {\n code: string;\n clientId: string;\n clientSecret: string;\n redirectUri: string;\n apiURI?: string;\n}): Promise<{\n accessToken: string;\n refreshToken: string;\n expiresAt: Date;\n scopes: string;\n tokenType: 'Bearer';\n}> {\n const res = await fetch(`${apiURI}/platform/oauth/token`, {\n method: 'POST',\n headers: { 'Content-type': 'application/json' },\n body: JSON.stringify({\n grant_type: 'authorization_code',\n code,\n redirect_uri: redirectUri,\n client_id: clientId,\n client_secret: clientSecret,\n }),\n });\n\n if (!res.ok) {\n const text = await res.text();\n let error;\n\n try {\n const json = JSON.parse(text);\n error = {\n error: json.error,\n errorDescription: json.error_description,\n message: `OAuth error: ${json.error || 'server_error'}`,\n };\n } catch (e) {\n error = {\n error: 'server_error',\n message: 'OAuth error: server_error',\n };\n }\n\n throw new InstantOAuthError(error);\n }\n\n const json = (await res.json()) as {\n access_token: string;\n refresh_token: string;\n expires_in: number;\n scopes: string;\n token_type: 'Bearer';\n };\n\n return {\n accessToken: json.access_token,\n expiresAt: new Date(Date.now() + (json.expires_in - 30) * 1000),\n refreshToken: json.refresh_token,\n scopes: json.scopes,\n tokenType: json.token_type,\n };\n}\n\nexport async function exchangeRefreshToken({\n clientId,\n clientSecret,\n refreshToken,\n apiURI = 'https://api.instantdb.com',\n}: {\n clientId: string;\n clientSecret: string;\n refreshToken: string;\n apiURI?: string;\n}): Promise<{\n accessToken: string;\n expiresAt: Date;\n scopes: string;\n tokenType: 'Bearer';\n}> {\n const res = await fetch(`${apiURI}/platform/oauth/token`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({\n grant_type: 'refresh_token',\n refresh_token: refreshToken,\n client_id: clientId,\n client_secret: clientSecret,\n }),\n });\n\n const json = (await res.json()) as {\n access_token: string;\n expires_in: number;\n scopes: string;\n token_type: 'Bearer';\n };\n\n return {\n accessToken: json.access_token,\n expiresAt: new Date((json.expires_in - 30) * 1000),\n scopes: json.scopes,\n tokenType: json.token_type,\n };\n}\n"]}
1
+ {"version":3,"file":"serverOAuth.js","sourceRoot":"","sources":["../../src/serverOAuth.ts"],"names":[],"mappings":";;AAEA,oDAmEC;AAED,oDAwCC;AA/GD,qDAAqD;AAE9C,KAAK,UAAU,oBAAoB,CAAC,EACzC,IAAI,EACJ,QAAQ,EACR,YAAY,EACZ,WAAW,EACX,MAAM,GAAG,2BAA2B,GAOrC;IAOC,MAAM,GAAG,GAAG,MAAM,KAAK,CAAC,GAAG,MAAM,uBAAuB,EAAE;QACxD,MAAM,EAAE,MAAM;QACd,OAAO,EAAE,EAAE,cAAc,EAAE,kBAAkB,EAAE;QAC/C,IAAI,EAAE,IAAI,CAAC,SAAS,CAAC;YACnB,UAAU,EAAE,oBAAoB;YAChC,IAAI;YACJ,YAAY,EAAE,WAAW;YACzB,SAAS,EAAE,QAAQ;YACnB,aAAa,EAAE,YAAY;SAC5B,CAAC;KACH,CAAC,CAAC;IAEH,IAAI,CAAC,GAAG,CAAC,EAAE,EAAE,CAAC;QACZ,MAAM,IAAI,GAAG,MAAM,GAAG,CAAC,IAAI,EAAE,CAAC;QAC9B,IAAI,KAAK,CAAC;QAEV,IAAI,CAAC;YACH,MAAM,IAAI,GAAG,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;YAC9B,KAAK,GAAG;gBACN,KAAK,EAAE,IAAI,CAAC,KAAK;gBACjB,gBAAgB,EAAE,IAAI,CAAC,iBAAiB;gBACxC,OAAO,EAA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AU,GAAG,EAAE,CAAC,GAAG,IAAI,CAAC;QAClD,MAAM,EAAE,IAAI,CAAC,MAAM;QACnB,SAAS,EAAE,IAAI,CAAC,UAAU;KAC3B,CAAC;AACJ,CAAC","sourcesContent":["import { InstantOAuthError } from './oauthCommon.ts';\n\nexport async function exchangeCodeForToken({\n code,\n clientId,\n clientSecret,\n redirectUri,\n apiURI = 'https://api.instantdb.com',\n}: {\n code: string;\n clientId: string;\n clientSecret: string;\n redirectUri: string;\n apiURI?: string;\n}): Promise<{\n accessToken: string;\n refreshToken: string;\n expiresAt: Date;\n scopes: string;\n tokenType: 'Bearer';\n}> {\n const res = await fetch(`${apiURI}/platform/oauth/token`, {\n method: 'POST',\n headers: { 'Content-type': 'application/json' },\n body: JSON.stringify({\n grant_type: 'authorization_code',\n code,\n redirect_uri: redirectUri,\n client_id: clientId,\n client_secret: clientSecret,\n }),\n });\n\n if (!res.ok) {\n const text = await res.text();\n let error;\n\n try {\n const json = JSON.parse(text);\n error = {\n error: json.error,\n errorDescription: json.error_description,\n message: `OAuth error: ${json.error || 'server_error'}`,\n };\n } catch (e) {\n error = {\n error: 'server_error',\n message: 'OAuth error: server_error',\n };\n }\n\n throw new InstantOAuthError(error);\n }\n\n const json = (await res.json()) as {\n access_token: string;\n refresh_token: string;\n expires_in: number;\n scopes: string;\n token_type: 'Bearer';\n };\n\n return {\n accessToken: json.access_token,\n expiresAt: new Date(Date.now() + (json.expires_in - 30) * 1000),\n refreshToken: json.refresh_token,\n scopes: json.scopes,\n tokenType: json.token_type,\n };\n}\n\nexport async function exchangeRefreshToken({\n clientId,\n clientSecret,\n refreshToken,\n apiURI = 'https://api.instantdb.com',\n}: {\n clientId: string;\n clientSecret: string;\n refreshToken: string;\n apiURI?: string;\n}): Promise<{\n accessToken: string;\n expiresAt: Date;\n scopes: string;\n tokenType: 'Bearer';\n}> {\n const res = await fetch(`${apiURI}/platform/oauth/token`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({\n grant_type: 'refresh_token',\n refresh_token: refreshToken,\n client_id: clientId,\n client_secret: clientSecret,\n }),\n });\n\n const json = (await res.json()) as {\n access_token: string;\n expires_in: number;\n scopes: string;\n token_type: 'Bearer';\n };\n\n return {\n accessToken: json.access_token,\n expiresAt: new Date((json.expires_in - 30) * 1000),\n scopes: json.scopes,\n tokenType: json.token_type,\n };\n}\n"]}
@@ -299,14 +299,13 @@ function astToSchemaDef(ast) {
299
299
  return core_1.i.schema({ entities, links, rooms });
300
300
  }
301
301
  function schemaTypescriptFileToInstantSchema(content, sourceFilename = 'instant.schema.ts') {
302
- var _a;
303
302
  const ast = (0, parser_1.parse)(content, {
304
303
  sourceFilename,
305
304
  sourceType: 'module',
306
305
  errorRecovery: false,
307
306
  plugins: ['typescript'],
308
307
  });
309
- if ((_a = ast.errors) === null || _a === void 0 ? void 0 : _a.length) {
308
+ if (ast.errors?.length) {
310
309
  throw new Error(`Could not parse schema file. ${ast.errors[0].reasonCode}.`);
311
310
  }
312
311
  return astToSchemaDef(ast);
@@ -1 +1 @@
1
- {"version":3,"file":"typescript-schema.js","sourceRoot":"","sources":["../../src/typescript-schema.ts"],"names":[],"mappings":";;AAqaA,kFAiBC;AAtbD,0CAAmE;AAgBnE,0CAA4D;AAU5D;;;;;;;GAOG;AACH,SAAS,SAAS,CAAC,IAAiB;IAClC,IAAI,CAAC,IAAI,EAAE,CAAC;QACV,OAAO,IAAI,CAAC;IACd,CAAC;IAED,QAAQ,IAAI,CAAC,IAAI,EAAE,CAAC;QAClB,KAAK,kBAAkB;YACrB,MAAM,OAAO,GAAG,IAAwB,CAAC;YACzC,OAAO,OAAO,CAAC,UAAU,CAAC,MAAM,CAC9B,CAAC,GAAiC,EAAE,IAAI,EAAE,EAAE;gBAC1C,IAAI,IAAI,CAAC,IAAI,KAAK,gBAAgB,EAAE,CAAC;oBACnC,MAAM,cAAc,GAAG,IAAsB,CAAC;oBAC9C,IAAI,GAAoB,CAAC;oBACzB,IAAI,cAAc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C,MAAM,CAAC,EAAE,QAAQ,EAAE,KAAK,EAAE,KAAK,EAAE,CAAC,CAAC;AAC9C,CAAC;AAED,SAAgB,mCAAmC,CACjD,OAAe,EACf,iBAAyB,mBAAmB;;IAE5C,MAAM,GAAG,GAAG,IAAA,cAAK,EAAC,OAAO,EAAE;QACzB,cAAc;QACd,UAAU,EAAE,QAAQ;QACpB,aAAa,EAAE,KAAK;QACpB,OAAO,EAAE,CAAC,YAAY,CAAC;KACxB,CAAC,CAAC;IACH,IAAI,MAAA,GAAG,CAAC,MAAM,0CAAE,MAAM,EAAE,CAAC;QACvB,MAAM,IAAI,KAAK,CACb,gCAAgC,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,UAAU,GAAG,CAC5D,CAAC;IACJ,CAAC;IAED,OAAO,cAAc,CAAC,GAAG,CAAC,CAAC;AAC7B,CAAC","sourcesContent":["import { parse, type ParseResult, type File } from '@babel/parser';\nimport type {\n CallExpression,\n ObjectExpression,\n ObjectProperty,\n Node,\n Expression,\n Identifier,\n StringLiteral,\n NumericLiteral,\n ArrayExpression,\n SpreadElement,\n BooleanLiteral,\n} from '@babel/types';\n\nimport { GenericSchemaDef } from './util.ts';\nimport { AttrsDefs, DataAttrDef, i } from '@instantdb/core';\n\ntype JsonValue =\n | string\n | number\n | boolean\n | null\n | JsonValue[]\n | { [key: string]: JsonValue };\n\n/**\n * Converts a Babel AST node into a JavaScript object/value,\n * suitable for JSON serialization.\n * Throws errors for unsupported AST structures.\n * @param {Node | null} node - The Babel AST node to convert.\n * @returns {JsonValue | null} The JavaScript representation.\n * @throws {Error} If the AST node or its structure is not convertible to JSON.\n */\nfunction astToJson(node: Node | null): JsonValue | null {\n if (!node) {\n return null;\n }\n\n switch (node.type) {\n case 'ObjectExpression':\n const objNode = node as ObjectExpression;\n return objNode.properties.reduce(\n (obj: { [key: string]: JsonValue }, prop) => {\n if (prop.type === 'ObjectProperty') {\n const objectProperty = prop as ObjectProperty;\n let key: string | number;\n if (objectProperty.key.type === 'Identifier') {\n key = (objectProperty.key as Identifier).name;\n } else if (\n objectProperty.key.type === 'StringLiteral' ||\n objectProperty.key.type === 'NumericLiteral'\n ) {\n key = (objectProperty.key as StringLiteral | NumericLiteral)\n .value;\n } else {\n throw new Error(\n `Unsupported key type in ObjectProperty: ${objectProperty.key.type}`,\n );\n }\n obj[key] = astToJson(objectProperty.value);\n } else if (\n prop.type !== 'SpreadElement' &&\n prop.type !== 'ObjectMethod'\n ) {\n throw new Error(\n // @ts-expect-error: prop is `never` here\n `Unsupported property type in ObjectExpression: ${prop.type}`,\n );\n }\n return obj;\n },\n {},\n );\n\n case 'ArrayExpression':\n const arrNode = node as ArrayExpression;\n return arrNode.elements\n .map((element) => {\n if (element && element.type === 'SpreadElement') {\n return undefined;\n }\n return astToJson(element as Expression | SpreadElement | null);\n })\n .filter((value) => value !== undefined) as JsonValue[];\n\n case 'ObjectProperty':\n const objPropNode = node as ObjectProperty;\n let objectPropertyKey: string | number;\n if (objPropNode.key.type === 'Identifier') {\n objectPropertyKey = (objPropNode.key as Identifier).name;\n } else if (\n objPropNode.key.type === 'StringLiteral' ||\n objPropNode.key.type === 'NumericLiteral'\n ) {\n objectPropertyKey = (objPropNode.key as StringLiteral | NumericLiteral)\n .value;\n } else {\n throw new Error(\n `Unsupported key type for standalone ObjectProperty: ${objPropNode.key.type}`,\n );\n }\n const newObj: { [key: string]: JsonValue } = {};\n newObj[objectPropertyKey] = astToJson(objPropNode.value);\n return newObj;\n\n case 'StringLiteral':\n case 'NumericLiteral':\n case 'BooleanLiteral':\n return (node as StringLiteral | NumericLiteral | BooleanLiteral).value;\n\n case 'NullLiteral':\n return null;\n\n default:\n throw new Error(\n `Unsupported AST node type for JSON conversion: ${node.type}`,\n );\n }\n}\n\nfunction keyName(property: ObjectProperty): string {\n switch (property.key.type) {\n case 'Identifier':\n return property.key.name;\n case 'StringLiteral':\n return property.key.value;\n default:\n throw new Error(\n `Could not extract entities, expected object key to be an \\`Identifier\\` or \\`StringLiteral\\`, got \\`${property.key.type}\\`.`,\n );\n }\n}\n\nfunction entityNodeToEntityDef(\n etype: string,\n node: ObjectExpression,\n): GenericSchemaDef['entities'][string] {\n const attrs: AttrsDefs = {};\n for (const property of node.properties) {\n if (property.type !== 'ObjectProperty') {\n throw new Error(\n `Expected i.entity for \\`${etype}\\` to contain only \\`ObjectProperty\\`, got \\`${property.type}\\`.`,\n );\n }\n const label = keyName(property);\n\n const props = [];\n\n if (property.value.type !== 'CallExpression') {\n throw new Error(\n `Could not extract \\`${etype}.${label}\\`. Expected a call to \\`i.string()\\`, \\`i.number()\\`, etc. Got something else.`,\n );\n }\n let next: CallExpression | null = property.value;\n if (label === 'path') {\n }\n let attrDef: DataAttrDef<string, boolean, boolean> | null = null;\n while (next) {\n if (\n next.callee.type !== 'MemberExpression' ||\n next.callee.property.type !== 'Identifier' ||\n !(\n next.callee.object.type === 'CallExpression' ||\n (next.callee.object.type === 'Identifier' &&\n next.callee.object.name === 'i')\n )\n ) {\n throw new Error(\n `Could not extract \\`${etype}.${label}\\`. Expected a call to \\`i.string()\\`, \\`i.number()\\`, etc. Got something else.`,\n );\n }\n\n if (next.callee.object.type === 'CallExpression') {\n props.push(next.callee.property.name);\n next = next.callee.object;\n } else {\n switch (next.callee.property.name) {\n case 'string': {\n attrDef = i.string();\n break;\n }\n case 'number': {\n attrDef = i.number();\n break;\n }\n case 'boolean': {\n attrDef = i.boolean();\n break;\n }\n case 'date': {\n attrDef = i.date();\n break;\n }\n case 'json': {\n attrDef = i.json();\n break;\n }\n case 'any': {\n attrDef = i.any();\n break;\n }\n }\n next = null;\n }\n }\n\n if (!attrDef) {\n throw new Error(\n `Could not extract \\`${etype}.${label}\\`. Found no call to \\`i.string()\\`, \\`i.number()\\`, etc.`,\n );\n }\n\n for (const prop of props.reverse()) {\n switch (prop) {\n case 'indexed': {\n attrDef = attrDef.indexed();\n break;\n }\n case 'unique': {\n attrDef = attrDef.unique();\n break;\n }\n case 'optional': {\n attrDef = attrDef.optional();\n break;\n }\n case 'clientRequired': {\n attrDef = attrDef.clientRequired();\n break;\n }\n default: {\n throw new Error(\n `Could not extract \\`${etype}.${label}\\`. Found a call to \\`${prop}()\\` that is not recognized.`,\n );\n }\n }\n }\n\n attrs[label] = attrDef;\n }\n\n return i.entity(attrs);\n}\n\nfunction entitiesNodeToEntitiesDef(\n node: ObjectExpression,\n): GenericSchemaDef['entities'] {\n const entities: GenericSchemaDef['entities'] = {};\n for (const property of node.properties) {\n if (property.type !== 'ObjectProperty') {\n throw new Error(\n `Expected entities to contain only \\`ObjectProperty\\`, got \\`${property.type}\\`.`,\n );\n }\n const etype = keyName(property);\n if (\n property.value.type !== 'CallExpression' ||\n property.value.callee.type !== 'MemberExpression' ||\n property.value.callee.object.type !== 'Identifier' ||\n property.value.callee.object.name !== 'i' ||\n property.value.arguments.length !== 1 ||\n property.value.arguments[0].type !== 'ObjectExpression'\n ) {\n throw new Error(\n `Could not extract entity \\`${etype}\\`. Expected a call to \\`i.entity()\\`, got something else.`,\n );\n }\n entities[etype] = entityNodeToEntityDef(etype, property.value.arguments[0]);\n }\n\n return entities;\n}\n\nfunction roomNodeToRoomDef(\n roomName: string,\n node: ObjectExpression,\n): GenericSchemaDef['rooms'][string] {\n let presence: GenericSchemaDef['rooms'][string]['presence'] | null = null;\n let topics: GenericSchemaDef['rooms'][string]['topics'] | undefined =\n undefined;\n for (const property of node.properties) {\n if (property.type !== 'ObjectProperty') {\n throw new Error(\n `Expected entities to contain only \\`ObjectProperty\\`, got \\`${property.type}\\`.`,\n );\n }\n const propName = keyName(property);\n switch (propName) {\n case 'topics': {\n if (property.value.type !== 'ObjectExpression') {\n throw new Error(\n `Could not exxtract \\`rooms.${roomName}.topics\\`. Expected an object, got \\`${property.value.type}\\`.`,\n );\n }\n topics = entitiesNodeToEntitiesDef(property.value);\n break;\n }\n case 'presence': {\n if (\n property.value.type !== 'CallExpression' ||\n property.value.callee.type !== 'MemberExpression' ||\n property.value.callee.object.type !== 'Identifier' ||\n property.value.callee.object.name !== 'i' ||\n property.value.arguments.length !== 1 ||\n property.value.arguments[0].type !== 'ObjectExpression'\n ) {\n throw new Error(\n `Could not extract \\`rooms.${roomName}.presence\\`. Expected a call to \\`i.entity()\\`, got something else.`,\n );\n }\n presence = entityNodeToEntityDef(roomName, property.value.arguments[0]);\n break;\n }\n default: {\n throw new Error(\n `Could not extract \\`rooms.${roomName}\\`. Unexpected property \\`${propName}\\`.`,\n );\n }\n }\n }\n if (!presence) {\n throw new Error(\n `Could not extract room ${roomName}, \\`presence\\` key was missing from room definition.`,\n );\n }\n return { presence, topics };\n}\n\nfunction roomsNodeToRoomsDef(\n node: ObjectExpression,\n): GenericSchemaDef['rooms'] {\n const rooms: GenericSchemaDef['rooms'] = {};\n for (const property of node.properties) {\n if (property.type !== 'ObjectProperty') {\n throw new Error(\n `Expected entities to contain only \\`ObjectProperty\\`, got \\`${property.type}\\`.`,\n );\n }\n\n const roomName = keyName(property);\n\n if (property.value.type !== 'ObjectExpression') {\n throw new Error(\n `Could not extract room \\`${roomName}\\`. Expected an object with topics and presence keys, got \\`${property.value.type}\\`.`,\n );\n }\n\n rooms[roomName] = roomNodeToRoomDef(roomName, property.value);\n }\n\n return rooms;\n}\n\nfunction astToSchemaDef(ast: ParseResult<File>): GenericSchemaDef {\n let entities: GenericSchemaDef['entities'] | null = null;\n let links = {};\n let rooms = {};\n\n for (const n of ast.program.body) {\n if (\n n.type !== 'VariableDeclaration' ||\n n.declarations.length !== 1 ||\n n.declarations[0].id.type !== 'Identifier' ||\n n.declarations[0].id.name !== '_schema'\n ) {\n continue;\n }\n\n const node = n.declarations[0];\n\n if (\n !node.init ||\n node.init.type !== 'CallExpression' ||\n node.init.callee.type !== 'MemberExpression' ||\n node.init.callee.object.type !== 'Identifier' ||\n node.init.callee.object.name !== 'i' ||\n node.init.arguments.length !== 1 ||\n node.init.arguments[0].type !== 'ObjectExpression'\n ) {\n throw new Error(\n `Could not extract schema. Expected a call to \\`i.schema()\\`, got something else.`,\n );\n }\n\n for (const property of node.init.arguments[0].properties) {\n if (property.type !== 'ObjectProperty') {\n throw new Error(\n `Could not extra schema property, expected an \\`ObjectProperty\\`, got \\`${property.type}\\'.`,\n );\n }\n const section = keyName(property);\n if (property.value.type !== 'ObjectExpression') {\n throw new Error(\n `Failed to extract ${section}, expected an \\`ObjectExpression\\`, got \\`${property.value.type}\\`.`,\n );\n }\n switch (keyName(property)) {\n case 'entities': {\n entities = entitiesNodeToEntitiesDef(property.value);\n break;\n }\n case 'links': {\n links = astToJson(property.value) || {};\n break;\n }\n case 'rooms': {\n rooms = roomsNodeToRoomsDef(property.value);\n break;\n }\n }\n }\n }\n\n if (!entities) {\n throw new Error('Could not extract schema, did not find any entities.');\n }\n\n return i.schema({ entities, links, rooms });\n}\n\nexport function schemaTypescriptFileToInstantSchema(\n content: string,\n sourceFilename: string = 'instant.schema.ts',\n): GenericSchemaDef {\n const ast = parse(content, {\n sourceFilename,\n sourceType: 'module',\n errorRecovery: false,\n plugins: ['typescript'],\n });\n if (ast.errors?.length) {\n throw new Error(\n `Could not parse schema file. ${ast.errors[0].reasonCode}.`,\n );\n }\n\n return astToSchemaDef(ast);\n}\n"]}
1
+ {"version":3,"file":"typescript-schema.js","sourceRoot":"","sources":["../../src/typescript-schema.ts"],"names":[],"mappings":";;AAqaA,kFAiBC;AAtbD,0CAAmE;AAgBnE,0CAA4D;AAU5D;;;;;;;GAOG;AACH,SAAS,SAAS,CAAC,IAAiB;IAClC,IAAI,CAAC,IAAI,EAAE,CAAC;QACV,OAAO,IAAI,CAAC;IACd,CAAC;IAED,QAAQ,IAAI,CAAC,IAAI,EAAE,CAAC;QAClB,KAAK,kBAAkB;YACrB,MAAM,OAAO,GAAG,IAAwB,CAAC;YACzC,OAAO,OAAO,CAAC,UAAU,CAAC,MAAM,CAC9B,CAAC,GAAiC,EAAE,IAAI,EAAE,EAAE;gBAC1C,IAAI,IAAI,CAAC,IAAI,KAAK,gBAAgB,EAAE,CAAC;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;QACd,MAAM,IAAI,KAAK,CAAC,sDAAsD,CAAC,CAAC;IAC1E,CAAC;IAED,OAAO,QAAC,CAAC,MAAM,CAAC,EAAE,QAAQ,EAAE,KAAK,EAAE,KAAK,EAAE,CAAC,CAAC;AAC9C,CAAC;AAED,SAAgB,mCAAmC,CACjD,OAAe,EACf,iBAAyB,mBAAmB;IAE5C,MAAM,GAAG,GAAG,IAAA,cAAK,EAAC,OAAO,EAAE;QACzB,cAAc;QACd,UAAU,EAAE,QAAQ;QACpB,aAAa,EAAE,KAAK;QACpB,OAAO,EAAE,CAAC,YAAY,CAAC;KACxB,CAAC,CAAC;IACH,IAAI,GAAG,CAAC,MAAM,EAAE,MAAM,EAAE,CAAC;QACvB,MAAM,IAAI,KAAK,CACb,gCAAgC,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,UAAU,GAAG,CAC5D,CAAC;IACJ,CAAC;IAED,OAAO,cAAc,CAAC,GAAG,CAAC,CAAC;AAC7B,CAAC","sourcesContent":["import { parse, type ParseResult, type File } from '@babel/parser';\nimport type {\n CallExpression,\n ObjectExpression,\n ObjectProperty,\n Node,\n Expression,\n Identifier,\n StringLiteral,\n NumericLiteral,\n ArrayExpression,\n SpreadElement,\n BooleanLiteral,\n} from '@babel/types';\n\nimport { GenericSchemaDef } from './util.ts';\nimport { AttrsDefs, DataAttrDef, i } from '@instantdb/core';\n\ntype JsonValue =\n | string\n | number\n | boolean\n | null\n | JsonValue[]\n | { [key: string]: JsonValue };\n\n/**\n * Converts a Babel AST node into a JavaScript object/value,\n * suitable for JSON serialization.\n * Throws errors for unsupported AST structures.\n * @param {Node | null} node - The Babel AST node to convert.\n * @returns {JsonValue | null} The JavaScript representation.\n * @throws {Error} If the AST node or its structure is not convertible to JSON.\n */\nfunction astToJson(node: Node | null): JsonValue | null {\n if (!node) {\n return null;\n }\n\n switch (node.type) {\n case 'ObjectExpression':\n const objNode = node as ObjectExpression;\n return objNode.properties.reduce(\n (obj: { [key: string]: JsonValue }, prop) => {\n if (prop.type === 'ObjectProperty') {\n const objectProperty = prop as ObjectProperty;\n let key: string | number;\n if (objectProperty.key.type === 'Identifier') {\n key = (objectProperty.key as Identifier).name;\n } else if (\n objectProperty.key.type === 'StringLiteral' ||\n objectProperty.key.type === 'NumericLiteral'\n ) {\n key = (objectProperty.key as StringLiteral | NumericLiteral)\n .value;\n } else {\n throw new Error(\n `Unsupported key type in ObjectProperty: ${objectProperty.key.type}`,\n );\n }\n obj[key] = astToJson(objectProperty.value);\n } else if (\n prop.type !== 'SpreadElement' &&\n prop.type !== 'ObjectMethod'\n ) {\n throw new Error(\n // @ts-expect-error: prop is `never` here\n `Unsupported property type in ObjectExpression: ${prop.type}`,\n );\n }\n return obj;\n },\n {},\n );\n\n case 'ArrayExpression':\n const arrNode = node as ArrayExpression;\n return arrNode.elements\n .map((element) => {\n if (element && element.type === 'SpreadElement') {\n return undefined;\n }\n return astToJson(element as Expression | SpreadElement | null);\n })\n .filter((value) => value !== undefined) as JsonValue[];\n\n case 'ObjectProperty':\n const objPropNode = node as ObjectProperty;\n let objectPropertyKey: string | number;\n if (objPropNode.key.type === 'Identifier') {\n objectPropertyKey = (objPropNode.key as Identifier).name;\n } else if (\n objPropNode.key.type === 'StringLiteral' ||\n objPropNode.key.type === 'NumericLiteral'\n ) {\n objectPropertyKey = (objPropNode.key as StringLiteral | NumericLiteral)\n .value;\n } else {\n throw new Error(\n `Unsupported key type for standalone ObjectProperty: ${objPropNode.key.type}`,\n );\n }\n const newObj: { [key: string]: JsonValue } = {};\n newObj[objectPropertyKey] = astToJson(objPropNode.value);\n return newObj;\n\n case 'StringLiteral':\n case 'NumericLiteral':\n case 'BooleanLiteral':\n return (node as StringLiteral | NumericLiteral | BooleanLiteral).value;\n\n case 'NullLiteral':\n return null;\n\n default:\n throw new Error(\n `Unsupported AST node type for JSON conversion: ${node.type}`,\n );\n }\n}\n\nfunction keyName(property: ObjectProperty): string {\n switch (property.key.type) {\n case 'Identifier':\n return property.key.name;\n case 'StringLiteral':\n return property.key.value;\n default:\n throw new Error(\n `Could not extract entities, expected object key to be an \\`Identifier\\` or \\`StringLiteral\\`, got \\`${property.key.type}\\`.`,\n );\n }\n}\n\nfunction entityNodeToEntityDef(\n etype: string,\n node: ObjectExpression,\n): GenericSchemaDef['entities'][string] {\n const attrs: AttrsDefs = {};\n for (const property of node.properties) {\n if (property.type !== 'ObjectProperty') {\n throw new Error(\n `Expected i.entity for \\`${etype}\\` to contain only \\`ObjectProperty\\`, got \\`${property.type}\\`.`,\n );\n }\n const label = keyName(property);\n\n const props = [];\n\n if (property.value.type !== 'CallExpression') {\n throw new Error(\n `Could not extract \\`${etype}.${label}\\`. Expected a call to \\`i.string()\\`, \\`i.number()\\`, etc. Got something else.`,\n );\n }\n let next: CallExpression | null = property.value;\n if (label === 'path') {\n }\n let attrDef: DataAttrDef<string, boolean, boolean> | null = null;\n while (next) {\n if (\n next.callee.type !== 'MemberExpression' ||\n next.callee.property.type !== 'Identifier' ||\n !(\n next.callee.object.type === 'CallExpression' ||\n (next.callee.object.type === 'Identifier' &&\n next.callee.object.name === 'i')\n )\n ) {\n throw new Error(\n `Could not extract \\`${etype}.${label}\\`. Expected a call to \\`i.string()\\`, \\`i.number()\\`, etc. Got something else.`,\n );\n }\n\n if (next.callee.object.type === 'CallExpression') {\n props.push(next.callee.property.name);\n next = next.callee.object;\n } else {\n switch (next.callee.property.name) {\n case 'string': {\n attrDef = i.string();\n break;\n }\n case 'number': {\n attrDef = i.number();\n break;\n }\n case 'boolean': {\n attrDef = i.boolean();\n break;\n }\n case 'date': {\n attrDef = i.date();\n break;\n }\n case 'json': {\n attrDef = i.json();\n break;\n }\n case 'any': {\n attrDef = i.any();\n break;\n }\n }\n next = null;\n }\n }\n\n if (!attrDef) {\n throw new Error(\n `Could not extract \\`${etype}.${label}\\`. Found no call to \\`i.string()\\`, \\`i.number()\\`, etc.`,\n );\n }\n\n for (const prop of props.reverse()) {\n switch (prop) {\n case 'indexed': {\n attrDef = attrDef.indexed();\n break;\n }\n case 'unique': {\n attrDef = attrDef.unique();\n break;\n }\n case 'optional': {\n attrDef = attrDef.optional();\n break;\n }\n case 'clientRequired': {\n attrDef = attrDef.clientRequired();\n break;\n }\n default: {\n throw new Error(\n `Could not extract \\`${etype}.${label}\\`. Found a call to \\`${prop}()\\` that is not recognized.`,\n );\n }\n }\n }\n\n attrs[label] = attrDef;\n }\n\n return i.entity(attrs);\n}\n\nfunction entitiesNodeToEntitiesDef(\n node: ObjectExpression,\n): GenericSchemaDef['entities'] {\n const entities: GenericSchemaDef['entities'] = {};\n for (const property of node.properties) {\n if (property.type !== 'ObjectProperty') {\n throw new Error(\n `Expected entities to contain only \\`ObjectProperty\\`, got \\`${property.type}\\`.`,\n );\n }\n const etype = keyName(property);\n if (\n property.value.type !== 'CallExpression' ||\n property.value.callee.type !== 'MemberExpression' ||\n property.value.callee.object.type !== 'Identifier' ||\n property.value.callee.object.name !== 'i' ||\n property.value.arguments.length !== 1 ||\n property.value.arguments[0].type !== 'ObjectExpression'\n ) {\n throw new Error(\n `Could not extract entity \\`${etype}\\`. Expected a call to \\`i.entity()\\`, got something else.`,\n );\n }\n entities[etype] = entityNodeToEntityDef(etype, property.value.arguments[0]);\n }\n\n return entities;\n}\n\nfunction roomNodeToRoomDef(\n roomName: string,\n node: ObjectExpression,\n): GenericSchemaDef['rooms'][string] {\n let presence: GenericSchemaDef['rooms'][string]['presence'] | null = null;\n let topics: GenericSchemaDef['rooms'][string]['topics'] | undefined =\n undefined;\n for (const property of node.properties) {\n if (property.type !== 'ObjectProperty') {\n throw new Error(\n `Expected entities to contain only \\`ObjectProperty\\`, got \\`${property.type}\\`.`,\n );\n }\n const propName = keyName(property);\n switch (propName) {\n case 'topics': {\n if (property.value.type !== 'ObjectExpression') {\n throw new Error(\n `Could not exxtract \\`rooms.${roomName}.topics\\`. Expected an object, got \\`${property.value.type}\\`.`,\n );\n }\n topics = entitiesNodeToEntitiesDef(property.value);\n break;\n }\n case 'presence': {\n if (\n property.value.type !== 'CallExpression' ||\n property.value.callee.type !== 'MemberExpression' ||\n property.value.callee.object.type !== 'Identifier' ||\n property.value.callee.object.name !== 'i' ||\n property.value.arguments.length !== 1 ||\n property.value.arguments[0].type !== 'ObjectExpression'\n ) {\n throw new Error(\n `Could not extract \\`rooms.${roomName}.presence\\`. Expected a call to \\`i.entity()\\`, got something else.`,\n );\n }\n presence = entityNodeToEntityDef(roomName, property.value.arguments[0]);\n break;\n }\n default: {\n throw new Error(\n `Could not extract \\`rooms.${roomName}\\`. Unexpected property \\`${propName}\\`.`,\n );\n }\n }\n }\n if (!presence) {\n throw new Error(\n `Could not extract room ${roomName}, \\`presence\\` key was missing from room definition.`,\n );\n }\n return { presence, topics };\n}\n\nfunction roomsNodeToRoomsDef(\n node: ObjectExpression,\n): GenericSchemaDef['rooms'] {\n const rooms: GenericSchemaDef['rooms'] = {};\n for (const property of node.properties) {\n if (property.type !== 'ObjectProperty') {\n throw new Error(\n `Expected entities to contain only \\`ObjectProperty\\`, got \\`${property.type}\\`.`,\n );\n }\n\n const roomName = keyName(property);\n\n if (property.value.type !== 'ObjectExpression') {\n throw new Error(\n `Could not extract room \\`${roomName}\\`. Expected an object with topics and presence keys, got \\`${property.value.type}\\`.`,\n );\n }\n\n rooms[roomName] = roomNodeToRoomDef(roomName, property.value);\n }\n\n return rooms;\n}\n\nfunction astToSchemaDef(ast: ParseResult<File>): GenericSchemaDef {\n let entities: GenericSchemaDef['entities'] | null = null;\n let links = {};\n let rooms = {};\n\n for (const n of ast.program.body) {\n if (\n n.type !== 'VariableDeclaration' ||\n n.declarations.length !== 1 ||\n n.declarations[0].id.type !== 'Identifier' ||\n n.declarations[0].id.name !== '_schema'\n ) {\n continue;\n }\n\n const node = n.declarations[0];\n\n if (\n !node.init ||\n node.init.type !== 'CallExpression' ||\n node.init.callee.type !== 'MemberExpression' ||\n node.init.callee.object.type !== 'Identifier' ||\n node.init.callee.object.name !== 'i' ||\n node.init.arguments.length !== 1 ||\n node.init.arguments[0].type !== 'ObjectExpression'\n ) {\n throw new Error(\n `Could not extract schema. Expected a call to \\`i.schema()\\`, got something else.`,\n );\n }\n\n for (const property of node.init.arguments[0].properties) {\n if (property.type !== 'ObjectProperty') {\n throw new Error(\n `Could not extra schema property, expected an \\`ObjectProperty\\`, got \\`${property.type}\\'.`,\n );\n }\n const section = keyName(property);\n if (property.value.type !== 'ObjectExpression') {\n throw new Error(\n `Failed to extract ${section}, expected an \\`ObjectExpression\\`, got \\`${property.value.type}\\`.`,\n );\n }\n switch (keyName(property)) {\n case 'entities': {\n entities = entitiesNodeToEntitiesDef(property.value);\n break;\n }\n case 'links': {\n links = astToJson(property.value) || {};\n break;\n }\n case 'rooms': {\n rooms = roomsNodeToRoomsDef(property.value);\n break;\n }\n }\n }\n }\n\n if (!entities) {\n throw new Error('Could not extract schema, did not find any entities.');\n }\n\n return i.schema({ entities, links, rooms });\n}\n\nexport function schemaTypescriptFileToInstantSchema(\n content: string,\n sourceFilename: string = 'instant.schema.ts',\n): GenericSchemaDef {\n const ast = parse(content, {\n sourceFilename,\n sourceType: 'module',\n errorRecovery: false,\n plugins: ['typescript'],\n });\n if (ast.errors?.length) {\n throw new Error(\n `Could not parse schema file. ${ast.errors[0].reasonCode}.`,\n );\n }\n\n return astToSchemaDef(ast);\n}\n"]}
@@ -42,7 +42,7 @@ function inferredType(attr) {
42
42
  return null;
43
43
  }
44
44
  const inferredList = attr['inferred-types'];
45
- const hasJustOne = (inferredList === null || inferredList === void 0 ? void 0 : inferredList.length) === 1;
45
+ const hasJustOne = inferredList?.length === 1;
46
46
  if (!hasJustOne) {
47
47
  return null;
48
48
  }
@@ -1 +1 @@
1
- {"version":3,"file":"util.js","sourceRoot":"","sources":["../../src/util.ts"],"names":[],"mappings":";;;AAYA,sCAEC;AAED,sDAEC;AASD,kCASC;AAED,kDAUC;AAED,oCAaC;AAED,4CAkBC;AAED,8BASC;AAlFD,SAAgB,aAAa,CAAI,CAAoB;IACnD,OAAO,MA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C,IAAI,IAAI,CAAC,OAAO,KAAK,QAAQ,EAAE,CAAC;QAC9B,OAAO,IAAI,CAAC;IACd,CAAC;IAED,MAAM,YAAY,GAAG,IAAI,CAAC,gBAAgB,CAAC,CAAC;IAC5C,MAAM,UAAU,GAAG,CAAA,YAAY,aAAZ,YAAY,uBAAZ,YAAY,CAAE,MAAM,MAAK,CAAC,CAAC;IAE9C,IAAI,CAAC,UAAU,EAAE,CAAC;QAChB,OAAO,IAAI,CAAC;IACd,CAAC;IAED,OAAO,YAAY,CAAC,CAAC,CAAC,CAAC;AACzB,CAAC;AAED,SAAgB,gBAAgB,CAC9B,IAAmB,EACnB,oBAA8B;IAK9B,IAAI,IAAI,CAAC,mBAAmB,CAAC,EAAE,CAAC;QAC9B,OAAO,EAAE,IAAI,EAAE,IAAI,CAAC,mBAAmB,CAAC,EAAE,MAAM,EAAE,SAAS,EAAE,CAAC;IAChE,CAAC;IAED,MAAM,QAAQ,GAAG,YAAY,CAAC,IAAI,CAAC,CAAC;IAEpC,IAAI,QAAQ,IAAI,CAAC,oBAAoB,EAAE,CAAC;QACtC,OAAO,EAAE,IAAI,EAAE,QAAQ,EAAE,MAAM,EAAE,UAAU,EAAE,CAAC;IAChD,CAAC;IAED,OAAO,EAAE,IAAI,EAAE,KAAK,EAAE,MAAM,EAAE,SAAS,EAAE,CAAC;AAC5C,CAAC;AAED,SAAgB,SAAS,CAAC,GAAW;IACnC,OAAO,IAAI,GAAG,GAAG,CAAC;IAClB,wEAAwE;IACxE,4EAA4E;IAC5E,qEAAqE;IACrE,gDAAgD;IAChD,gBAAgB;IAChB,IAAI;IACJ,qBAAqB;AACvB,CAAC","sourcesContent":["import {\n AttrsDefs,\n CardinalityKind,\n EntityDef,\n InstantDBAttr,\n InstantDBCheckedDataType,\n InstantDBInferredType,\n InstantSchemaDef,\n LinksDef,\n RoomsDef,\n} from '@instantdb/core';\n\nexport function sortedEntries<T>(o: Record<string, T>): [string, T][] {\n return Object.entries(o).sort(([a], [b]) => a.localeCompare(b));\n}\n\nexport function capitalizeFirstLetter(string: string): string {\n return string.charAt(0).toUpperCase() + string.slice(1);\n}\n\nexport const rels: Record<string, CardinalityKind[]> = {\n 'many-false': ['many', 'many'],\n 'one-true': ['one', 'one'],\n 'many-true': ['many', 'one'],\n 'one-false': ['one', 'many'],\n};\n\nexport function indentLines(s: string, n = 2) {\n if (!s) {\n return s;\n }\n const space = ' '.repeat(n);\n return s\n .split('\\n')\n .map((l) => `${space}${l}`)\n .join('\\n');\n}\n\nexport function joinWithTrailingSep(\n arr: string[],\n sep: string,\n trailingSep: string = sep,\n): string {\n const s = arr.join(sep);\n if (arr.length) {\n return s + trailingSep;\n }\n return s;\n}\n\nexport function inferredType(attr: InstantDBAttr) {\n if (attr.catalog === 'system') {\n return null;\n }\n\n const inferredList = attr['inferred-types'];\n const hasJustOne = inferredList?.length === 1;\n\n if (!hasJustOne) {\n return null;\n }\n\n return inferredList[0];\n}\n\nexport function deriveClientType(\n attr: InstantDBAttr,\n disableTypeInference?: boolean,\n): {\n type: InstantDBCheckedDataType | InstantDBInferredType | 'any';\n origin: 'checked' | 'inferred' | 'unknown';\n} {\n if (attr['checked-data-type']) {\n return { type: attr['checked-data-type'], origin: 'checked' };\n }\n\n const inferred = inferredType(attr);\n\n if (inferred && !disableTypeInference) {\n return { type: inferred, origin: 'inferred' };\n }\n\n return { type: 'any', origin: 'unknown' };\n}\n\nexport function formatKey(key: string) {\n return `\"${key}\"`;\n // It would be nice to generate unquoted keys, but we use JSON.stringify\n // for some things so we can't be consistent with it unless we write our own\n // stringify function. If we do, here's the code for formatting keys:\n // if (/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(key)) {\n // return key;\n // }\n // return `\"${key}\"`;\n}\n\nexport type GenericSchemaDef = InstantSchemaDef<\n Record<string, EntityDef<AttrsDefs, any, any>>,\n LinksDef<Record<string, EntityDef<AttrsDefs, any, any>>>,\n RoomsDef\n>;\n"]}
1
+ {"version":3,"file":"util.js","sourceRoot":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ataType,\n InstantDBInferredType,\n InstantSchemaDef,\n LinksDef,\n RoomsDef,\n} from '@instantdb/core';\n\nexport function sortedEntries<T>(o: Record<string, T>): [string, T][] {\n return Object.entries(o).sort(([a], [b]) => a.localeCompare(b));\n}\n\nexport function capitalizeFirstLetter(string: string): string {\n return string.charAt(0).toUpperCase() + string.slice(1);\n}\n\nexport const rels: Record<string, CardinalityKind[]> = {\n 'many-false': ['many', 'many'],\n 'one-true': ['one', 'one'],\n 'many-true': ['many', 'one'],\n 'one-false': ['one', 'many'],\n};\n\nexport function indentLines(s: string, n = 2) {\n if (!s) {\n return s;\n }\n const space = ' '.repeat(n);\n return s\n .split('\\n')\n .map((l) => `${space}${l}`)\n .join('\\n');\n}\n\nexport function joinWithTrailingSep(\n arr: string[],\n sep: string,\n trailingSep: string = sep,\n): string {\n const s = arr.join(sep);\n if (arr.length) {\n return s + trailingSep;\n }\n return s;\n}\n\nexport function inferredType(attr: InstantDBAttr) {\n if (attr.catalog === 'system') {\n return null;\n }\n\n const inferredList = attr['inferred-types'];\n const hasJustOne = inferredList?.length === 1;\n\n if (!hasJustOne) {\n return null;\n }\n\n return inferredList[0];\n}\n\nexport function deriveClientType(\n attr: InstantDBAttr,\n disableTypeInference?: boolean,\n): {\n type: InstantDBCheckedDataType | InstantDBInferredType | 'any';\n origin: 'checked' | 'inferred' | 'unknown';\n} {\n if (attr['checked-data-type']) {\n return { type: attr['checked-data-type'], origin: 'checked' };\n }\n\n const inferred = inferredType(attr);\n\n if (inferred && !disableTypeInference) {\n return { type: inferred, origin: 'inferred' };\n }\n\n return { type: 'any', origin: 'unknown' };\n}\n\nexport function formatKey(key: string) {\n return `\"${key}\"`;\n // It would be nice to generate unquoted keys, but we use JSON.stringify\n // for some things so we can't be consistent with it unless we write our own\n // stringify function. If we do, here's the code for formatting keys:\n // if (/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(key)) {\n // return key;\n // }\n // return `\"${key}\"`;\n}\n\nexport type GenericSchemaDef = InstantSchemaDef<\n Record<string, EntityDef<AttrsDefs, any, any>>,\n LinksDef<Record<string, EntityDef<AttrsDefs, any, any>>>,\n RoomsDef\n>;\n"]}
@@ -1,74 +1,62 @@
1
- var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
2
- if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
3
- if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
4
- return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
5
- };
6
- var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
7
- if (kind === "m") throw new TypeError("Private method is not writable");
8
- if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
9
- if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
10
- return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
11
- };
12
- var _ProgressPromise_observers, _ProgressPromise_result, _ProgressPromise_onNext, _ProgressPromise_onError, _ProgressPromise_onComplete;
13
1
  export class ProgressPromise {
2
+ #observers = [];
3
+ #result = null;
14
4
  constructor(callbackFn) {
15
- _ProgressPromise_observers.set(this, []);
16
- _ProgressPromise_result.set(this, null);
17
- _ProgressPromise_onNext.set(this, (status) => {
18
- if (__classPrivateFieldGet(this, _ProgressPromise_result, "f")) {
19
- return;
20
- }
21
- for (const observer of __classPrivateFieldGet(this, _ProgressPromise_observers, "f")) {
22
- try {
23
- observer.next && observer.next(status);
24
- }
25
- catch (_e) { }
26
- }
27
- });
28
- _ProgressPromise_onError.set(this, (error) => {
29
- if (__classPrivateFieldGet(this, _ProgressPromise_result, "f")) {
30
- return;
31
- }
32
- __classPrivateFieldSet(this, _ProgressPromise_result, { type: 'error', error }, "f");
33
- for (const observer of __classPrivateFieldGet(this, _ProgressPromise_observers, "f")) {
34
- try {
35
- observer.error && observer.error(error);
36
- }
37
- catch (_e) { }
5
+ callbackFn(this.#onNext, this.#onComplete, this.#onError);
6
+ }
7
+ #onNext = (status) => {
8
+ if (this.#result) {
9
+ return;
10
+ }
11
+ for (const observer of this.#observers) {
12
+ try {
13
+ observer.next && observer.next(status);
38
14
  }
39
- __classPrivateFieldSet(this, _ProgressPromise_observers, [], "f");
40
- });
41
- _ProgressPromise_onComplete.set(this, (result) => {
42
- if (__classPrivateFieldGet(this, _ProgressPromise_result, "f")) {
43
- return;
15
+ catch (_e) { }
16
+ }
17
+ };
18
+ #onError = (error) => {
19
+ if (this.#result) {
20
+ return;
21
+ }
22
+ this.#result = { type: 'error', error };
23
+ for (const observer of this.#observers) {
24
+ try {
25
+ observer.error && observer.error(error);
44
26
  }
45
- __classPrivateFieldSet(this, _ProgressPromise_result, { type: 'complete', result }, "f");
46
- for (const observer of __classPrivateFieldGet(this, _ProgressPromise_observers, "f")) {
47
- try {
48
- observer.complete && observer.complete(result);
49
- }
50
- catch (_e) { }
27
+ catch (_e) { }
28
+ }
29
+ this.#observers = [];
30
+ };
31
+ #onComplete = (result) => {
32
+ if (this.#result) {
33
+ return;
34
+ }
35
+ this.#result = { type: 'complete', result };
36
+ for (const observer of this.#observers) {
37
+ try {
38
+ observer.complete && observer.complete(result);
51
39
  }
52
- __classPrivateFieldSet(this, _ProgressPromise_observers, [], "f");
53
- });
54
- callbackFn(__classPrivateFieldGet(this, _ProgressPromise_onNext, "f"), __classPrivateFieldGet(this, _ProgressPromise_onComplete, "f"), __classPrivateFieldGet(this, _ProgressPromise_onError, "f"));
55
- }
40
+ catch (_e) { }
41
+ }
42
+ this.#observers = [];
43
+ };
56
44
  subscribe(observer) {
57
- if (__classPrivateFieldGet(this, _ProgressPromise_result, "f")) {
45
+ if (this.#result) {
58
46
  const ret = { unsubscribe: () => null };
59
- if (__classPrivateFieldGet(this, _ProgressPromise_result, "f").type === 'error') {
60
- observer.error && observer.error(__classPrivateFieldGet(this, _ProgressPromise_result, "f").error);
47
+ if (this.#result.type === 'error') {
48
+ observer.error && observer.error(this.#result.error);
61
49
  return ret;
62
50
  }
63
- else if (__classPrivateFieldGet(this, _ProgressPromise_result, "f").type === 'complete') {
64
- observer.complete && observer.complete(__classPrivateFieldGet(this, _ProgressPromise_result, "f").result);
51
+ else if (this.#result.type === 'complete') {
52
+ observer.complete && observer.complete(this.#result.result);
65
53
  return ret;
66
54
  }
67
55
  }
68
- __classPrivateFieldGet(this, _ProgressPromise_observers, "f").push(observer);
56
+ this.#observers.push(observer);
69
57
  return {
70
58
  unsubscribe: () => {
71
- __classPrivateFieldSet(this, _ProgressPromise_observers, __classPrivateFieldGet(this, _ProgressPromise_observers, "f").filter((o) => o !== observer), "f");
59
+ this.#observers = this.#observers.filter((o) => o !== observer);
72
60
  },
73
61
  };
74
62
  }
@@ -82,5 +70,4 @@ export class ProgressPromise {
82
70
  this.subscribe({ error: () => cb(), complete: () => cb() });
83
71
  }
84
72
  }
85
- _ProgressPromise_observers = new WeakMap(), _ProgressPromise_result = new WeakMap(), _ProgressPromise_onNext = new WeakMap(), _ProgressPromise_onError = new WeakMap(), _ProgressPromise_onComplete = new WeakMap();
86
73
  //# sourceMappingURL=ProgressPromise.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"ProgressPromise.js","sourceRoot":"","sources":["../../src/ProgressPromise.ts"],"names":[],"mappings":";;;;;;;;;;;;AAgBA,MAAM,OAAO,eAAe;IAO1B,YAAY,UAAwD;QANpE,qCAA0D,EAAE,EAAC;QAC7D,kCAG4C,IAAI,EAAC;QAMjD,kCAAU,CAAC,MAAe,EAAE,EAAE;YAC5B,IAAI,uBAAA,IAAI,+BAAQ,EAAE,CAAC;gBACjB,OAAO;YACT,CAAC;YACD,KAAK,MAAM,QAAQ,IAAI,uBAAA,IAAI,kCAAW,EAAE,CAAC;gBACvC,IAAI,CAAC;oBACH,QAAQ,CAAC,IAAI,IAAI,QAAQ,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;g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Content":["export type ProgressPromiseSubscription = {\n unsubscribe: () => void;\n};\n\nexport type ProgressPromiseObserver<StatusT, ResultT> = {\n next?: (t: StatusT) => void;\n error?: (error: Error) => void;\n complete?: (t: ResultT) => void;\n};\n\nexport type ProgressPromiseConstructor<StatusT, ResultT> = (\n progress: (status: StatusT) => void,\n resolve: (result: ResultT) => void,\n reject: (error: Error) => void,\n) => void;\n\nexport class ProgressPromise<StatusT, ResultT> {\n #observers: ProgressPromiseObserver<StatusT, ResultT>[] = [];\n #result:\n | null\n | { type: 'error'; error: Error }\n | { type: 'complete'; result: ResultT } = null;\n\n constructor(callbackFn: ProgressPromiseConstructor<StatusT, ResultT>) {\n callbackFn(this.#onNext, this.#onComplete, this.#onError);\n }\n\n #onNext = (status: StatusT) => {\n if (this.#result) {\n return;\n }\n for (const observer of this.#observers) {\n try {\n observer.next && observer.next(status);\n } catch (_e) {}\n }\n };\n\n #onError = (error: Error) => {\n if (this.#result) {\n return;\n }\n this.#result = { type: 'error', error };\n for (const observer of this.#observers) {\n try {\n observer.error && observer.error(error);\n } catch (_e) {}\n }\n this.#observers = [];\n };\n\n #onComplete = (result: ResultT) => {\n if (this.#result) {\n return;\n }\n this.#result = { type: 'complete', result };\n for (const observer of this.#observers) {\n try {\n observer.complete && observer.complete(result);\n } catch (_e) {}\n }\n this.#observers = [];\n };\n\n subscribe(\n observer: ProgressPromiseObserver<StatusT, ResultT>,\n ): ProgressPromiseSubscription {\n if (this.#result) {\n const ret = { unsubscribe: () => null };\n if (this.#result.type === 'error') {\n observer.error && observer.error(this.#result.error);\n return ret;\n } else if (this.#result.type === 'complete') {\n observer.complete && observer.complete(this.#result.result);\n return ret;\n }\n }\n this.#observers.push(observer);\n return {\n unsubscribe: () => {\n this.#observers = this.#observers.filter((o) => o !== observer);\n },\n };\n }\n\n then(resolve: (result: ResultT) => void, reject: (error: Error) => void) {\n this.subscribe({ error: reject, complete: resolve });\n }\n\n catch(cb: (error: Error) => void) {\n this.subscribe({ error: cb });\n }\n\n finally(cb: () => void) {\n this.subscribe({ error: () => cb(), complete: () => cb() });\n }\n}\n"]}
1
+ {"version":3,"file":"ProgressPromise.js","sourceRoot":"","sources":["../../src/ProgressPromise.ts"],"names":[],"mappings":"AAgBA,MAAM,OAAO,eAAe;IAC1B,UAAU,GAAgD,EAAE,CAAC;IAC7D,OAAO,GAGqC,IAAI,CAAC;IAEjD,YAAY,UAAwD;QAClE,UAAU,CAAC,IAAI,CAAC,OAAO,EAAE,IAAI,CAAC,WAAW,EAAE,IAAI,CAAC,QAAQ,CAAC,CAAC;IAC5D,CAAC;IAED,OAAO,GAAG,CAAC,MAAe,EAAE,EAAE;QAC5B,IAAI,IAAI,CAAC,OAAO,EAAE,CAAC;YACjB,OAAO;QACT,CAAC;QACD,KAAK,MAAM,QAAQ,IAAI,IAAI,CAAC,UAAU,EAAE,CAAC;YACvC,IAAI,CAAC;gBACH,QAAQ,CAAC,IAAI,IAAI,QAAQ,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;YACzC,CAAC;YAAC,OAAO,EAAE,EAAE,CAAC,CAAA,CAAC;QACjB,CAAC;IACH,CAAC,CAAC;IAEF,QAAQ,GAAG,CAAC,KAAY,EAAE,EAAE;QAC1B,IAAI,IAAI,CAAC,OAAO,EAAE,CAAC;YACjB,OAAO;QACT,CAAC;QACD,IAAI,CAAC,OAAO,GAAG,EAAE,IAAI,EAAE,OAAO,EAAE,KAAK,EAAE,CAAC;QACxC,KAAK,MAAM,QAAQ,IAAI,IAAI,CAAC,UAAU,EAAE,CAAC;YACvC,IAAI,CAAC;gBACH,QAAQ,CAAC,KAAK,IAAI,QAAQ,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;YAC1C,CAAC;YAAC,OAAO,EAAE,EAAE,CAAC,CAAA,CAAC;QACjB,CAAC;QACD,IAAI,CAAC,UAAU,GAAG,EAAE,CAAC;IACvB,CAAC,CAAC;IAEF,WAAW,GAAG,CAAC,MAAe,EAAE,EAAE;QAChC,IAAI,IA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ACJ,CAAC;IAED,IAAI,CAAC,OAAkC,EAAE,MAA8B;QACrE,IAAI,CAAC,SAAS,CAAC,EAAE,KAAK,EAAE,MAAM,EAAE,QAAQ,EAAE,OAAO,EAAE,CAAC,CAAC;IACvD,CAAC;IAED,KAAK,CAAC,EAA0B;QAC9B,IAAI,CAAC,SAAS,CAAC,EAAE,KAAK,EAAE,EAAE,EAAE,CAAC,CAAC;IAChC,CAAC;IAED,OAAO,CAAC,EAAc;QACpB,IAAI,CAAC,SAAS,CAAC,EAAE,KAAK,EAAE,GAAG,EAAE,CAAC,EAAE,EAAE,EAAE,QAAQ,EAAE,GAAG,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC,CAAC;IAC9D,CAAC;CACF","sourcesContent":["export type ProgressPromiseSubscription = {\n unsubscribe: () => void;\n};\n\nexport type ProgressPromiseObserver<StatusT, ResultT> = {\n next?: (t: StatusT) => void;\n error?: (error: Error) => void;\n complete?: (t: ResultT) => void;\n};\n\nexport type ProgressPromiseConstructor<StatusT, ResultT> = (\n progress: (status: StatusT) => void,\n resolve: (result: ResultT) => void,\n reject: (error: Error) => void,\n) => void;\n\nexport class ProgressPromise<StatusT, ResultT> {\n #observers: ProgressPromiseObserver<StatusT, ResultT>[] = [];\n #result:\n | null\n | { type: 'error'; error: Error }\n | { type: 'complete'; result: ResultT } = null;\n\n constructor(callbackFn: ProgressPromiseConstructor<StatusT, ResultT>) {\n callbackFn(this.#onNext, this.#onComplete, this.#onError);\n }\n\n #onNext = (status: StatusT) => {\n if (this.#result) {\n return;\n }\n for (const observer of this.#observers) {\n try {\n observer.next && observer.next(status);\n } catch (_e) {}\n }\n };\n\n #onError = (error: Error) => {\n if (this.#result) {\n return;\n }\n this.#result = { type: 'error', error };\n for (const observer of this.#observers) {\n try {\n observer.error && observer.error(error);\n } catch (_e) {}\n }\n this.#observers = [];\n };\n\n #onComplete = (result: ResultT) => {\n if (this.#result) {\n return;\n }\n this.#result = { type: 'complete', result };\n for (const observer of this.#observers) {\n try {\n observer.complete && observer.complete(result);\n } catch (_e) {}\n }\n this.#observers = [];\n };\n\n subscribe(\n observer: ProgressPromiseObserver<StatusT, ResultT>,\n ): ProgressPromiseSubscription {\n if (this.#result) {\n const ret = { unsubscribe: () => null };\n if (this.#result.type === 'error') {\n observer.error && observer.error(this.#result.error);\n return ret;\n } else if (this.#result.type === 'complete') {\n observer.complete && observer.complete(this.#result.result);\n return ret;\n }\n }\n this.#observers.push(observer);\n return {\n unsubscribe: () => {\n this.#observers = this.#observers.filter((o) => o !== observer);\n },\n };\n }\n\n then(resolve: (result: ResultT) => void, reject: (error: Error) => void) {\n this.subscribe({ error: reject, complete: resolve });\n }\n\n catch(cb: (error: Error) => void) {\n this.subscribe({ error: cb });\n }\n\n finally(cb: () => void) {\n this.subscribe({ error: () => cb(), complete: () => cb() });\n }\n}\n"]}