@tearleads/client-sdk 0.1.59 → 0.1.60
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/Tearleads.d.ts +15 -15
- package/Tearleads.js +14 -14
- package/Tearleads.js.map +1 -1
- package/client/{blobs.d.ts → blobs/index.d.ts} +1 -1
- package/client/{blobs.js → blobs/index.js} +3 -3
- package/client/blobs/index.js.map +1 -0
- package/client/{containerDocumentDiscovery.js → containerContents/documentDiscovery.js} +11 -11
- package/client/containerContents/documentDiscovery.js.map +1 -0
- package/client/{containerContents.d.ts → containerContents/index.d.ts} +13 -13
- package/client/{containerContents.js → containerContents/index.js} +18 -18
- package/client/containerContents/index.js.map +1 -0
- package/client/{containerContentsTypes.d.ts → containerContents/types.d.ts} +14 -14
- package/client/containerContents/types.js +2 -0
- package/client/containerContents/types.js.map +1 -0
- package/client/{deviceFirst.d.ts → deviceFirst/index.d.ts} +7 -7
- package/client/{deviceFirst.js → deviceFirst/index.js} +11 -11
- package/client/deviceFirst/index.js.map +1 -0
- package/client/{reconciledDocumentContentPull.js → deviceFirst/reconciledDocumentContentPull.js} +1 -1
- package/client/deviceFirst/reconciledDocumentContentPull.js.map +1 -0
- package/client/{documents.d.ts → documents/index.d.ts} +5 -5
- package/client/{documents.js → documents/index.js} +5 -5
- package/client/documents/index.js.map +1 -0
- package/client/{identity.d.ts → identity/index.d.ts} +2 -2
- package/client/{identity.js → identity/index.js} +5 -5
- package/client/identity/index.js.map +1 -0
- package/client/{identityKeyPackage.d.ts → identity/keyPackage.d.ts} +1 -1
- package/client/{identityKeyPackage.js → identity/keyPackage.js} +4 -4
- package/client/identity/keyPackage.js.map +1 -0
- package/client/{userIdentities.d.ts → identity/userIdentities.d.ts} +2 -2
- package/client/{userIdentities.js → identity/userIdentities.js} +4 -4
- package/client/identity/userIdentities.js.map +1 -0
- package/client/index.d.ts +17 -17
- package/client/index.js +8 -8
- package/client/index.js.map +1 -1
- package/client/organizations/currentPrincipalMutations.js.map +1 -1
- package/client/organizations/index.d.ts +2 -2
- package/client/organizations/index.js.map +1 -1
- package/client/organizations/organizationDataUsage.d.ts +1 -1
- package/client/organizations/organizationDataUsage.js.map +1 -1
- package/client/organizations/organizationGroupNameHydration.js.map +1 -1
- package/client/organizations/organizationGroupPresentation.d.ts +1 -1
- package/client/organizations/organizationGroupPresentation.js.map +1 -1
- package/client/organizations/organizationReadModels.d.ts +1 -1
- package/client/organizations/organizationReadModels.js.map +1 -1
- package/client/organizations/organizationWorkflowRuntime.js.map +1 -1
- package/client/organizations/organizationsTypes.d.ts +1 -1
- package/client/organizations/organizationsTypes.js.map +1 -1
- package/client/organizations/principalContainerMutations.js.map +1 -1
- package/client/organizations/principalMutationRecovery.d.ts +1 -1
- package/client/organizations/principalMutationRecovery.js.map +1 -1
- package/client/organizations/principalMutationScope.js.map +1 -1
- package/client/organizations/principalMutations.d.ts +2 -2
- package/client/organizations/principalMutations.js.map +1 -1
- package/client/root/index.d.ts +1 -1
- package/client/root/index.js.map +1 -1
- package/client/{database.d.ts → runtime/database.d.ts} +1 -1
- package/client/{database.js → runtime/database.js} +1 -1
- package/client/runtime/database.js.map +1 -0
- package/client/{principalHistoryProtection.d.ts → runtime/principalHistoryProtection.d.ts} +1 -1
- package/client/{principalHistoryProtection.js → runtime/principalHistoryProtection.js} +2 -2
- package/client/runtime/principalHistoryProtection.js.map +1 -0
- package/client/{principalMutationApi.d.ts → runtime/principalMutationApi.d.ts} +4 -4
- package/client/{principalMutationApi.js → runtime/principalMutationApi.js} +2 -2
- package/client/runtime/principalMutationApi.js.map +1 -0
- package/client/{principalMutationDispatch.js → runtime/principalMutationDispatch.js} +2 -2
- package/client/runtime/principalMutationDispatch.js.map +1 -0
- package/client/runtime/rootContainerAdoption.js.map +1 -0
- package/client/{workflowRuntime.d.ts → runtime/workflowRuntime.d.ts} +12 -12
- package/client/{workflowRuntime.js → runtime/workflowRuntime.js} +5 -5
- package/client/runtime/workflowRuntime.js.map +1 -0
- package/client/{securityIncidents.d.ts → securityIncidents/index.d.ts} +3 -3
- package/client/{securityIncidents.js → securityIncidents/index.js} +5 -5
- package/client/securityIncidents/index.js.map +1 -0
- package/client/session/index.js +1 -1
- package/client/session/index.js.map +1 -1
- package/client/session/sessionIdentityTrust.d.ts +1 -1
- package/client/session/sessionOrganizationCreation.js.map +1 -1
- package/client/session/sessionPurgeRecovery.js.map +1 -1
- package/client/session/sessionTypes.d.ts +2 -2
- package/client/session/sessionTypes.js.map +1 -1
- package/package.json +1 -1
- package/client/blobs.js.map +0 -1
- package/client/containerContents.js.map +0 -1
- package/client/containerContentsTypes.js +0 -2
- package/client/containerContentsTypes.js.map +0 -1
- package/client/containerDocumentDiscovery.js.map +0 -1
- package/client/database.js.map +0 -1
- package/client/deviceFirst.js.map +0 -1
- package/client/documents.js.map +0 -1
- package/client/identity.js.map +0 -1
- package/client/identityKeyPackage.js.map +0 -1
- package/client/principalHistoryProtection.js.map +0 -1
- package/client/principalMutationApi.js.map +0 -1
- package/client/principalMutationDispatch.js.map +0 -1
- package/client/reconciledDocumentContentPull.js.map +0 -1
- package/client/rootContainerAdoption.js.map +0 -1
- package/client/securityIncidents.js.map +0 -1
- package/client/userIdentities.js.map +0 -1
- package/client/workflowRuntime.js.map +0 -1
- /package/client/{fileSaver.d.ts → host/fileSaver.d.ts} +0 -0
- /package/client/{fileSaver.js → host/fileSaver.js} +0 -0
- /package/client/{fileSaver.js.map → host/fileSaver.js.map} +0 -0
- /package/client/{logger.d.ts → host/logger.d.ts} +0 -0
- /package/client/{logger.js → host/logger.js} +0 -0
- /package/client/{logger.js.map → host/logger.js.map} +0 -0
- /package/client/{apiVersion.d.ts → runtime/apiVersion.d.ts} +0 -0
- /package/client/{apiVersion.js → runtime/apiVersion.js} +0 -0
- /package/client/{apiVersion.js.map → runtime/apiVersion.js.map} +0 -0
- /package/client/{events.d.ts → runtime/events.d.ts} +0 -0
- /package/client/{events.js → runtime/events.js} +0 -0
- /package/client/{events.js.map → runtime/events.js.map} +0 -0
- /package/client/{listenerSet.js → runtime/listenerSet.js} +0 -0
- /package/client/{listenerSet.js.map → runtime/listenerSet.js.map} +0 -0
- /package/client/{network.d.ts → runtime/network.d.ts} +0 -0
- /package/client/{network.js → runtime/network.js} +0 -0
- /package/client/{network.js.map → runtime/network.js.map} +0 -0
- /package/client/{principalMutationDeadline.js → runtime/principalMutationDeadline.js} +0 -0
- /package/client/{principalMutationDeadline.js.map → runtime/principalMutationDeadline.js.map} +0 -0
- /package/client/{rootContainerAdoption.js → runtime/rootContainerAdoption.js} +0 -0
- /package/client/{syncBillingGate.d.ts → runtime/syncBillingGate.d.ts} +0 -0
- /package/client/{syncBillingGate.js → runtime/syncBillingGate.js} +0 -0
- /package/client/{syncBillingGate.js.map → runtime/syncBillingGate.js.map} +0 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"sessionOrganizationCreation.js","sourceRoot":"","sources":["sessionOrganizationCreation.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,kBAAkB,IAAI,0BAA0B,EAAE,MAAM,kDAAkD,CAAC;AAyBpH,MAAM,CAAC,KAAK,UAAU,yBAAyB,CAC7C,YAAqD,EACrD,KAKC;IAED,IAAI,CAAC,KAAK,CAAC,MAAM,EAAE,CAAC;QAClB,YAAY,CAAC,GAAG,CAAC,qDAAqD,CAAC,CAAC;QACxE,OAAO,IAAI,CAAC;IACd,CAAC;IAED,MAAM,gBAAgB,GAAG,YAAY,CAAC,QAAQ,CAAC,QAAQ,CAAC;IACxD,MAAM,EAAE,oBAAoB,EAAE,cAAc,EAAE,GAAG,gBAAgB,CAAC;IAClE,IAAI,CAAC,cAAc,IAAI,CAAC,oBAAoB,EAAE,CAAC;QAC7C,YAAY,CAAC,GAAG,CACd,4DAA4D,CAC7D,CAAC;QACF,OAAO,IAAI,CAAC;IACd,CAAC;IAED,MAAM,QAAQ,GAAG,YAAY,CAAC,QAAQ,CAAC,MAAM,CAAC;IAC9C,IAAI,CAAC,Q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xC,CAAC;AACJ,CAAC","sourcesContent":["import type { ApiClient } from \"@tearleads/api-client\";\nimport type { DocumentProjectorRegistryInput } from \"../../data/documents/documentKinds\";\nimport { createOrganization as createOrganizationWorkflow } from \"../../workflows/organizations/createOrganization\";\nimport type { ProvisionedSystemContainerSpec } from \"../../workflows/registration\";\nimport type { ProvisionedPrincipalHistoryPrimer } from \"../../workflows/registration/provisionedPrincipalHistory\";\nimport type {
|
|
1
|
+
{"version":3,"file":"sessionOrganizationCreation.js","sourceRoot":"","sources":["sessionOrganizationCreation.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,kBAAkB,IAAI,0BAA0B,EAAE,MAAM,kDAAkD,CAAC;AAyBpH,MAAM,CAAC,KAAK,UAAU,yBAAyB,CAC7C,YAAqD,EACrD,KAKC;IAED,IAAI,CAAC,KAAK,CAAC,MAAM,EAAE,CAAC;QAClB,YAAY,CAAC,GAAG,CAAC,qDAAqD,CAAC,CAAC;QACxE,OAAO,IAAI,CAAC;IACd,CAAC;IAED,MAAM,gBAAgB,GAAG,YAAY,CAAC,QAAQ,CAAC,QAAQ,CAAC;IACxD,MAAM,EAAE,oBAAoB,EAAE,cAAc,EAAE,GAAG,gBAAgB,CAAC;IAClE,IAAI,CAAC,cAAc,IAAI,CAAC,oBAAoB,EAAE,CAAC;QAC7C,YAAY,CAAC,GAAG,CACd,4DAA4D,CAC7D,CAAC;QACF,OAAO,IAAI,CAAC;IACd,CAAC;IAED,MAAM,QAAQ,GAAG,YAAY,CAAC,QAAQ,CAAC,MAAM,CAAC;IAC9C,IAAI,CAAC,QAAQ,EAAE,CAAC;QACd,YAAY,CAAC,GAAG,CACd,6DAA6D,CAC9D,CAAC;QACF,OAAO,IAAI,CAAC;IACd,CAAC;IAED,IAAI,QAAgE,CAAC;IACrE,IAAI,CAAC;QACH,QAAQ,GAAG,MAAM,0BAA0B,CAAC;YAC1C,SAAS,EAAE,YAAY,CAAC,GAAG;YAC3B,QAAQ;YACR,kBAAkB,EAAE,YAAY,CAAC,kBAAkB;YACnD,oBAAoB;YACpB,iBAAiB,EAAE,GAAG,EAAE,CACtB,YAAY,CAAC,QAAQ,CAAC,QAAQ,KAAK,gBAAgB;YACrD,GAAG,EAAE,YAAY,CAAC,GAAG;YACrB,QAAQ,EAAE,YAAY,CAAC,QAAQ;YAC/B,yBAAyB,EAAE,KAAK,CAAC,yBAAyB;YAC1D,uBAAuB,EAAE,KAAK,CAAC,OAAO,EAAE,uBAAuB;YAC/D,qBAAqB,EAAE,YAAY,CAAC,gCAAgC;YACpE,2BAA2B,EAAE,YAAY,CAAC,2BAA2B;YACrE,sBAAsB,EAAE,KAAK,CAAC,sBAAsB;YACpD,qBAAqB,EAAE,KAAK,CAAC,OAAO,EAAE,qBAAqB;YAC3D,cAAc;YACd,MAAM,EAAE,KAAK,CAAC,MAAM;SACrB,CAAC,CAAC;IACL,CAAC;IAAC,OAAO,KAAc,EAAE,CAAC;QACxB,YAAY,CAAC,QAAQ,CAAC,8BAA8B,EAAE,KAAK,CAAC,CAAC;QAC7D,MAAM,KAAK,CAAC;IACd,CAAC;IAED,IAAI,YAAY,CAAC,QAAQ,CAAC,QAAQ,KAAK,gBAAgB;QAAE,OAAO,IAAI,CAAC;IACrE,IAAI,CAAC,QAAQ,EAAE,CAAC;QACd,YAAY,CAAC,GAAG,CAAC,8BAA8B,CAAC,CAAC;QACjD,OAAO,IAAI,CAAC;IACd,CAAC;IACD,oEAAoE;IACpE,OAAO;QACL,WAAW,EAAE,QAAQ,CAAC,eAAe;QACrC,cAAc,EAAE,QAAQ,CAAC,cAAc;KACxC,CAAC;AACJ,CAAC","sourcesContent":["import type { ApiClient } from \"@tearleads/api-client\";\nimport type { DocumentProjectorRegistryInput } from \"../../data/documents/documentKinds\";\nimport { createOrganization as createOrganizationWorkflow } from \"../../workflows/organizations/createOrganization\";\nimport type { ProvisionedSystemContainerSpec } from \"../../workflows/registration\";\nimport type { ProvisionedPrincipalHistoryPrimer } from \"../../workflows/registration/provisionedPrincipalHistory\";\nimport type { Identity } from \"../identity\";\nimport type { Database } from \"../runtime/database\";\nimport type {\n CreateOrganizationOptions,\n SessionCreateOrganizationResult,\n} from \"./sessionTypes\";\n\ninterface SessionOrganizationCreationDependencies {\n readonly api: ApiClient;\n readonly database: Database;\n readonly documentProjectors?: DocumentProjectorRegistryInput | undefined;\n readonly identity: Identity;\n readonly log: (message: string) => void;\n readonly logError: (message: string | Error, cause?: unknown) => void;\n readonly primeProvisionedPrincipalHistory?:\n | ProvisionedPrincipalHistoryPrimer\n | undefined;\n readonly provisionedSystemContainers?:\n | ReadonlyArray<ProvisionedSystemContainerSpec>\n | undefined;\n}\n\nexport async function createSessionOrganization(\n dependencies: SessionOrganizationCreationDependencies,\n input: {\n readonly nativeSubscriptionRestore?: boolean | undefined;\n readonly options?: CreateOrganizationOptions | undefined;\n readonly replacesOrganizationId?: string | undefined;\n readonly userId: string | null;\n },\n): Promise<SessionCreateOrganizationResult | null> {\n if (!input.userId) {\n dependencies.log(\"Create organization skipped: user id is unavailable\");\n return null;\n }\n\n const identitySnapshot = dependencies.identity.snapshot;\n const { encapsulationKeyPair, signingKeyPair } = identitySnapshot;\n if (!signingKeyPair || !encapsulationKeyPair) {\n dependencies.log(\n \"Create organization skipped: identity keys are unavailable\",\n );\n return null;\n }\n\n const dbClient = dependencies.database.client;\n if (!dbClient) {\n dependencies.log(\n \"Create organization skipped: database client is unavailable\",\n );\n return null;\n }\n\n let response: Awaited<ReturnType<typeof createOrganizationWorkflow>>;\n try {\n response = await createOrganizationWorkflow({\n apiClient: dependencies.api,\n dbClient,\n documentProjectors: dependencies.documentProjectors,\n encapsulationKeyPair,\n isIdentityCurrent: () =>\n dependencies.identity.snapshot === identitySnapshot,\n log: dependencies.log,\n logError: dependencies.logError,\n nativeSubscriptionRestore: input.nativeSubscriptionRestore,\n organizationProfileName: input.options?.organizationProfileName,\n primePrincipalHistory: dependencies.primeProvisionedPrincipalHistory,\n provisionedSystemContainers: dependencies.provisionedSystemContainers,\n replacesOrganizationId: input.replacesOrganizationId,\n rosterProfileNickname: input.options?.rosterProfileNickname,\n signingKeyPair,\n userId: input.userId,\n });\n } catch (error: unknown) {\n dependencies.logError(\"Organization creation failed\", error);\n throw error;\n }\n\n if (dependencies.identity.snapshot !== identitySnapshot) return null;\n if (!response) {\n dependencies.log(\"Organization creation failed\");\n return null;\n }\n // Creating an organization does not switch the active organization.\n return {\n containerId: response.rootContainerId,\n organizationId: response.organizationId,\n };\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"sessionPurgeRecovery.js","sourceRoot":"","sources":["sessionPurgeRecovery.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,8BAA8B,EAAE,MAAM,uCAAuC,CAAC;AACvF,OAAO,EACL,8CAA8C,EAC9C,qCAAqC,GACtC,MAAM,+DAA+D,CAAC;AACvE,OAAO,EAAE,qCAAqC,EAAE,MAAM,mEAAmE,CAAC;AAC1H,OAAO,EAAE,oBAAoB,EAAE,MAAM,sBAAsB,CAAC;AAG5D,OAAO,EAAE,8CAA8C,EAAE,MAAM,yBAAyB,CAAC;AAyBzF,SAAS,yBAAyB,CAChC,WAA4C,EAC5C,OAAiE;IAEjE,IAAI,CAAC,OAAO,EAAE,CAAC;QACb,MAAM,IAAI,KAAK,CAAC,sDAAsD,CAAC,CAAC;IAC1E,CAAC;IACD,IAAI,CAAC,8BAA8B,CAAC,OAAO,EAAE,IAAI,CAAC,GAAG,EAAE,CAAC,CAAC,OAAO,EAAE,CAAC;QACjE,MAAM,IAAI,8CAA8C,CACtD,WAAW,CAAC,cAAc,EAC1B,OAAO,CAAC,MAAM,EACd,WAAW,CAAC,WAAW,CACxB,CAAC;IACJ,CAAC;AACH,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,2BAA2B,CAC/C,YAA8C,EAC9C,OAAoC,EACpC,cAAsB;IAEtB,MAAM,OAAO,GAAG,YAAY,CAAC,QAAQ,CAAC,cAAc,CAAC,sBAAsB,CAAC,CAAC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EAAE;QAAE,OAAO,IAAI,CAAC;IACtC,MAAM,mBAAmB,GACvB,MAAM,8CAA8C,CAAC;QACnD,OAAO;QACP,sBAAsB,EAAE,cAAc;QACtC,MAAM;KACP,CAAC,CAAC;IACL,IAAI,CAAC,iBAAiB,EAAE;QAAE,OAAO,IAAI,CAAC;IACtC,MAAM,oBAAoB,GACxB,MAAM,YAAY,CAAC,GAAG,CAAC,kBAAkB,CAAC,mBAAmB,CAAC,CAAC;IACjE,IAAI,CAAC,iBAAiB,EAAE;QAAE,OAAO,IAAI,CAAC;IACtC,0BAA0B,CACxB,oBAAoB,EACpB,WAAW,EACX,cAAc,EACd,MAAM,EACN,gBAAgB,CAAC,cAAc,CAChC,CAAC;IACF,MAAM,cAAc,GAAG,MAAM,qCAAqC,CAAC;QACjE,SAAS,EAAE,iBAAiB;QAC5B,OAAO;QACP,sBAAsB,EAAE,cAAc;QACtC,MAAM;KACP,CAAC,CAAC;IACH,IAAI,CAAC,cAAc,IAAI,CAAC,iBAAiB,EAAE;QAAE,OAAO,IAAI,CAAC;IACzD,YAAY,CAAC,GAAG,CAAC,2BAA2B,EAAE,CAAC;IAC/C,OAAO,CAAC,UAAU,CAAC;QACjB,WAAW,EAAE,WAAW,CAAC,WAAW;QACpC,qBAAqB,EAAE,WAAW,CAAC,cAAc;QACjD,cAAc,EAAE,WAAW,CAAC,cAAc;KAC3C,CAAC,CAAC;IACH,YAAY,CAAC,GAAG,CACd,iCAAiC,WAAW,CAAC,cAAc,GAAG,CAC/D,CAAC;IACF,OAAO;QACL,GAAG,WAAW;QACd,sBAAsB,EAAE,cAAc;QACtC,KAAK;KACN,CAAC;AACJ,CAAC","sourcesContent":["import type { ApiClient } from \"@tearleads/api-client\";\nimport { resolveOrganizationBillingView } from \"../../workflows/organizations/billing\";\nimport {\n loadOrganizationReplacementFinalizationRequest,\n removeOrganizationProvisioningAttempt,\n} from \"../../workflows/organizations/organizationProvisioningAttempt\";\nimport { verifyOrganizationReplacementResponse } from \"../../workflows/organizations/organizationReplacementVerification\";\nimport { clearRemoteSyncState } from \"../../workflows/sync\";\nimport type { Database } from \"../database\";\nimport type { Identity } from \"../identity\";\nimport { PurgedOrganizationRecoveryBillingRequiredError } from \"./sessionRecoveryErrors\";\nimport type {\n CreateOrganizationOptions,\n SessionContext,\n SessionCreateOrganizationResult,\n SessionRecoverOrganizationResult,\n} from \"./sessionTypes\";\n\ninterface SessionPurgeRecoveryDependencies {\n api: Pick<ApiClient, \"clearWriterProjectionCaches\">;\n database: Pick<Database, \"requireExecSql\">;\n identity: Pick<Identity, \"snapshot\">;\n log: (message: string) => void;\n}\n\ninterface SessionPurgeRecoveryContext {\n createOrganization: (\n options?: CreateOrganizationOptions,\n replacesOrganizationId?: string,\n ) => Promise<SessionCreateOrganizationResult | null>;\n organizationId: string | null;\n setContext: (context: SessionContext) => void;\n userId: string | null;\n}\n\nfunction requireReplacementCanSync(\n replacement: SessionCreateOrganizationResult,\n billing: Awaited<ReturnType<ApiClient[\"getOrganizationBilling\"]>>,\n): void {\n if (!billing) {\n throw new Error(\"Replacement organization billing could not be loaded\");\n }\n if (!resolveOrganizationBillingView(billing, Date.now()).canSync) {\n throw new PurgedOrganizationRecoveryBillingRequiredError(\n replacement.organizationId,\n billing.status,\n replacement.containerId,\n );\n }\n}\n\nexport async function clearSessionRemoteSyncState(\n dependencies: SessionPurgeRecoveryDependencies,\n session: SessionPurgeRecoveryContext,\n organizationId: string,\n) {\n const execSql = dependencies.database.requireExecSql(\"clearRemoteSyncState\");\n const result = await clearRemoteSyncState(execSql, {\n organizationId,\n });\n dependencies.api.clearWriterProjectionCaches();\n if (session.organizationId === organizationId) {\n session.setContext({ containerId: null, organizationId: null });\n }\n dependencies.log(\"Remote sync state cleared\");\n return result;\n}\n\nfunction verifyFinalizedReplacement(\n finalizedReplacement: Awaited<ReturnType<ApiClient[\"createOrganization\"]>>,\n replacement: SessionCreateOrganizationResult,\n replacesOrganizationId: string,\n userId: string,\n signingKeyPair: Identity[\"snapshot\"][\"signingKeyPair\"],\n): void {\n if (\n !finalizedReplacement ||\n finalizedReplacement.organizationId !== replacement.organizationId ||\n finalizedReplacement.rootContainerId !== replacement.containerId ||\n finalizedReplacement.userId !== userId\n ) {\n throw new Error(\"Organization replacement finalization was inconsistent\");\n }\n if (!signingKeyPair) {\n throw new Error(\n \"Organization replacement requires the current signing identity\",\n );\n }\n verifyOrganizationReplacementResponse({\n replacesOrganizationId,\n response: finalizedReplacement,\n signingPublicKey: signingKeyPair.signingPublicKey,\n userId,\n });\n}\n\nexport async function recoverPurgedSessionOrganization(\n dependencies: SessionPurgeRecoveryDependencies & {\n api: Pick<\n ApiClient,\n | \"clearWriterProjectionCaches\"\n | \"createOrganization\"\n | \"getOrganizationBilling\"\n >;\n },\n session: SessionPurgeRecoveryContext,\n organizationId: string,\n options: CreateOrganizationOptions | undefined,\n): Promise<SessionRecoverOrganizationResult | null> {\n const identitySnapshot = dependencies.identity.snapshot;\n const sessionOrganizationId = session.organizationId;\n const userId = session.userId;\n if (!userId) {\n throw new Error(\"Purged organization recovery requires a current user\");\n }\n const isRecoveryCurrent = () =>\n dependencies.identity.snapshot === identitySnapshot &&\n session.organizationId === sessionOrganizationId &&\n session.userId === userId;\n const billing = await dependencies.api.getOrganizationBilling(organizationId);\n if (billing?.status !== \"purged\") {\n throw new Error(\n `Organization ${organizationId} cannot be recovered before its purge finishes`,\n );\n }\n if (!isRecoveryCurrent()) return null;\n const replacement = await session.createOrganization(options, organizationId);\n if (!replacement) return null;\n if (!isRecoveryCurrent()) return null;\n const replacementBilling = await dependencies.api.getOrganizationBilling(\n replacement.organizationId,\n );\n if (!isRecoveryCurrent()) return null;\n requireReplacementCanSync(replacement, replacementBilling);\n const execSql = dependencies.database.requireExecSql(\n \"recoverPurgedOrganization\",\n );\n const reset = await clearRemoteSyncState(\n execSql,\n {\n organizationId,\n replacement: {\n organizationId: replacement.organizationId,\n rootContainerId: replacement.containerId,\n },\n },\n isRecoveryCurrent,\n );\n if (!isRecoveryCurrent()) return null;\n const finalizationRequest =\n await loadOrganizationReplacementFinalizationRequest({\n execSql,\n replacedOrganizationId: organizationId,\n userId,\n });\n if (!isRecoveryCurrent()) return null;\n const finalizedReplacement =\n await dependencies.api.createOrganization(finalizationRequest);\n if (!isRecoveryCurrent()) return null;\n verifyFinalizedReplacement(\n finalizedReplacement,\n replacement,\n organizationId,\n userId,\n identitySnapshot.signingKeyPair,\n );\n const attemptRemoved = await removeOrganizationProvisioningAttempt({\n canCommit: isRecoveryCurrent,\n execSql,\n replacedOrganizationId: organizationId,\n userId,\n });\n if (!attemptRemoved || !isRecoveryCurrent()) return null;\n dependencies.api.clearWriterProjectionCaches();\n session.setContext({\n containerId: replacement.containerId,\n defaultOrganizationId: replacement.organizationId,\n organizationId: replacement.organizationId,\n });\n dependencies.log(\n `Purged organization replaced (${replacement.organizationId})`,\n );\n return {\n ...replacement,\n replacedOrganizationId: organizationId,\n reset,\n };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"sessionPurgeRecovery.js","sourceRoot":"","sources":["sessionPurgeRecovery.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,8BAA8B,EAAE,MAAM,uCAAuC,CAAC;AACvF,OAAO,EACL,8CAA8C,EAC9C,qCAAqC,GACtC,MAAM,+DAA+D,CAAC;AACvE,OAAO,EAAE,qCAAqC,EAAE,MAAM,mEAAmE,CAAC;AAC1H,OAAO,EAAE,oBAAoB,EAAE,MAAM,sBAAsB,CAAC;AAG5D,OAAO,EAAE,8CAA8C,EAAE,MAAM,yBAAyB,CAAC;AAyBzF,SAAS,yBAAyB,CAChC,WAA4C,EAC5C,OAAiE;IAEjE,IAAI,CAAC,OAAO,EAAE,CAAC;QACb,MAAM,IAAI,KAAK,CAAC,sDAAsD,CAAC,CAAC;IAC1E,CAAC;IACD,IAAI,CAAC,8BAA8B,CAAC,OAAO,EAAE,IAAI,CAAC,GAAG,EAAE,CAAC,CAAC,OAAO,EAAE,CAAC;QACjE,MAAM,IAAI,8CAA8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G,WAAW;QACd,sBAAsB,EAAE,cAAc;QACtC,KAAK;KACN,CAAC;AACJ,CAAC","sourcesContent":["import type { ApiClient } from \"@tearleads/api-client\";\nimport { resolveOrganizationBillingView } from \"../../workflows/organizations/billing\";\nimport {\n loadOrganizationReplacementFinalizationRequest,\n removeOrganizationProvisioningAttempt,\n} from \"../../workflows/organizations/organizationProvisioningAttempt\";\nimport { verifyOrganizationReplacementResponse } from \"../../workflows/organizations/organizationReplacementVerification\";\nimport { clearRemoteSyncState } from \"../../workflows/sync\";\nimport type { Identity } from \"../identity\";\nimport type { Database } from \"../runtime/database\";\nimport { PurgedOrganizationRecoveryBillingRequiredError } from \"./sessionRecoveryErrors\";\nimport type {\n CreateOrganizationOptions,\n SessionContext,\n SessionCreateOrganizationResult,\n SessionRecoverOrganizationResult,\n} from \"./sessionTypes\";\n\ninterface SessionPurgeRecoveryDependencies {\n api: Pick<ApiClient, \"clearWriterProjectionCaches\">;\n database: Pick<Database, \"requireExecSql\">;\n identity: Pick<Identity, \"snapshot\">;\n log: (message: string) => void;\n}\n\ninterface SessionPurgeRecoveryContext {\n createOrganization: (\n options?: CreateOrganizationOptions,\n replacesOrganizationId?: string,\n ) => Promise<SessionCreateOrganizationResult | null>;\n organizationId: string | null;\n setContext: (context: SessionContext) => void;\n userId: string | null;\n}\n\nfunction requireReplacementCanSync(\n replacement: SessionCreateOrganizationResult,\n billing: Awaited<ReturnType<ApiClient[\"getOrganizationBilling\"]>>,\n): void {\n if (!billing) {\n throw new Error(\"Replacement organization billing could not be loaded\");\n }\n if (!resolveOrganizationBillingView(billing, Date.now()).canSync) {\n throw new PurgedOrganizationRecoveryBillingRequiredError(\n replacement.organizationId,\n billing.status,\n replacement.containerId,\n );\n }\n}\n\nexport async function clearSessionRemoteSyncState(\n dependencies: SessionPurgeRecoveryDependencies,\n session: SessionPurgeRecoveryContext,\n organizationId: string,\n) {\n const execSql = dependencies.database.requireExecSql(\"clearRemoteSyncState\");\n const result = await clearRemoteSyncState(execSql, {\n organizationId,\n });\n dependencies.api.clearWriterProjectionCaches();\n if (session.organizationId === organizationId) {\n session.setContext({ containerId: null, organizationId: null });\n }\n dependencies.log(\"Remote sync state cleared\");\n return result;\n}\n\nfunction verifyFinalizedReplacement(\n finalizedReplacement: Awaited<ReturnType<ApiClient[\"createOrganization\"]>>,\n replacement: SessionCreateOrganizationResult,\n replacesOrganizationId: string,\n userId: string,\n signingKeyPair: Identity[\"snapshot\"][\"signingKeyPair\"],\n): void {\n if (\n !finalizedReplacement ||\n finalizedReplacement.organizationId !== replacement.organizationId ||\n finalizedReplacement.rootContainerId !== replacement.containerId ||\n finalizedReplacement.userId !== userId\n ) {\n throw new Error(\"Organization replacement finalization was inconsistent\");\n }\n if (!signingKeyPair) {\n throw new Error(\n \"Organization replacement requires the current signing identity\",\n );\n }\n verifyOrganizationReplacementResponse({\n replacesOrganizationId,\n response: finalizedReplacement,\n signingPublicKey: signingKeyPair.signingPublicKey,\n userId,\n });\n}\n\nexport async function recoverPurgedSessionOrganization(\n dependencies: SessionPurgeRecoveryDependencies & {\n api: Pick<\n ApiClient,\n | \"clearWriterProjectionCaches\"\n | \"createOrganization\"\n | \"getOrganizationBilling\"\n >;\n },\n session: SessionPurgeRecoveryContext,\n organizationId: string,\n options: CreateOrganizationOptions | undefined,\n): Promise<SessionRecoverOrganizationResult | null> {\n const identitySnapshot = dependencies.identity.snapshot;\n const sessionOrganizationId = session.organizationId;\n const userId = session.userId;\n if (!userId) {\n throw new Error(\"Purged organization recovery requires a current user\");\n }\n const isRecoveryCurrent = () =>\n dependencies.identity.snapshot === identitySnapshot &&\n session.organizationId === sessionOrganizationId &&\n session.userId === userId;\n const billing = await dependencies.api.getOrganizationBilling(organizationId);\n if (billing?.status !== \"purged\") {\n throw new Error(\n `Organization ${organizationId} cannot be recovered before its purge finishes`,\n );\n }\n if (!isRecoveryCurrent()) return null;\n const replacement = await session.createOrganization(options, organizationId);\n if (!replacement) return null;\n if (!isRecoveryCurrent()) return null;\n const replacementBilling = await dependencies.api.getOrganizationBilling(\n replacement.organizationId,\n );\n if (!isRecoveryCurrent()) return null;\n requireReplacementCanSync(replacement, replacementBilling);\n const execSql = dependencies.database.requireExecSql(\n \"recoverPurgedOrganization\",\n );\n const reset = await clearRemoteSyncState(\n execSql,\n {\n organizationId,\n replacement: {\n organizationId: replacement.organizationId,\n rootContainerId: replacement.containerId,\n },\n },\n isRecoveryCurrent,\n );\n if (!isRecoveryCurrent()) return null;\n const finalizationRequest =\n await loadOrganizationReplacementFinalizationRequest({\n execSql,\n replacedOrganizationId: organizationId,\n userId,\n });\n if (!isRecoveryCurrent()) return null;\n const finalizedReplacement =\n await dependencies.api.createOrganization(finalizationRequest);\n if (!isRecoveryCurrent()) return null;\n verifyFinalizedReplacement(\n finalizedReplacement,\n replacement,\n organizationId,\n userId,\n identitySnapshot.signingKeyPair,\n );\n const attemptRemoved = await removeOrganizationProvisioningAttempt({\n canCommit: isRecoveryCurrent,\n execSql,\n replacedOrganizationId: organizationId,\n userId,\n });\n if (!attemptRemoved || !isRecoveryCurrent()) return null;\n dependencies.api.clearWriterProjectionCaches();\n session.setContext({\n containerId: replacement.containerId,\n defaultOrganizationId: replacement.organizationId,\n organizationId: replacement.organizationId,\n });\n dependencies.log(\n `Purged organization replaced (${replacement.organizationId})`,\n );\n return {\n ...replacement,\n replacedOrganizationId: organizationId,\n reset,\n };\n}\n"]}
|
|
@@ -4,8 +4,8 @@ import type { SecurityIncidentReporter } from "../../data/shared/securityInciden
|
|
|
4
4
|
import type { ProvisionedSystemContainerSpec } from "../../workflows/registration/index.js";
|
|
5
5
|
import type { ProvisionedPrincipalHistoryPrimer } from "../../workflows/registration/provisionedPrincipalHistory.js";
|
|
6
6
|
import type { ClearRemoteSyncStateResult } from "../../workflows/sync/index.js";
|
|
7
|
-
import type {
|
|
8
|
-
import type {
|
|
7
|
+
import type { Identity } from "../identity/index.js";
|
|
8
|
+
import type { Database } from "../runtime/database.js";
|
|
9
9
|
import type { BoundUserIdLookup, SessionRegistrationRefusal, UserIdentityAvailable } from "./sessionIdentityTrust.js";
|
|
10
10
|
export type { SessionRegistrationRefusal } from "./sessionIdentityTrust.js";
|
|
11
11
|
export interface SessionDependencies {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"sessionTypes.js","sourceRoot":"","sources":["sessionTypes.ts"],"names":[],"mappings":"","sourcesContent":["import type { ApiClient } from \"@tearleads/api-client\";\nimport type { DocumentProjectorRegistryInput } from \"../../data/documents/documentKinds\";\nimport type { SecurityIncidentReporter } from \"../../data/shared/securityIncidents\";\nimport type { ProvisionedSystemContainerSpec } from \"../../workflows/registration\";\nimport type { ProvisionedPrincipalHistoryPrimer } from \"../../workflows/registration/provisionedPrincipalHistory\";\nimport type { ClearRemoteSyncStateResult } from \"../../workflows/sync\";\nimport type {
|
|
1
|
+
{"version":3,"file":"sessionTypes.js","sourceRoot":"","sources":["sessionTypes.ts"],"names":[],"mappings":"","sourcesContent":["import type { ApiClient } from \"@tearleads/api-client\";\nimport type { DocumentProjectorRegistryInput } from \"../../data/documents/documentKinds\";\nimport type { SecurityIncidentReporter } from \"../../data/shared/securityIncidents\";\nimport type { ProvisionedSystemContainerSpec } from \"../../workflows/registration\";\nimport type { ProvisionedPrincipalHistoryPrimer } from \"../../workflows/registration/provisionedPrincipalHistory\";\nimport type { ClearRemoteSyncStateResult } from \"../../workflows/sync\";\nimport type { Identity } from \"../identity\";\nimport type { Database } from \"../runtime/database\";\nimport type {\n BoundUserIdLookup,\n SessionRegistrationRefusal,\n UserIdentityAvailable,\n} from \"./sessionIdentityTrust\";\n\nexport type { SessionRegistrationRefusal } from \"./sessionIdentityTrust\";\n\nexport interface SessionDependencies {\n api: ApiClient;\n database: Database;\n documentProjectors?: DocumentProjectorRegistryInput | undefined;\n identity: Identity;\n log: (message: string) => void;\n logError: (message: string | Error, cause?: unknown) => void;\n /** The user this device's trust store already binds a signing key to. */\n boundUserIdForSigningKey?: BoundUserIdLookup | undefined;\n onUserIdentityAvailable?: UserIdentityAvailable | undefined;\n /** Seeds verified recovery progress for a new organization's founding heads. */\n primeProvisionedPrincipalHistory?:\n | ProvisionedPrincipalHistoryPrimer\n | undefined;\n /** App-owned system containers provisioned with each new organization. */\n provisionedSystemContainers?:\n | ReadonlyArray<ProvisionedSystemContainerSpec>\n | undefined;\n /**\n * Records a refused login (a different account than acknowledged) or a\n * refused root acknowledgement; absent in bare test harnesses.\n */\n reportSecurityIncident?: SecurityIncidentReporter | undefined;\n}\n\nexport interface SessionContext {\n /** Fingerprint-bound host restore only; view selections never acknowledge roots. */\n rootAcknowledgments?: SessionSnapshot[\"rootAcknowledgments\"] | undefined;\n authToken?: string | null | undefined;\n containerId?: string | null | undefined;\n /** Server-backed personal organization; independent of the active org. */\n defaultOrganizationId?: string | null | undefined;\n isAuthenticated?: boolean | undefined;\n /** Platform-operator flag reported by the server at login. */\n isRoot?: boolean | undefined;\n organizationId?: string | null | undefined;\n userId?: string | null | undefined;\n}\n\nexport interface SessionSnapshot {\n /**\n * Server acknowledgements retained independently of the selected container.\n * Bound to (signing fingerprint, user, organization): once acknowledged, an\n * organization's root id may only be re-acknowledged or reported purged.\n */\n rootAcknowledgments: ReadonlyArray<{\n readonly signingFingerprint: string;\n readonly userId: string;\n readonly organizationId: string;\n readonly rootContainerId: string | null;\n }>;\n authToken: string | null;\n containerId: string | null;\n /** Server-backed personal organization; independent of the active org. */\n defaultOrganizationId: string | null;\n isAuthenticated: boolean;\n /** Platform-operator flag reported by the server at login. */\n isRoot: boolean;\n organizationId: string | null;\n userId: string | null;\n}\n\nexport type SessionListener = () => void;\n\nexport interface SessionRegistrationResult {\n readonly challenge: string;\n readonly containerId: string;\n readonly organizationId: string;\n readonly userId: string;\n}\n\nexport interface SessionCreateOrganizationResult {\n readonly containerId: string;\n readonly organizationId: string;\n}\n\nexport interface SessionRecoverOrganizationResult\n extends SessionCreateOrganizationResult {\n readonly reset: ClearRemoteSyncStateResult;\n readonly replacedOrganizationId: string;\n}\n\nexport interface CreateOrganizationOptions {\n /** Overrides the seeded organization profile name; see registration. */\n readonly organizationProfileName?: string | undefined;\n /** Overrides the seeded self roster-profile nickname; see registration. */\n readonly rosterProfileNickname?: string | undefined;\n}\n\nexport interface RegisterIdentityOptions {\n /**\n * Overrides the seeded personal-organization profile name. Optional; when\n * omitted the default personal-org name is used. The demo host passes each\n * pane's peer-labeled org name (\"Peer 1's Org\").\n */\n readonly organizationProfileName?: string | undefined;\n /**\n * Overrides the seeded self roster-profile nickname. Optional; when omitted\n * the default (\"You\") is used. The demo host passes each pane's peer-labeled\n * self name (\"Peer 1 (You)\").\n */\n readonly rosterProfileNickname?: string | undefined;\n}\n\nexport interface UserSession {\n readonly createdAt: string;\n readonly id: string;\n readonly ipAddresses: string[];\n readonly isCurrent: boolean;\n readonly lastActiveAt: string;\n readonly lastActiveIp: string | null;\n readonly signingKeyFingerprint: string;\n}\n\nexport interface Session {\n readonly authToken: string | null;\n readonly containerId: string | null;\n /** Server-backed personal organization; independent of the active org. */\n readonly defaultOrganizationId: string | null;\n readonly isAuthenticated: boolean;\n /**\n * Platform-operator flag reported by the server at login. It only decides\n * whether the root console is offered; the API enforces root access itself.\n */\n readonly isRoot: boolean;\n readonly organizationId: string | null;\n readonly snapshot: SessionSnapshot;\n /** Controls server replication without changing network connectivity. */\n readonly syncEnabled: boolean;\n readonly userId: string | null;\n /**\n * Whether `userId` was acknowledged by the server for the active signing\n * identity (a successful login or a fingerprint-bound host restore). A user\n * ID chosen locally through `setUserId` is not, and hosts must not persist\n * it as this identity's account.\n */\n readonly userIdAcknowledged: boolean;\n bootstrapLocalRootContainer(): Promise<{\n containerId: string;\n created: boolean;\n }>;\n clearRemoteSyncState(\n organizationId: string,\n ): Promise<ClearRemoteSyncStateResult>;\n createOrganization(\n options?: CreateOrganizationOptions,\n ): Promise<SessionCreateOrganizationResult | null>;\n completeNativeSubscriptionRestoreOrganization(\n organizationId: string,\n ): Promise<boolean>;\n destroySession(sessionId: string): Promise<boolean>;\n listSessions(): Promise<UserSession[]>;\n login(challengeHex?: string | undefined): Promise<boolean>;\n logout(): void;\n logoutRemote(): Promise<boolean>;\n prepareNativeSubscriptionRestoreOrganization(\n options?: CreateOrganizationOptions,\n ): Promise<SessionCreateOrganizationResult | null>;\n registerIdentity(\n options?: RegisterIdentityOptions,\n ): Promise<SessionRegistrationResult | SessionRegistrationRefusal | null>;\n recoverPurgedOrganization(\n organizationId: string,\n options?: CreateOrganizationOptions,\n ): Promise<SessionRecoverOrganizationResult | null>;\n setAuthToken(authToken: string | null): void;\n setContainerId(containerId: string | null): void;\n /** Host-restored context must match the active signing identity; conflicting user acknowledgments throw. */\n setContext(context: SessionContext): void;\n setOrganizationId(organizationId: string | null): void;\n setSyncEnabled(enabled: boolean): void;\n setUserId(userId: string | null): void;\n subscribe(listener: SessionListener): () => void;\n}\n"]}
|
package/package.json
CHANGED
package/client/blobs.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"blobs.js","sourceRoot":"","sources":["blobs.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,eAAe,EAAE,MAAM,+BAA+B,CAAC;AAChE,OAAO,EAAE,qBAAqB,EAAE,MAAM,+BAA+B,CAAC;AAItE,MAAM,OAAO,KAAK;IACC,cAAc,GAAG,qBAAqB,EAAE,CAAC;IAClD,cAAc,GAAG,KAAK,CAAC;IACd,mBAAmB,CAAmB;IAC/C,UAAU,CAAY;IAE9B,YACE,KAA6B,EAC7B,sBAAwC,eAAe;QAEvD,IAAI,CAAC,mBAAmB,GAAG,mBAAmB,CAAC;QAC/C,IAAI,CAAC,UAAU,GAAG,KAAK,IAAI,IAAI,CAAC,cAAc,CAAC;IACjD,CAAC;IAED,IAAI,KAAK;QACP,OAAO,IAAI,CAAC,UAAU,CAAC;IACzB,CAAC;IAED,iBAAiB;QACf,IAAI,CAAC,cAAc,GAAG,KAAK,CAAC;QAC5B,IAAI,CAAC,UAAU,GAAG,IAAI,CAAC,cAAc,CAAC;IACxC,CAAC;IAED,oBAAoB,CAAC,kBAA0B;QAC7C,IAAI,CAAC,cAAc,GAAG,IAAI,CAAC;QAC3B,IAAI,CAAC,UAAU,GAAG,IAAI,CAAC,mBAAmB,CAAC,kBAAkB,CAAC,CAAC;IACjE,CAAC;IAED,uBAAuB,CAAC,kBAAiC;QACvD,IAAI,IAAI,CAAC,cAAc,IAAI,IAAI,CAAC,UAAU,KAAK,IAAI,CAAC,cAAc,EAAE,CAAC;YACnE,IAAI,kBAAkB,EAAE,CAAC;gBACvB,IAAI,CAAC,oBAAoB,CAAC,kBAAkB,CAAC,CAAC;gBAC9C,OAAO;YACT,CAAC;YAED,IAAI,CAAC,iBAAiB,EAAE,CAAC;QAC3B,CAAC;IACH,CAAC;CACF","sourcesContent":["import type { BlobStore } from \"../data/blobs/blobContracts\";\nimport { createBlobStore } from \"../data/blobs/createBlobStore\";\nimport { createMemoryBlobStore } from \"../data/blobs/memoryBlobStore\";\n\nexport type BlobStoreFactory = (namespace: string) => BlobStore;\n\nexport class Blobs {\n private readonly ephemeralStore = createMemoryBlobStore();\n private identityScoped = false;\n private readonly createIdentityStore: BlobStoreFactory;\n private storeValue: BlobStore;\n\n constructor(\n store?: BlobStore | undefined,\n createIdentityStore: BlobStoreFactory = createBlobStore,\n ) {\n this.createIdentityStore = createIdentityStore;\n this.storeValue = store ?? this.ephemeralStore;\n }\n\n get store(): BlobStore {\n return this.storeValue;\n }\n\n useEphemeralStore(): void {\n this.identityScoped = false;\n this.storeValue = this.ephemeralStore;\n }\n\n useIdentityNamespace(signingFingerprint: string): void {\n this.identityScoped = true;\n this.storeValue = this.createIdentityStore(signingFingerprint);\n }\n\n updateIdentityNamespace(signingFingerprint: string | null): void {\n if (this.identityScoped || this.storeValue === this.ephemeralStore) {\n if (signingFingerprint) {\n this.useIdentityNamespace(signingFingerprint);\n return;\n }\n\n this.useEphemeralStore();\n }\n }\n}\n"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file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,EAAE,YAAY,CAAC,OAAO,CAAC;SAC/B,CAAC,CAAC;IACL,CAAC;IAED,eAAe;QACb,OAAO,2CAA2C,CAChD,IAAI,CAAC,cAAc,CAAC,aAAa,EAAE,EACnC,IAAI,CAAC,cAAc,CAAC,kBAAkB,CACvC,CAAC;IACJ,CAAC;CACF","sourcesContent":["import { DEFAULT_DOCUMENT_KIND } from \"../data/documents/documentConstants\";\nimport type { DocumentSummary } from \"../data/documents/documentSummary\";\nimport { inheritPrincipalHistoryProtection } from \"../data/principals/principalHistoryRuntime\";\nimport {\n type ContainerContentsStore,\n type ContainerContentsStoreOptions,\n getOrCreateContainerContentsStore,\n} from \"../stores/container-contents\";\nimport { openDocumentStore } from \"../stores/documents\";\nimport { relinkDocumentStoreWithCommitSideEffect } from \"../stores/documents/documentStore/internalRelink\";\nimport {\n type BlobInfoInput,\n type BlobInfoList,\n listBlobInfo,\n} from \"../workflows/container-contents/blobInfo\";\nimport {\n type ContainerInfo,\n loadContainerInfo,\n} from \"../workflows/container-contents/containerInfo\";\nimport {\n type DocumentAttributionRangesInput,\n type DocumentAttributionRangesPage,\n loadDocumentAttributionRanges,\n} from \"../workflows/container-contents/documentAttributionRanges\";\nimport {\n type DocumentInfo,\n loadDocumentInfo,\n} from \"../workflows/container-contents/documentInfo\";\nimport {\n purgeLocalContainerDocument,\n purgeRemoteContainerDocument,\n} from \"../workflows/container-contents/documentPurge\";\nimport {\n type ContainerDocumentQueries,\n createContainerDocumentQueriesFromRuntime,\n} from \"../workflows/container-contents/documentQueries\";\nimport {\n activateDocumentLink,\n addDocumentLink,\n canMutateDocumentLink,\n canMutateLocalDocumentLink,\n type DocumentStructuralMutationHost,\n moveDocumentLink,\n removeDocumentLink,\n} from \"../workflows/container-contents/documentStructure\";\nimport { createContainerContentsDocumentProjectionUserKeyResolver } from \"../workflows/container-contents/projectionKeys\";\nimport {\n type ContainerContentsStoreWorkflowRuntime,\n createContainerContentsDocumentsRuntime,\n createContainerContentsStoreWorkflowRuntime,\n} from \"../workflows/container-contents/runtime\";\nimport { createContainerDocumentObjectSyncState } from \"../workflows/container-contents/syncState\";\nimport type { DocumentsWorkflowRuntime } from \"../workflows/documents\";\nimport type {\n ContainerContents,\n ContainerDocumentLinks,\n ContainerInfoInput,\n DocumentInfoInput,\n MergeDocumentSummary,\n MoveDocumentToContainerInput,\n OpenContainerDocumentInput,\n} from \"./containerContentsTypes\";\nimport { discoverContainerDocumentsForRuntime } from \"./containerDocumentDiscovery\";\nimport {\n createOrganizationReadModelCoordinator,\n type OrganizationReadModelCoordinator,\n} from \"./organizations/organizationReadModels\";\nimport type {\n InternalRuntime,\n InternalWorkflowRuntimeInput,\n} from \"./workflowRuntime\";\n\nexport type {\n ContainerContentsContextValue,\n ContainerContentsStore,\n ContainerContentsStoreOptions,\n ContainerNode,\n} from \"../stores/container-contents\";\nexport type {\n BlobInfo,\n BlobInfoAttachmentKind,\n BlobInfoDocumentReference,\n BlobInfoInput,\n BlobInfoList,\n BlobInfoSort,\n BlobInfoSortDirection,\n BlobInfoSortKey,\n} from \"../workflows/container-contents/blobInfo\";\nexport type {\n ContainerInfo,\n ContainerShareAccessLevel,\n} from \"../workflows/container-contents/containerInfo\";\nexport type {\n DocumentAttributionRangesInput,\n DocumentAttributionRangesPage,\n} from \"../workflows/container-contents/documentAttributionRanges\";\nexport type { DocumentInfo } from \"../workflows/container-contents/documentInfo\";\nexport type {\n ContainerDocumentQueries,\n ContainerDocumentSidebarRow,\n ContainerItemRow,\n ContainerItemSort,\n ContainerItemSortDirection,\n ContainerItemSortKey,\n} from \"../workflows/container-contents/documentQueries\";\nexport type { SetLinkedContainerIdsForDocument } from \"../workflows/container-contents/documentStructure\";\nexport type {\n PendingWriteQueueItem,\n PendingWriteQueueItemStatus,\n PendingWriteQueueObjectKind,\n PendingWriteQueueOperation,\n PendingWriteQueueOperationKind,\n PendingWriteQueueOperationStatus,\n} from \"../workflows/container-contents/pendingWrites\";\nexport type {\n ContainerDocumentObjectSyncState,\n ContainerDocumentObjectSyncStatus,\n} from \"../workflows/container-contents/syncState\";\nexport type {\n ContainerContents,\n ContainerDocumentLinkInput,\n ContainerDocumentLinks,\n ContainerInfoInput,\n DocumentInfoInput,\n LinkDocumentToContainerInput,\n MergeDocumentSummary,\n MoveDocumentToContainerInput,\n OpenContainerDocumentInput,\n PurgeDocumentInput,\n PurgeDocumentResult,\n SetActiveDocumentContainerInput,\n UnlinkDocumentFromContainerInput,\n} from \"./containerContentsTypes\";\n\nexport { createContainerDocumentObjectSyncState };\n\nexport function createContainerContents(\n runtime: InternalRuntime,\n): ContainerContents {\n return new ContainerContentsService(runtime);\n}\n\nfunction createDocumentLinkHost(\n runtime: ContainerDocumentLinks,\n mergeDocumentSummary: MergeDocumentSummary,\n): DocumentStructuralMutationHost<DocumentsWorkflowRuntime> {\n return {\n documentWorkflowRuntime: runtime.documentRuntime,\n mergeDocumentSummary,\n openDocumentStore: (input) => {\n const store = runtime.openDocument({\n containerId: input.containerId,\n documentId: input.documentId,\n localId: input.localId,\n });\n return {\n ...store,\n relink: ({ commitSideEffect, ...relinkInput }) =>\n commitSideEffect\n ? relinkDocumentStoreWithCommitSideEffect(\n store,\n relinkInput,\n commitSideEffect,\n )\n : store.relink(relinkInput),\n };\n },\n };\n}\n\nfunction moveDocumentLinkNote(\n input: Pick<MoveDocumentToContainerInput, \"note\" | \"sourceContainerId\">,\n): DocumentSummary {\n if (\n input.note.documentId &&\n input.sourceContainerId &&\n input.sourceContainerId !== input.note.containerId\n ) {\n return { ...input.note, containerId: input.sourceContainerId };\n }\n\n return input.note;\n}\n\ninterface ContainerInfoOrganizationScope {\n readonly domainScope: InternalWorkflowRuntimeInput[\"state\"][\"domainScope\"];\n readonly organizationId: string;\n readonly userId: string;\n}\n\nfunction readyExecSql(\n runtime: InternalWorkflowRuntimeInput,\n): InternalWorkflowRuntimeInput[\"infra\"][\"execSql\"] | null {\n return runtime.infra.dbStatus === \"ready\" ? runtime.infra.execSql : null;\n}\n\nfunction isActiveContainerInfoOrganizationScope(\n runtime: InternalWorkflowRuntimeInput,\n scope: ContainerInfoOrganizationScope,\n): boolean {\n return (\n runtime.auth.isAuthenticated &&\n runtime.auth.organizationId === scope.organizationId &&\n runtime.auth.userId === scope.userId &&\n runtime.state.domainScope === scope.domainScope\n );\n}\n\nfunction purgeDocumentFromLinks(input: {\n readonly document: Parameters<ContainerDocumentLinks[\"purgeDocument\"]>[0];\n readonly resolveProjectionUserKey: ContainerDocumentLinks[\"resolveProjectionUserKey\"];\n readonly runtime: ContainerDocumentLinks;\n}) {\n const { note } = input.document;\n if (!note.documentId) {\n return purgeLocalContainerDocument({\n noteId: note.id,\n runtime: input.runtime,\n });\n }\n return purgeRemoteContainerDocument({\n documentId: note.documentId,\n documentKind: note.documentKind ?? DEFAULT_DOCUMENT_KIND,\n noteId: note.id,\n resolveProjectionUserKey: input.resolveProjectionUserKey,\n runtime: input.runtime,\n });\n}\n\nclass ContainerContentsService implements ContainerContents {\n private readonly organizationReadModels: OrganizationReadModelCoordinator;\n\n constructor(private readonly runtimeService: InternalRuntime) {\n this.organizationReadModels =\n createOrganizationReadModelCoordinator(runtimeService);\n }\n\n openTree(\n options?: ContainerContentsStoreOptions | undefined,\n ): ContainerContentsStore {\n const runtime = this.workflowRuntime();\n const store = getOrCreateContainerContentsStore(\n runtime.state.domainScope,\n runtime,\n options,\n );\n return store;\n }\n\n documentQueries(): ContainerDocumentQueries {\n return createContainerDocumentQueriesFromRuntime(this.workflowRuntime());\n }\n\n documentLinks(): ContainerDocumentLinks {\n const runtime = this.workflowRuntime();\n const resolveProjectionUserKey =\n createContainerContentsDocumentProjectionUserKeyResolver(runtime);\n const documentRuntime = (containerId: string | null) =>\n createContainerContentsDocumentsRuntime(runtime, containerId);\n const openContainerDocument = (input: OpenContainerDocumentInput) =>\n openDocumentStore(\n runtime.state.domainScope,\n input.localId,\n documentRuntime(input.containerId),\n input.documentId ?? null,\n input.initialText,\n input.initialDocumentKind,\n { deferInitialUpdate: input.deferInitialUpdate },\n );\n const documentLinks: ContainerDocumentLinks = {\n ...runtime,\n documentRuntime,\n openDocument: openContainerDocument,\n setActiveDocumentContainer: (input) =>\n activateDocumentLink({\n host: createDocumentLinkHost(\n documentLinks,\n input.mergeDocumentSummary,\n ),\n note: input.note,\n runtime: documentLinks,\n targetContainerId: input.targetContainerId,\n }),\n canMutateDocumentLinks: canMutateDocumentLink(runtime),\n canMutateUnsyncedDocumentLinks: canMutateLocalDocumentLink(runtime),\n linkDocumentToContainer: (input) =>\n addDocumentLink({\n host: createDocumentLinkHost(\n documentLinks,\n input.mergeDocumentSummary,\n ),\n note: input.note,\n runtime: documentLinks,\n scheduleSync: () => this.openTree().requestSync(),\n setLinkedContainerIdsForDocument:\n input.setLinkedContainerIdsForDocument,\n targetContainerId: input.targetContainerId,\n }),\n moveDocumentToContainer: (input) =>\n moveDocumentLink({\n expandNode: input.expandNode,\n host: createDocumentLinkHost(\n documentLinks,\n input.mergeDocumentSummary,\n ),\n note: moveDocumentLinkNote(input),\n replaceLinkedContainers: input.replaceLinkedContainers,\n runtime: documentLinks,\n scheduleSync: () => this.openTree().requestSync(),\n setLinkedContainerIdsForDocument:\n input.setLinkedContainerIdsForDocument,\n targetContainerId: input.targetContainerId,\n }),\n purgeDocument: (document) =>\n purgeDocumentFromLinks({\n document,\n resolveProjectionUserKey,\n runtime: documentLinks,\n }),\n resolveProjectionUserKey,\n unlinkDocumentFromContainer: (input) =>\n removeDocumentLink({\n host: createDocumentLinkHost(\n documentLinks,\n input.mergeDocumentSummary,\n ),\n note: input.note,\n removedContainerId: input.removedContainerId,\n runtime: documentLinks,\n scheduleSync: () => this.openTree().requestSync(),\n setLinkedContainerIdsForDocument:\n input.setLinkedContainerIdsForDocument,\n }),\n };\n\n return inheritPrincipalHistoryProtection(runtime, documentLinks);\n }\n\n discoverContainerDocuments(\n containerId: string,\n ): Promise<ReadonlyArray<DocumentSummary> | null> {\n return discoverContainerDocumentsForRuntime({\n containerId,\n runtimeService: this.runtimeService,\n });\n }\n\n pullDocumentContent(input: {\n containerId: string;\n localId: string;\n documentId?: string | null | undefined;\n }): void {\n const runtime = this.workflowRuntime();\n const store = openDocumentStore(\n runtime.state.domainScope,\n input.localId,\n createContainerContentsDocumentsRuntime(runtime, input.containerId),\n input.documentId ?? null,\n );\n store.requestRemoteSync();\n }\n\n loadContainerInfo(input: ContainerInfoInput): Promise<ContainerInfo> {\n const runtime = this.runtimeService.workflowInput();\n const organizationScope =\n runtime.auth.isAuthenticated &&\n runtime.auth.organizationId &&\n runtime.auth.userId\n ? {\n domainScope: runtime.state.domainScope,\n organizationId: runtime.auth.organizationId,\n userId: runtime.auth.userId,\n }\n : null;\n const cachedContainerProjection =\n input.remoteInfoMode === \"always\"\n ? null\n : this.openTree().getCachedContainerWriterProjection(input.containerId);\n return loadContainerInfo({\n ...input,\n apiClient: runtime.apiClient,\n containerProjection: cachedContainerProjection,\n execSql: readyExecSql(runtime),\n loadOrganizationGroups: async () => {\n if (\n !organizationScope ||\n !isActiveContainerInfoOrganizationScope(\n this.runtimeService.workflowInput(),\n organizationScope,\n )\n ) {\n return [];\n }\n // Organization groups are disposable presentation data. Container\n // writer projections remain the authority for grants and access.\n const projection = await this.organizationReadModels.loadLocal(\n organizationScope.organizationId,\n );\n return isActiveContainerInfoOrganizationScope(\n this.runtimeService.workflowInput(),\n organizationScope,\n )\n ? (projection?.groups ?? [])\n : [];\n },\n parentId: input.parentId ?? null,\n });\n }\n\n loadDocumentInfo(input: DocumentInfoInput): Promise<DocumentInfo> {\n const runtime = this.runtimeService.workflowInput();\n return loadDocumentInfo({\n ...input,\n apiClient: runtime.apiClient,\n execSql: readyExecSql(runtime),\n reportSecurityIncident: runtime.util.reportSecurityIncident,\n });\n }\n\n loadDocumentEditAttribution(\n documentId: string,\n ): ReturnType<ContainerContents[\"loadDocumentEditAttribution\"]> {\n return this.runtimeService\n .workflowInput()\n .apiClient.getDocumentEditAttribution(documentId);\n }\n\n loadDocumentAttributionRanges(\n input: DocumentAttributionRangesInput,\n ): Promise<DocumentAttributionRangesPage> {\n return loadDocumentAttributionRanges({\n apiClient: this.runtimeService.workflowInput().apiClient,\n query: input,\n });\n }\n\n listBlobInfo(input: BlobInfoInput = {}): Promise<BlobInfoList> {\n const runtime = this.runtimeService.workflowInput();\n return listBlobInfo({\n ...input,\n execSql: readyExecSql(runtime),\n });\n }\n\n workflowRuntime(): ContainerContentsStoreWorkflowRuntime {\n return createContainerContentsStoreWorkflowRuntime(\n this.runtimeService.workflowInput(),\n this.runtimeService.adoptRootContainer,\n );\n }\n}\n"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"containerContentsTypes.js","sourceRoot":"","sources":["containerContentsTypes.ts"],"names":[],"mappings":"","sourcesContent":["import type { DocumentEditAttributionResponse } from \"@tearleads/validators/response\";\nimport type { StoredDocumentKind } from \"../data/documents/documentKinds\";\nimport type { DocumentSummary } from \"../data/documents/documentSummary\";\nimport type {\n ContainerContentsStore,\n ContainerContentsStoreOptions,\n ContainerContentsStoreRuntime,\n} from \"../stores/container-contents\";\nimport type { DocumentStore } from \"../stores/documents\";\nimport type {\n BlobInfoInput,\n BlobInfoList,\n} from \"../workflows/container-contents/blobInfo\";\nimport type {\n ContainerInfo,\n ContainerInfoRemoteMode,\n} from \"../workflows/container-contents/containerInfo\";\nimport type {\n DocumentAttributionRangesInput,\n DocumentAttributionRangesPage,\n} from \"../workflows/container-contents/documentAttributionRanges\";\nimport type {\n DocumentInfo,\n DocumentInfoRemoteMode,\n} from \"../workflows/container-contents/documentInfo\";\nimport type { ContainerDocumentQueries } from \"../workflows/container-contents/documentQueries\";\nimport type { SetLinkedContainerIdsForDocument } from \"../workflows/container-contents/documentStructure\";\nimport type { ContainerContentsProjectionUserKeyResolver } from \"../workflows/container-contents/projectionKeys\";\nimport type { ContainerContentsWorkflowRuntime } from \"../workflows/container-contents/runtime\";\nimport type { DocumentsWorkflowRuntime } from \"../workflows/documents\";\n\n/**\n * Selects the container to inspect.\n *\n * Container info combines local SQLite timestamps with optional remote writer\n * projection details. Remote details include direct and inherited grants,\n * organization groups, security-path metadata, and sync watermarks for the\n * parent, child-container, and document lanes.\n *\n * Fields:\n * - `containerId`: Container id to inspect.\n * - `parentId`: Known parent id used when the container has not been synced\n * locally yet. Synced local state wins when available.\n * - `remoteInfoMode`: Controls whether remote projection details are fetched.\n */\nexport interface ContainerInfoInput {\n containerId: string;\n parentId?: string | null | undefined;\n remoteInfoMode?: ContainerInfoRemoteMode | undefined;\n}\n\n/**\n * Selects the document to inspect.\n *\n * Document info combines local document state, local and pending attachment\n * rows, and optional remote writer projection details.\n *\n * Fields:\n * - `attributionRequestKey`: Optional freshness generation used to coalesce\n * duplicate attribution reads without joining requests across invalidation.\n * - `localId`: Local document id stored in the client database.\n * - `remoteInfoMode`: Controls whether remote projection details are fetched.\n */\nexport interface DocumentInfoInput {\n attributionRequestKey?: string | undefined;\n localId: string;\n remoteInfoMode?: DocumentInfoRemoteMode | undefined;\n}\n\nexport type MergeDocumentSummary = (nextDocument: DocumentSummary) => void;\n\nexport interface OpenContainerDocumentInput {\n readonly containerId: string | null;\n /** A file attach follows creation and carries the birth; see the store. */\n readonly deferInitialUpdate?: boolean | undefined;\n readonly documentId?: string | null | undefined;\n readonly initialDocumentKind?: StoredDocumentKind | undefined;\n readonly initialText?: string | undefined;\n readonly localId: string;\n}\n\nexport interface ContainerDocumentLinkInput {\n readonly mergeDocumentSummary: MergeDocumentSummary;\n readonly note: DocumentSummary;\n}\n\nexport interface MoveDocumentToContainerInput\n extends ContainerDocumentLinkInput {\n readonly expandNode: (nodeId: string) => void;\n readonly replaceLinkedContainers?: boolean | undefined;\n readonly setLinkedContainerIdsForDocument: SetLinkedContainerIdsForDocument;\n readonly sourceContainerId?: string | null | undefined;\n readonly targetContainerId: string;\n}\n\nexport interface LinkDocumentToContainerInput\n extends ContainerDocumentLinkInput {\n readonly setLinkedContainerIdsForDocument: SetLinkedContainerIdsForDocument;\n readonly targetContainerId: string;\n}\n\nexport interface UnlinkDocumentFromContainerInput\n extends ContainerDocumentLinkInput {\n readonly removedContainerId: string;\n readonly setLinkedContainerIdsForDocument: SetLinkedContainerIdsForDocument;\n}\n\nexport interface SetActiveDocumentContainerInput\n extends ContainerDocumentLinkInput {\n readonly targetContainerId: string;\n}\n\nexport interface PurgeDocumentInput {\n /** The current local summary of the document to destroy. */\n readonly note: DocumentSummary;\n}\n\nexport interface PurgeDocumentResult {\n readonly documentId: string;\n readonly purgedAt: string;\n readonly reclaimedBlobStorageKeys: ReadonlyArray<string>;\n}\n\nexport interface ContainerDocumentLinks\n extends ContainerContentsWorkflowRuntime {\n documentRuntime(containerId: string | null): DocumentsWorkflowRuntime;\n openDocument(input: OpenContainerDocumentInput): DocumentStore;\n setActiveDocumentContainer(\n input: SetActiveDocumentContainerInput,\n ): Promise<DocumentSummary | null>;\n readonly canMutateDocumentLinks: boolean;\n readonly canMutateUnsyncedDocumentLinks: boolean;\n linkDocumentToContainer(\n input: LinkDocumentToContainerInput,\n ): Promise<DocumentSummary | null>;\n moveDocumentToContainer(\n input: MoveDocumentToContainerInput,\n ): Promise<{ linksChanged: boolean; note: DocumentSummary | null }>;\n /**\n * Permanently destroy a local-only document, or submit and verify a signed\n * terminal purge for a remote document. Remote purge requires exactly one\n * remaining container link and returns null on refusal or verification\n * failure.\n */\n purgeDocument(input: PurgeDocumentInput): Promise<PurgeDocumentResult | null>;\n readonly resolveProjectionUserKey: ContainerContentsProjectionUserKeyResolver;\n unlinkDocumentFromContainer(\n input: UnlinkDocumentFromContainerInput,\n ): Promise<DocumentSummary | null>;\n}\n\n/**\n * High-level container-content service for tree state, document lists, document\n * links, discovery, and diagnostics.\n *\n * The facade owns the normal SDK protocol: it supplies the API client,\n * referenced-principal policy cache, local document query helpers, link\n * projection, tombstone handling, and sync watermarks. Consumers that need a\n * custom persistence protocol can call the lower-level workflows directly from\n * `@tearleads/client-sdk`.\n */\nexport interface ContainerContents {\n /**\n * Open the container tree state store for the current SDK runtime.\n *\n * The store is cached per domain scope and created from the current runtime\n * snapshot. Long-lived hosts should call `updateRuntime` after runtime\n * changes, such as from a React effect.\n */\n openTree(\n options?: ContainerContentsStoreOptions | undefined,\n ): ContainerContentsStore;\n\n /**\n * Create local document query helpers for container contents.\n *\n * The facade is bound to the current SDK runtime snapshot, including the\n * active SQLite executor. Recreate it when the SDK runtime version changes.\n */\n documentQueries(): ContainerDocumentQueries;\n\n /**\n * Create the default document-link workflow helper.\n *\n * The returned object includes the current container-contents runtime,\n * the document projection-key resolver, mutation readiness, document store\n * priming, and container document-link mutations. Product stores can pass\n * this bundle around without rebuilding SDK runtime plumbing themselves.\n */\n documentLinks(): ContainerDocumentLinks;\n\n /**\n * Discover remote documents linked to one container.\n *\n * The method pages the remote container-document lane, writes discovered\n * document summaries into local SQLite, replaces the local link projection for\n * each discovered document, applies applicable tombstones, caches referenced\n * principal policies needed by newly visible documents, and advances the\n * container-document watermark after the local apply completes.\n *\n * One call verifies a bounded batch. Pending evidence is durable; a later\n * explicit call or background reconciliation resumes it.\n *\n * Returns the summaries touched by the apply, or `null` when the database or\n * listing is unavailable, a trust reset cancels the pass, or all evidence is\n * pending. Pending evidence may advance the watermark after durable staging.\n *\n * Parameters:\n * - `containerId`: Remote container id whose document lane should be listed.\n */\n discoverContainerDocuments(\n containerId: string,\n ): Promise<ReadonlyArray<DocumentSummary> | null>;\n\n /**\n * Sync the content of a single document that no mini-app has opened.\n *\n * Discovery only records a document's metadata + an empty content shell, and a\n * document's locally authored content is only pushed once its store syncs; both\n * normally happen lazily when a mini-app opens the document. Some documents are\n * never opened yet still need to sync — notably the organization profile\n * document, which lives in an org's Members-granted metadata container and\n * holds the org display name. This opens a transient document store (registered\n * under the container's keys, so it can decrypt) and schedules a remote sync\n * pass. The pass both pushes the store's pending updates and merges + persists\n * any remote body, so the same call lets an owning device publish its profile\n * content and a member device pull it. `documentId` may be omitted; the store\n * then resolves it from the persisted record (the owning device keys the\n * document under a local alias, not its server id).\n */\n pullDocumentContent(input: {\n containerId: string;\n localId: string;\n documentId?: string | null | undefined;\n }): void;\n\n /**\n * Load diagnostic information for one local document.\n *\n * Local details are available when SQLite is ready. Remote details are loaded\n * from the document writer projection according to `remoteInfoMode`; the\n * default is `\"if-synced\"`.\n */\n loadDocumentInfo(input: DocumentInfoInput): Promise<DocumentInfo>;\n\n /**\n * Fetch a synced document's compact edit-attribution segments (peer -> writer\n * intervals) on their own, without the writer-projection/attachment work\n * `loadDocumentInfo` also does. Resolves to `null` on any request failure.\n * Callers must ignore the segments when `truncated` is set — a truncated\n * interval list can drop a peer's segments and mis-resolve it.\n */\n loadDocumentEditAttribution(\n documentId: string,\n ): Promise<DocumentEditAttributionResponse | null>;\n\n /** Load one revision-bound page of detailed per-upload edit attribution. */\n loadDocumentAttributionRanges(\n input: DocumentAttributionRangesInput,\n ): Promise<DocumentAttributionRangesPage>;\n\n /**\n * List local blob projections and pending attachment bytes grouped by blob.\n *\n * This is a reverse lookup query: callers can search by server blob id,\n * local storage key, document id/title, attachment slot, or MIME metadata and\n * then traverse matching blobs back to their owning local documents.\n */\n listBlobInfo(input?: BlobInfoInput | undefined): Promise<BlobInfoList>;\n\n /**\n * Load diagnostic information for one container.\n *\n * Local details include synced timestamps. Remote details are loaded from the\n * container writer projection according to `remoteInfoMode`; the default is\n * `\"always\"`. Pass `parentId` when inspecting a container before its local row\n * has been synced.\n */\n loadContainerInfo(input: ContainerInfoInput): Promise<ContainerInfo>;\n\n /**\n * Create a workflow runtime for advanced container-content workflows.\n *\n * Prefer the high-level methods on this service for the default SDK protocol.\n * Use this when constructing lower-level stores or custom workflows that need\n * access to the current runtime snapshot.\n */\n workflowRuntime(): ContainerContentsStoreRuntime;\n}\n"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"containerDocumentDiscovery.js","sourceRoot":"","sources":["containerDocumentDiscovery.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,+BAA+B,EAAE,MAAM,qEAAqE,CAAC;AACtH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,CAAC;QAC/D,QAAQ,EAAE,CAAC,OAAO,CAAC;QACnB,cAAc;KACf,CAAC,CAAC;IACH,IAAI,OAAO,EAAE,MAAM,KAAK,UAAU;QAAE,MAAM,OAAO,CAAC,MAAM,CAAC;IACzD,OAAO,OAAO,EAAE,KAAK,IAAI,IAAI,CAAC;AAChC,CAAC","sourcesContent":["import type { DocumentSummary } from \"../data/documents/documentSummary\";\nimport { sqlContainerContentsPersistence } from \"../data/persistence/container-contents/containerContentsPersistence\";\nimport {\n holdContainerDocumentTombstones,\n listKnownContainerDocumentPlacements,\n listRetryableHeldContainerDocumentTombstones,\n loadLocalDocumentAccessEpoch,\n refuteContainerDocumentTombstoneHolds,\n} from \"../data/persistence/documents/containerDocumentTombstoneHoldsPersistence\";\nimport { createDocumentDiscoveryEvidenceStore } from \"../data/persistence/documents/documentDiscoveryEvidencePersistence\";\nimport { listContainerDocumentLanesFromApi } from \"../workflows/container-contents/containerDocumentListing\";\nimport { createDiscoveredDocumentVerifier } from \"../workflows/container-contents/documentDiscoveryEvidence\";\nimport {\n type ContainerDocumentDiscoveryLane,\n type ContainerDocumentDiscoveryOutcome,\n type ContainerDocumentDiscoveryOutcomeHandler,\n discoverContainerDocumentLanes,\n} from \"../workflows/container-contents/documentDiscoveryLanes\";\nimport { createContainerDocumentQueriesFromRuntime } from \"../workflows/container-contents/documentQueries\";\nimport {\n createContainerDocumentTombstoneVerifier,\n createDocumentHeadLinkSetLoader,\n} from \"../workflows/container-contents/documentTombstoneEvidence\";\nimport {\n type ContainerContentsWorkflowRuntime,\n createContainerContentsWorkflowRuntime,\n} from \"../workflows/container-contents/runtime\";\nimport { createRuntimePrincipalPolicyWarmer } from \"../workflows/principals/runtimePolicyWarmer\";\nimport type { InternalRuntime } from \"./workflowRuntime\";\n\nexport type { ContainerDocumentDiscoveryOutcome } from \"../workflows/container-contents/documentDiscoveryLanes\";\n\n/** One container to discover, with the reconciler's per-lane callbacks. */\nexport interface ContainerDocumentDiscoveryRequest {\n readonly containerId: string;\n readonly onFullListing?:\n | ((documentIds: ReadonlyArray<string>) => void)\n | undefined;\n readonly onPendingDiscovery?: ((delayMs: number) => void) | undefined;\n}\n\ntype ExecSql = ReturnType<InternalRuntime[\"workflowInput\"]>[\"infra\"][\"execSql\"];\n\nfunction createDiscoveryLane(input: {\n readonly containerOrganizationId: string | undefined;\n readonly evidenceStore: ReturnType<\n typeof createDocumentDiscoveryEvidenceStore\n >;\n readonly execSql: ExecSql;\n readonly queries: ReturnType<\n typeof createContainerDocumentQueriesFromRuntime\n >;\n readonly request: ContainerDocumentDiscoveryRequest;\n readonly runtime: ContainerContentsWorkflowRuntime;\n}): ContainerDocumentDiscoveryLane {\n const { containerOrganizationId, execSql, request, runtime } = input;\n const warmReferencedPrincipalPolicies =\n createRuntimePrincipalPolicyWarmer(runtime);\n const loadHead = createDocumentHeadLinkSetLoader(runtime);\n const loadEpoch = (documentId: string) =>\n loadLocalDocumentAccessEpoch(execSql, documentId);\n return {\n ...input.queries,\n cacheReferencedPrincipalPolicies: (references) =>\n containerOrganizationId\n ? warmReferencedPrincipalPolicies({\n organizationId: containerOrganizationId,\n references,\n })\n : Promise.resolve(),\n containerId: request.containerId,\n holdContainerDocumentTombstones: (tombstones) =>\n holdContainerDocumentTombstones(execSql, tombstones),\n listHeldContainerDocumentTombstones: (containerIds) =>\n listRetryableHeldContainerDocumentTombstones(execSql, containerIds),\n listKnownContainerDocumentPlacements: (placements) =>\n listKnownContainerDocumentPlacements(execSql, placements),\n onFullListing: request.onFullListing,\n refuteContainerDocumentTombstoneHolds: (placements) =>\n refuteContainerDocumentTombstoneHolds(execSql, placements),\n verifyContainerDocumentTombstones: createContainerDocumentTombstoneVerifier(\n containerOrganizationId,\n loadHead,\n loadEpoch,\n ),\n verifyDiscoveredDocuments: createDiscoveredDocumentVerifier(\n containerOrganizationId,\n loadHead,\n loadEpoch,\n input.evidenceStore,\n request.onPendingDiscovery,\n ),\n };\n}\n\n/**\n * Internal adapter shared by explicit discovery and background reconciliation:\n * one batched listing for every requested container, then per-container\n * verification scoped to each container's durable organization.\n */\nexport async function discoverContainerDocumentLanesForRuntime({\n onOutcome,\n requests,\n runtimeService,\n}: {\n readonly onOutcome?: ContainerDocumentDiscoveryOutcomeHandler | undefined;\n readonly requests: ReadonlyArray<ContainerDocumentDiscoveryRequest>;\n readonly runtimeService: InternalRuntime;\n}): Promise<ReadonlyArray<ContainerDocumentDiscoveryOutcome>> {\n const unlisted = (\n containerId: string,\n ): ContainerDocumentDiscoveryOutcome => ({\n containerId,\n status: \"fulfilled\",\n value: null,\n });\n const input = runtimeService.workflowInput();\n if (input.infra.dbStatus !== \"ready\") {\n return requests.map(({ containerId }) => unlisted(containerId));\n }\n const runtime = createContainerContentsWorkflowRuntime(input);\n const execSql = input.infra.execSql;\n const evidenceStore = createDocumentDiscoveryEvidenceStore(execSql);\n const queries = createContainerDocumentQueriesFromRuntime(runtime);\n // Capture the reset fence before reading any lane's scope, so a reset\n // between these reads and the listing cannot publish old-organization\n // evidence into its replacement.\n const generation = await evidenceStore.begin();\n const lanes: ContainerDocumentDiscoveryLane[] = [];\n for (const request of requests) {\n const stored =\n await sqlContainerContentsPersistence.loadContainerMetadataState(\n execSql,\n request.containerId,\n );\n if (stored)\n lanes.push(\n createDiscoveryLane({\n containerOrganizationId: stored.container.organizationId,\n evidenceStore,\n execSql,\n queries,\n request,\n runtime,\n }),\n );\n }\n const outcomes = await discoverContainerDocumentLanes({\n generation,\n lanes,\n listContainerDocumentLanes: (listed) =>\n listContainerDocumentLanesFromApi(runtime.apiClient, listed),\n loadContainerDocumentWatermark: queries.loadContainerDocumentWatermark,\n onOutcome,\n });\n const outcomeByContainerId = new Map(\n outcomes.map((outcome) => [outcome.containerId, outcome]),\n );\n return requests.map(\n ({ containerId }) =>\n outcomeByContainerId.get(containerId) ?? unlisted(containerId),\n );\n}\n\n/** Discovers one container; a rejected lane rethrows its failure. */\nexport async function discoverContainerDocumentsForRuntime({\n runtimeService,\n ...request\n}: ContainerDocumentDiscoveryRequest & {\n readonly runtimeService: InternalRuntime;\n}): Promise<ReadonlyArray<DocumentSummary> | null> {\n const [outcome] = await discoverContainerDocumentLanesForRuntime({\n requests: [request],\n runtimeService,\n });\n if (outcome?.status === \"rejected\") throw outcome.reason;\n return outcome?.value ?? null;\n}\n"]}
|
package/client/database.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"database.js","sourceRoot":"","sources":["database.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,aAAa,GAGd,MAAM,0BAA0B,CAAC;AAClC,OAAO,EAAE,iBAAiB,EAAE,MAAM,eAAe,CAAC;AAoBlD,MAAM,OAAO,QAAQ;IACF,SAAS,GAAG,iBAAiB,EAAE,CAAC;IACzC,aAAa,GAAqB;QACxC,MAAM,EAAE,IAAI;QACZ,OAAO,EAAE,IAAI;QACb,EAAE,EAAE,IAAI;QACR,MAAM,EAAE,MAAM;KACf,CAAC;IAEF,YAAY,OAAqC;QAC/C,IAAI,OAAO,EAAE,CAAC;YACZ,IAAI,CAAC,SAAS,CAAC,OAAO,CAAC,CAAC;QAC1B,CAAC;IACH,CAAC;IAED,IAAI,MAAM;QACR,OAAO,IAAI,CAAC,aAAa,CAAC,MAAM,CAAC;IACnC,CAAC;IAED,IAAI,OAAO;QACT,OAAO,IAAI,CAAC,aAAa,CAAC,OAAO,CAAC;IACpC,CAAC;IAED,IAAI,EAAE;QACJ,OAAO,IAAI,CAAC,aAAa,CAAC,EAAE,CAAC;IAC/B,CAAC;IAED,IAAI,QAAQ;QACV,OAAO,IAAI,CAAC,aAAa,CAAC;IAC5B,CAAC;IAED,IAAI,MAAM;QACR,OAAO,IAAI,CAAC,aAAa,CAAC,MAAM,CAAC;IACnC,CAAC;IAED,KAAK,CAAC,SAAyB,MAAM;QACnC,IAAI,CAAC,WAAW,CAAC;YACf,MAAM,EAAE,IAAI;YACZ,OAAO,EAAE,IAAI;YACb,EAAE,EAAE,IAAI;YACR,MAAM;SACP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W,CAAC,IAAsB;QACxC,MAAM,QAAQ,GAAG,IAAI,CAAC,aAAa,CAAC;QACpC,IACE,QAAQ,CAAC,MAAM,KAAK,IAAI,CAAC,MAAM;YAC/B,QAAQ,CAAC,OAAO,KAAK,IAAI,CAAC,OAAO;YACjC,QAAQ,CAAC,EAAE,KAAK,IAAI,CAAC,EAAE;YACvB,QAAQ,CAAC,MAAM,KAAK,IAAI,CAAC,MAAM,EAC/B,CAAC;YACD,OAAO;QACT,CAAC;QAED,IAAI,CAAC,aAAa,GAAG,IAAI,CAAC;QAC1B,IAAI,CAAC,SAAS,CAAC,MAAM,EAAE,CAAC;IAC1B,CAAC;CACF","sourcesContent":["import {\n createExecSql,\n type ExecSql,\n type ExecSqlClientLike,\n} from \"../data/sqlite/sqlSchema\";\nimport { createListenerSet } from \"./listenerSet\";\n\nexport type DatabaseStatus = \"idle\" | \"ready\" | \"error\" | \"terminated\";\n\nexport interface DatabaseSnapshot {\n client: ExecSqlClientLike | null;\n execSql: ExecSql | null;\n id: string | null;\n status: DatabaseStatus;\n}\n\nexport type DatabaseListener = () => void;\n\nexport interface DatabaseOptions {\n client?: ExecSqlClientLike | null | undefined;\n execSql?: ExecSql | null | undefined;\n id?: string | null | undefined;\n status?: DatabaseStatus | undefined;\n}\n\nexport class Database {\n private readonly listeners = createListenerSet();\n private snapshotValue: DatabaseSnapshot = {\n client: null,\n execSql: null,\n id: null,\n status: \"idle\",\n };\n\n constructor(options?: DatabaseOptions | undefined) {\n if (options) {\n this.configure(options);\n }\n }\n\n get client(): ExecSqlClientLike | null {\n return this.snapshotValue.client;\n }\n\n get execSql(): ExecSql | null {\n return this.snapshotValue.execSql;\n }\n\n get id(): string | null {\n return this.snapshotValue.id;\n }\n\n get snapshot(): DatabaseSnapshot {\n return this.snapshotValue;\n }\n\n get status(): DatabaseStatus {\n return this.snapshotValue.status;\n }\n\n clear(status: DatabaseStatus = \"idle\"): void {\n this.setSnapshot({\n client: null,\n execSql: null,\n id: null,\n status,\n });\n }\n\n configure(options: DatabaseOptions): void {\n const client = options.client ?? null;\n const execSql = options.execSql ?? (client ? createExecSql(client) : null);\n if (options.status === \"ready\" && !execSql) {\n throw new Error(\n \"A ready SQLite database requires a configured executor or client.\",\n );\n }\n\n this.setSnapshot({\n client,\n execSql,\n id: options.id ?? null,\n status: options.status ?? (execSql ? \"ready\" : \"idle\"),\n });\n }\n\n requireExecSql(operation = \"This operation\"): ExecSql {\n if (!this.snapshotValue.execSql) {\n throw new Error(`${operation} requires a configured SQLite executor.`);\n }\n\n return this.snapshotValue.execSql;\n }\n\n setClient(\n client: ExecSqlClientLike,\n options: Omit<DatabaseOptions, \"client\" | \"execSql\"> = {},\n ): void {\n this.configure({ ...options, client });\n }\n\n setExecSql(\n execSql: ExecSql,\n options: Omit<DatabaseOptions, \"client\" | \"execSql\"> = {},\n ): void {\n this.configure({ ...options, execSql });\n }\n\n subscribe = (listener: DatabaseListener): (() => void) =>\n this.listeners.subscribe(listener);\n\n private setSnapshot(next: DatabaseSnapshot): void {\n const previous = this.snapshotValue;\n if (\n previous.client === next.client &&\n previous.execSql === next.execSql &&\n previous.id === next.id &&\n previous.status === next.status\n ) {\n return;\n }\n\n this.snapshotValue = next;\n this.listeners.notify();\n }\n}\n"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"deviceFirst.js","sourceRoot":"","sources":["deviceFirst.ts"],"names":[],"mappings":"AACA,OAAO,EACL,4BAA4B,EAC5B,gCAAgC,EAChC,0BAA0B,GAC3B,MAAM,8BAA8B,CAAC;AACtC,OAAO,EAGL,mCAAmC,EACnC,2BAA2B,EAC3B,2BAA2B,GAC5B,MAAM,8BAA8B,CAAC;AACtC,OAAO,EAAE,iBAAiB,EAAE,MAAM,qBAAqB,CAAC;AACxD,OAAO,EACL,mCAAmC,EACnC,qCAAqC,EACrC,6BAA6B,GAC9B,MAAM,8BAA8B,CAAC;AACtC,OAAO,EACL,+BAA+B,GAGhC,MAAM,4BAA4B,CAAC;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,kBAAkB,CAClC,CAAC;AACJ,CAAC","sourcesContent":["import type { DomainScope } from \"../data/shared/domainScope\";\nimport {\n disposeDomainSyncCoordinator,\n getOrCreateDomainSyncCoordinator,\n isDatabaseUnavailableError,\n} from \"../data/sync/syncCoordinator\";\nimport {\n type ContainerContentsStore,\n type ContainerContentsStoreOptions,\n isAutomaticRootCatchupContainerNode,\n isReconcilableContainerNode,\n isRemoteBackedContainerNode,\n} from \"../stores/container-contents\";\nimport { openDocumentStore } from \"../stores/documents\";\nimport {\n requestRegisteredDocumentRemoteSync,\n subscribeToPersistedDocumentDeletions,\n subscribeToPersistedDocuments,\n} from \"../stores/documents/registry\";\nimport {\n getOrCreateLocalProjectionStore,\n type LocalProjectionStore,\n type LocalProjectionView,\n} from \"../stores/local-projection\";\nimport {\n connectReconciliationTriggers,\n createReconciliationService,\n type ReconciliationHost,\n type ReconciliationService,\n systemReconciliationClock,\n} from \"../sync/reconciliation\";\nimport { listAllContainerDocumentIdsFromApi } from \"../workflows/container-contents/containerDocumentListing\";\nimport { probeUndiscoveredRemoteDocumentBatch } from \"../workflows/container-contents/documentHydrationProbe\";\nimport {\n type ContainerContentsStoreWorkflowRuntime,\n createContainerContentsDocumentsRuntime,\n createContainerContentsStoreWorkflowRuntime,\n} from \"../workflows/container-contents/runtime\";\nimport type { ContainerContents } from \"./containerContents\";\nimport { discoverContainerDocumentLanesForRuntime } from \"./containerDocumentDiscovery\";\nimport { createReconciledDocumentContentPuller } from \"./reconciledDocumentContentPull\";\nimport type { InternalRuntime } from \"./workflowRuntime\";\n\nexport type { LocalProjectionView } from \"../stores/local-projection\";\n\n/** One domain scope's local read, local-write, and reconciliation handles. */\nexport interface DeviceFirstContainerContents {\n /**\n * Locally durable container tree and mutation store. Ordinary tree writes\n * update this store after local persistence and queue remote convergence in\n * the background; security-sensitive remote operations keep their explicit\n * online requirements.\n */\n readonly containerStore: ContainerContentsStore;\n /** Background remote reconciliation; never awaited for first paint. */\n readonly reconciler: ReconciliationService;\n /** Synchronously readable container/document projection. */\n readonly view: LocalProjectionView;\n}\n\n/**\n * Device-first facade. Opens a shared scope that pairs immediate local reads\n * and locally durable writes with background remote convergence.\n */\nexport interface DeviceFirst {\n /** Open all device-first handles for the current domain scope. */\n open(\n options?: ContainerContentsStoreOptions | undefined,\n ): DeviceFirstContainerContents;\n /** Stop the current scope's reconciler (if one was created) on teardown. */\n dispose(): void;\n}\n\nexport function createDeviceFirst(\n runtimeService: InternalRuntime,\n containerContents: ContainerContents,\n): DeviceFirst {\n return new DeviceFirstService(runtimeService, containerContents);\n}\n\ninterface DeviceFirstScopeEntry {\n contents: DeviceFirstContainerContents;\n disconnectReconciliationTriggers: () => void;\n unsubscribePersistedDocumentDeletions: () => void;\n unsubscribePersistedDocuments: () => void;\n}\n\nfunction createInitialDocumentProbeHost(\n runtimeService: InternalRuntime,\n domainScope: ReconciliationHost[\"domainScope\"],\n): Pick<\n ReconciliationHost,\n | \"listContainerDocumentIds\"\n | \"probeUndiscoveredDocumentsBatch\"\n | \"reportInitialDocumentProbeComplete\"\n> {\n return {\n listContainerDocumentIds: (containerId) => {\n const runtime = createDeviceFirstWorkflowRuntime(runtimeService);\n return listAllContainerDocumentIdsFromApi({\n apiClient: runtime.apiClient,\n containerId,\n reportErrors: false,\n });\n },\n probeUndiscoveredDocumentsBatch: async (input) => {\n const runtime = createDeviceFirstWorkflowRuntime(runtimeService);\n return probeUndiscoveredRemoteDocumentBatch({\n ...input,\n host: {\n documentWorkflowRuntime: (containerId) =>\n createContainerContentsDocumentsRuntime(runtime, containerId),\n openDocumentStore: (target) =>\n openDocumentStore(\n domainScope,\n target.localId,\n target.runtime,\n target.documentId,\n ),\n },\n runtime,\n });\n },\n reportInitialDocumentProbeComplete: (requestedCount) => {\n runtimeService\n .workflowInput()\n .util.log(\n `Initial document hydration probe requested ${requestedCount} syncs`,\n );\n },\n };\n}\n\nclass DeviceFirstService implements DeviceFirst {\n // A real Map (not WeakMap) so dispose() can iterate every scope seen this\n // session. A running reconciler holds event subscriptions that keep an idle,\n // stale-scope service (and its scope) reachable anyway, so WeakMap bought no\n // GC here; the entries are released explicitly on dispose().\n private readonly entriesByScope = new Map<\n DomainScope,\n DeviceFirstScopeEntry\n >();\n\n constructor(\n private readonly runtimeService: InternalRuntime,\n private readonly containerContents: ContainerContents,\n ) {}\n\n open(\n options?: ContainerContentsStoreOptions | undefined,\n ): DeviceFirstContainerContents {\n return this.getOrCreateEntry(options).contents;\n }\n\n dispose(): void {\n // Stop every reconciler created this session — not just the current\n // scope's. A scope change (e.g. anonymous -> authenticated) leaves the old\n // scope's reconciler subscribed and its coordinator pump live; tear them\n // all down. Force-stop each scope's coordinator (which runs the reconciler\n // lane) alongside stopping the service.\n for (const [domainScope, entry] of this.entriesByScope) {\n entry.contents.reconciler.stop();\n entry.disconnectReconciliationTriggers();\n entry.unsubscribePersistedDocumentDeletions();\n entry.unsubscribePersistedDocuments();\n disposeDomainSyncCoordinator(domainScope);\n }\n this.entriesByScope.clear();\n }\n\n private workflowRuntime(): ContainerContentsStoreWorkflowRuntime {\n return createDeviceFirstWorkflowRuntime(this.runtimeService);\n }\n\n private getOrCreateEntry(\n options?: ContainerContentsStoreOptions | undefined,\n ): DeviceFirstScopeEntry {\n const runtime = this.workflowRuntime();\n const domainScope = runtime.state.domainScope;\n const existing = this.entriesByScope.get(domainScope);\n if (existing) {\n // Do not call updateRuntime here: facade selectors run during React\n // render, and updateRuntime emits synchronously. Hosts drive runtime\n // updates through view.updateRuntime() from an effect instead.\n return existing;\n }\n\n const store = getOrCreateLocalProjectionStore({\n domainScope,\n runtime,\n options,\n });\n const service = createReconciliationService(\n this.createReconciliationHost(store, domainScope),\n );\n const disconnectReconciliationTriggers = connectReconciliationTriggers({\n service,\n store,\n });\n const unsubscribePersistedDocumentDeletions =\n subscribeToPersistedDocumentDeletions(domainScope, (localId) => {\n store.removePersistedDocument(localId);\n });\n const unsubscribePersistedDocuments = subscribeToPersistedDocuments(\n domainScope,\n (document, change) =>\n store.refreshPersistedDocument(document, change.placementChanged),\n );\n service.start();\n\n const view: LocalProjectionView = {\n getSnapshot: () => store.getSnapshot(),\n subscribe: (listener) => store.subscribe(listener),\n setActiveContainer: (containerId) =>\n store.setActiveContainer(containerId),\n updateRuntime: (nextRuntime) => store.updateRuntime(nextRuntime),\n };\n\n const entry: DeviceFirstScopeEntry = {\n contents: {\n containerStore: store.getContainerStore(),\n reconciler: service,\n view,\n },\n disconnectReconciliationTriggers,\n unsubscribePersistedDocumentDeletions,\n unsubscribePersistedDocuments,\n };\n this.entriesByScope.set(domainScope, entry);\n return entry;\n }\n\n private createReconciliationHost(\n store: LocalProjectionStore,\n domainScope: ReconciliationHost[\"domainScope\"],\n ): ReconciliationHost {\n const runtimeService = this.runtimeService;\n const containerContents = this.containerContents;\n const requestDocumentContentPull = createReconciledDocumentContentPuller({\n getContainer: (containerId) =>\n store\n .getSnapshot()\n .containers.find((container) => container.id === containerId) ?? null,\n pullDocumentContent: (input) =>\n containerContents.pullDocumentContent(input),\n requestRegisteredDocumentRemoteSync: (localId, documentId) =>\n requestRegisteredDocumentRemoteSync(domainScope, localId, documentId),\n });\n const canDiscoverContainerDocuments = (containerId: string) => {\n const container = store\n .getSnapshot()\n .containers.find((node) => node.id === containerId);\n return container ? isRemoteBackedContainerNode(container) : false;\n };\n const listKnownContainerIds = () => {\n // A local-first id is not listable yet and may still be racing its create\n // request. Once remote-backed, it participates normally; system contents\n // are especially important during rematerialization because this device\n // may not have authored them.\n const homeOrganizationId =\n runtimeService.workflowInput().auth.organizationId;\n return store\n .getSnapshot()\n .containers.flatMap((node) =>\n isReconcilableContainerNode(node, homeOrganizationId)\n ? [node.id]\n : [],\n );\n };\n const listAutomaticRootCatchupContainerIds = () => {\n const homeOrganizationId =\n runtimeService.workflowInput().auth.organizationId;\n return store\n .getSnapshot()\n .containers.flatMap((node) =>\n isAutomaticRootCatchupContainerNode(node, homeOrganizationId)\n ? [node.id]\n : [],\n );\n };\n return {\n clock: systemReconciliationClock,\n domainScope,\n registerLane: (key, config) =>\n getOrCreateDomainSyncCoordinator(domainScope).registerLane(key, config),\n canDiscoverContainerDocuments,\n getRuntimeStatus: () => {\n const input = runtimeService.workflowInput();\n return {\n dbStatus: input.infra.dbStatus,\n isAuthenticated: input.auth.isAuthenticated,\n online: input.state.online,\n };\n },\n listKnownContainerIds,\n // Root discovery can surface directly granted non-root containers, so\n // retain every regular container. Exclude only this identity's own system\n // children; cold/auth backfill and explicit full Refresh cover those.\n listAutomaticRootCatchupContainerIds,\n discoverContainerDocuments: (requests, onOutcome) =>\n discoverContainerDocumentLanesForRuntime({\n onOutcome,\n requests,\n runtimeService,\n }),\n loadContainerDelta: (containerId) =>\n store.loadContainerDelta(containerId),\n applyReconciled: (delta) => store.applyReconciled(delta),\n requestDocumentContentPull,\n ...createInitialDocumentProbeHost(runtimeService, domainScope),\n refreshTree: async () => {\n await store.getContainerStore().refresh();\n },\n refreshRootTree: async () => {\n await store.getContainerStore().refreshRootLane();\n },\n isIgnorableError: isDatabaseUnavailableError,\n // Resolve the runtime per call: it is rebuilt as the active identity\n // changes, and a reference captured here would report into a dead host.\n logError: (message, error) =>\n logReconciliationFailure(this.workflowRuntime(), message, error),\n };\n }\n}\n\n// Returns the host's result: both callbacks are declared `=> void` but may be\n// async, and the lane reporter only catches a rejection it is handed.\nfunction logReconciliationFailure(\n runtime: ContainerContentsStoreWorkflowRuntime,\n message: string,\n error: unknown,\n): unknown {\n const { log, logError } = runtime.util;\n return logError ? logError(message, error) : log(message);\n}\n\nexport function createDeviceFirstWorkflowRuntime(\n runtimeService: InternalRuntime,\n): ContainerContentsStoreWorkflowRuntime {\n return createContainerContentsStoreWorkflowRuntime(\n runtimeService.workflowInput(),\n runtimeService.adoptRootContainer,\n );\n}\n"]}
|
package/client/documents.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"documents.js","sourceRoot":"","sources":["documents.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,qBAAqB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CAAC,eAAe,CAAC,WAAW,CAAC,CAAC;QAC/D,OAAO,iBAAiB,CACtB,OAAO,CAAC,KAAK,CAAC,WAAW,EACzB,OAAO,EACP,OAAO,EACP,UAAU,EACV,WAAW,EACX,mBAAmB,EACnB,EAAE,cAAc,EAAE,OAAO,CAAC,cAAc,EAAE,CAC3C,CAAC;IACJ,CAAC;IAED,SAAS,CACP,QAAmC,EACnC,UAAuC,EAAE;QAEzC,OAAO,6BAA6B,CAClC,IAAI,CAAC,YAAY,CAAC,OAAO,CAAC,aAAa,CAAC,OAAO,CAAC,WAAW,CAAC,CAAC,KAAK;aAC/D,WAAW,EACd,QAAQ,CACT,CAAC;IACJ,CAAC;IAEO,YAAY,CAAC,OAAgB;QACnC,MAAM,QAAQ,GAAG,IAAI,CAAC,sBAAsB,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC;QAC1D,IAAI,QAAQ,EAAE,CAAC;YACb,OAAO,QAAQ,CAAC;QAClB,CAAC;QAED,MAAM,MAAM,GAAG,2BAA2B;aACvC,YAAY,CAAC,OAAO,CAAC;aACrB,KAAK,CAAC,CAAC,KAAc,EAAE,EAAE;YACxB,IAAI,CAAC,sBAAsB,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC;YAC5C,MAAM,KAAK,CAAC;QACd,CAAC,CAAC,CAAC;QACL,IAAI,CAAC,sBAAsB,CAAC,GAAG,CAAC,OAAO,EAAE,MAAM,CAAC,CAAC;QACjD,OAAO,MAAM,CAAC;IAChB,CAAC;CACF","sourcesContent":["import { DEFAULT_DOCUMENT_KIND } from \"../data/documents/documentConstants\";\nimport type { StoredDocumentKind } from \"../data/documents/documentKinds\";\nimport type {\n DocumentSummaryList,\n DocumentSummarySort,\n DocumentSummarySortDirection,\n DocumentSummarySortKey,\n ListDocumentSummariesInput,\n} from \"../data/persistence/documents/types\";\nimport type { ExecSql } from \"../data/sqlite/sqlSchema\";\nimport {\n DEFAULT_DOCUMENT_ID as DEFAULT_LOCAL_DOCUMENT_ID,\n type DocumentStore,\n type DocumentsRuntime,\n openDocumentStore,\n type PersistedDocumentListener,\n subscribeToPersistedDocuments,\n} from \"../stores/documents\";\nimport { emitPersistedDocumentDeletion } from \"../stores/documents/registry\";\nimport {\n createDocumentsWorkflowRuntime,\n defaultDocumentsPersistence,\n deletePersistedDocument,\n reclaimDocumentOrphanBlobs,\n} from \"../workflows/documents\";\nimport type { InternalRuntime } from \"./workflowRuntime\";\n\nexport type {\n DocumentAttachmentStatus,\n DocumentAttachmentUpload,\n DocumentContextValue,\n DocumentStore,\n DocumentsRuntime,\n PersistedDocumentListener,\n} from \"../stores/documents\";\n\nexport type DocumentSortDirection = DocumentSummarySortDirection;\nexport type DocumentSortKey = DocumentSummarySortKey;\n\nexport type DocumentSort = DocumentSummarySort;\n\nexport interface ListDocumentsInput extends ListDocumentSummariesInput {}\n\nexport type DocumentList = DocumentSummaryList;\n\nexport { DEFAULT_LOCAL_DOCUMENT_ID as DEFAULT_DOCUMENT_ID };\n\nexport interface OpenDocumentInput {\n readonly containerId?: string | null | undefined;\n readonly documentId?: string | null | undefined;\n readonly initialDocumentKind?: StoredDocumentKind | undefined;\n readonly initialText?: string | undefined;\n readonly localId?: string | undefined;\n}\n\nexport interface OpenDocumentOptions {\n readonly remoteSyncMode?: \"on-demand\" | \"startup\" | undefined;\n readonly workflowRuntime?: DocumentsRuntime | undefined;\n}\n\nexport interface DocumentSubscriptionOptions {\n readonly containerId?: string | null | undefined;\n}\n\nexport interface Documents {\n delete(localId: string): Promise<boolean>;\n findLocalIdByDocumentId(documentId: string): Promise<string | null>;\n list(input?: ListDocumentsInput | undefined): Promise<DocumentList | null>;\n open(\n input?: OpenDocumentInput | undefined,\n options?: OpenDocumentOptions | undefined,\n ): DocumentStore;\n subscribe(\n listener: PersistedDocumentListener,\n options?: DocumentSubscriptionOptions | undefined,\n ): () => void;\n workflowRuntime(containerId?: string | null | undefined): DocumentsRuntime;\n}\n\ninterface DocumentsDependencies {\n getDefaultContainerId: () => string | null;\n runtime: InternalRuntime;\n}\n\nexport function createDocuments(\n dependencies: DocumentsDependencies,\n): Documents {\n return new DocumentsService(dependencies);\n}\n\nclass DocumentsService implements Documents {\n private readonly schemaEnsuresByExecSql = new WeakMap<\n ExecSql,\n Promise<void>\n >();\n\n constructor(private readonly dependencies: DocumentsDependencies) {}\n\n async delete(localId: string): Promise<boolean> {\n const runtime = this.workflowRuntime();\n if (runtime.infra.dbStatus !== \"ready\") {\n return false;\n }\n\n const deleted = await deletePersistedDocument({\n documentProjectors: runtime.infra.documentProjectors,\n execSql: runtime.infra.execSql,\n localId,\n persistence: defaultDocumentsPersistence,\n });\n if (!deleted) return false;\n void reclaimDocumentOrphanBlobs(runtime);\n emitPersistedDocumentDeletion(runtime.state.domainScope, localId);\n return true;\n }\n\n async findLocalIdByDocumentId(documentId: string): Promise<string | null> {\n const runtime = this.dependencies.runtime.workflowInput();\n if (runtime.infra.dbStatus !== \"ready\") {\n return null;\n }\n\n await this.ensureSchema(runtime.infra.execSql);\n return defaultDocumentsPersistence.findLocalIdByDocumentId(\n runtime.infra.execSql,\n documentId,\n );\n }\n\n async list(input: ListDocumentsInput = {}): Promise<DocumentList | null> {\n const runtime = this.dependencies.runtime.workflowInput();\n if (runtime.infra.dbStatus !== \"ready\") {\n return null;\n }\n\n await this.ensureSchema(runtime.infra.execSql);\n return defaultDocumentsPersistence.listDocumentSummaries(\n runtime.infra.execSql,\n input,\n );\n }\n\n workflowRuntime(\n containerId = this.dependencies.getDefaultContainerId(),\n ): DocumentsRuntime {\n const input = this.dependencies.runtime.workflowInput(containerId);\n return createDocumentsWorkflowRuntime(input);\n }\n\n open(\n input: OpenDocumentInput = {},\n options: OpenDocumentOptions = {},\n ): DocumentStore {\n const {\n containerId,\n documentId = null,\n initialDocumentKind = DEFAULT_DOCUMENT_KIND,\n initialText = \"\",\n localId = DEFAULT_LOCAL_DOCUMENT_ID,\n } = input;\n const runtime =\n options.workflowRuntime ?? this.workflowRuntime(containerId);\n return openDocumentStore(\n runtime.state.domainScope,\n localId,\n runtime,\n documentId,\n initialText,\n initialDocumentKind,\n { remoteSyncMode: options.remoteSyncMode },\n );\n }\n\n subscribe(\n listener: PersistedDocumentListener,\n options: DocumentSubscriptionOptions = {},\n ): () => void {\n return subscribeToPersistedDocuments(\n this.dependencies.runtime.workflowInput(options.containerId).state\n .domainScope,\n listener,\n );\n }\n\n private ensureSchema(execSql: ExecSql): Promise<void> {\n const existing = this.schemaEnsuresByExecSql.get(execSql);\n if (existing) {\n return existing;\n }\n\n const ensure = defaultDocumentsPersistence\n .ensureSchema(execSql)\n .catch((error: unknown) => {\n this.schemaEnsuresByExecSql.delete(execSql);\n throw error;\n });\n this.schemaEnsuresByExecSql.set(execSql, ensure);\n return ensure;\n }\n}\n"]}
|
package/client/identity.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"identity.js","sourceRoot":"","sources":["identity.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,wBAAwB,EAExB,sCAAsC,EAEtC,aAAa,GACd,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,YAAY,EAAE,MAAM,6BAA6B,CAAC;AAC3D,OAAO,EACL,wBAAwB,EAExB,uBAAuB,GACxB,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EAAE,iBAAiB,EAAE,MAAM,eAAe,CAAC;AA2DlD,MAAM,UAAU,cAAc,CAC5B,UAA2B,EAAE,EAC7B,iBAA8D,EAC9D,GAA8B,EAC9B,eAAqC,EAAE;IAEvC,OAAO,IAAI,eAAe,CAAC,OAAO,EAAE,iBAAiB,EAAE,GAAG,EAAE,YAAY,CAAC,CAAC;AAC5E,CAAC;AAED,MAAM,eAAe;IAUA;IAGA;IACA;IAbX,yBAAyB,CAA8B;IAC9C,SAAS,GAAG,iBAAiB,EAAE,CAAC;IACzC,eAAe,CAAgB;IAC/B,uBAAuB,CAAgB;IACvC,mBAAmB,CAAwB;IAC3C,aAAa,CAAmB;IAExC,YACE,UAA2B,E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YACxD,MAAM,KAAK,CAAC;QACd,CAAC;IACH,CAAC;IAEO,eAAe;QACrB,MAAM,YAAY,GAAG,IAAI,CAAC,cAAc,EAAE,CAAC;QAC3C,MAAM,gBAAgB,GAAG,IAAI,CAAC,aAAa,CAAC;QAC5C,IACE,gBAAgB,CAAC,oBAAoB;YACnC,YAAY,CAAC,oBAAoB;YACnC,gBAAgB,CAAC,UAAU,KAAK,YAAY,CAAC,UAAU;YACvD,gBAAgB,CAAC,kBAAkB,KAAK,YAAY,CAAC,kBAAkB;YACvE,gBAAgB,CAAC,cAAc,KAAK,YAAY,CAAC,cAAc,EAC/D,CAAC;YACD,OAAO;QACT,CAAC;QAED,IAAI,CAAC,aAAa,GAAG,YAAY,CAAC;QAClC,IAAI,CAAC,iBAAiB,CAAC,YAAY,CAAC,kBAAkB,CAAC,CAAC;QACxD,IAAI,CAAC,SAAS,CAAC,MAAM,EAAE,CAAC;IAC1B,CAAC;CACF","sourcesContent":["import {\n createIdentitySeedPhrase,\n type EncapsulationKeyPair,\n generateIdentityKeyPairsFromSeedPhrase,\n type SigningKeyPair,\n toFingerprint,\n} from \"@tearleads/crypto\";\nimport { errorMessage } from \"../data/shared/errorMessage\";\nimport {\n createIdentityKeyPackage,\n type IdentityKeyPackage,\n parseIdentityKeyPackage,\n} from \"./identityKeyPackage\";\nimport { createListenerSet } from \"./listenerSet\";\n\nexport interface IdentityOptions {\n encapsulationKeyPair?: EncapsulationKeyPair | null | undefined;\n seedPhrase?: string | null | undefined;\n signingFingerprint?: string | null | undefined;\n signingKeyPair?: SigningKeyPair | null | undefined;\n}\n\nexport interface IdentitySnapshot {\n encapsulationKeyPair: EncapsulationKeyPair | null;\n seedPhrase: string | null;\n signingFingerprint: string | null;\n signingKeyPair: SigningKeyPair | null;\n}\n\nexport interface IdentityGenerationResult extends IdentitySnapshot {\n rootContainerCreated: boolean;\n rootContainerId: string;\n userId: string | null;\n}\n\nexport type IdentityListener = () => void;\n\nexport interface Identity {\n readonly encapsulationKeyPair: EncapsulationKeyPair | null;\n readonly seedPhrase: string | null;\n readonly signingFingerprint: string | null;\n readonly signingKeyPair: SigningKeyPair | null;\n readonly snapshot: IdentitySnapshot;\n destroy(): void;\n exportKeyPackage(): Promise<IdentityKeyPackage>;\n generate(): Promise<IdentityGenerationResult>;\n importKeyPackage(keyPackage: unknown): Promise<IdentitySnapshot>;\n importSeedPhrase(seedPhrase: string): Promise<IdentitySnapshot>;\n requireSigningKeyPair(operation?: string): SigningKeyPair;\n refreshSigningFingerprint(): Promise<string | null>;\n setKeyPairs(options: {\n encapsulationKeyPair: EncapsulationKeyPair | null;\n seedPhrase?: string | null | undefined;\n signingFingerprint?: string | null | undefined;\n signingKeyPair: SigningKeyPair | null;\n }): Promise<IdentitySnapshot>;\n subscribe(listener: IdentityListener): () => void;\n}\n\ninterface IdentityGenerationContext {\n rootContainerCreated: boolean;\n rootContainerId: string;\n userId: string | null;\n}\n\ninterface IdentityRuntimeHooks {\n bootstrapLocalRootContainer?:\n | (() => Promise<{ containerId: string; created: boolean }>)\n | undefined;\n getUserId?: (() => string | null) | undefined;\n}\n\nexport function createIdentity(\n options: IdentityOptions = {},\n onIdentityChanged: (signingFingerprint: string | null) => void,\n log: (message: string) => void,\n runtimeHooks: IdentityRuntimeHooks = {},\n): Identity {\n return new IdentityService(options, onIdentityChanged, log, runtimeHooks);\n}\n\nclass IdentityService implements Identity {\n private encapsulationKeyPairValue: EncapsulationKeyPair | null;\n private readonly listeners = createListenerSet();\n private seedPhraseValue: string | null;\n private signingFingerprintValue: string | null;\n private signingKeyPairValue: SigningKeyPair | null;\n private snapshotValue: IdentitySnapshot;\n\n constructor(\n options: IdentityOptions = {},\n private readonly onIdentityChanged: (\n signingFingerprint: string | null,\n ) => void,\n private readonly log: (message: string) => void,\n private readonly runtimeHooks: IdentityRuntimeHooks,\n ) {\n this.encapsulationKeyPairValue = options.encapsulationKeyPair ?? null;\n this.seedPhraseValue = options.seedPhrase ?? null;\n this.signingFingerprintValue = options.signingFingerprint ?? null;\n this.signingKeyPairValue = options.signingKeyPair ?? null;\n this.snapshotValue = this.createSnapshot();\n this.onIdentityChanged(this.signingFingerprintValue);\n }\n\n get encapsulationKeyPair(): EncapsulationKeyPair | null {\n return this.encapsulationKeyPairValue;\n }\n\n get seedPhrase(): string | null {\n return this.seedPhraseValue;\n }\n\n get signingFingerprint(): string | null {\n return this.signingFingerprintValue;\n }\n\n get signingKeyPair(): SigningKeyPair | null {\n return this.signingKeyPairValue;\n }\n\n get snapshot(): IdentitySnapshot {\n return this.snapshotValue;\n }\n\n destroy(): void {\n this.encapsulationKeyPairValue = null;\n this.seedPhraseValue = null;\n this.signingFingerprintValue = null;\n this.signingKeyPairValue = null;\n this.publishSnapshot();\n this.log(\"Key pair destroyed\");\n }\n\n exportKeyPackage(): Promise<IdentityKeyPackage> {\n return createIdentityKeyPackage(this.snapshot);\n }\n\n async generate(): Promise<IdentityGenerationResult> {\n const seedPhrase = createIdentitySeedPhrase();\n const { encapsulationKeyPair, signingKeyPair } =\n generateIdentityKeyPairsFromSeedPhrase(seedPhrase);\n const signingFingerprint = await toFingerprint(\n signingKeyPair.signingPublicKey,\n );\n const generationContext = await this.createGenerationContext();\n\n this.signingKeyPairValue = signingKeyPair;\n this.encapsulationKeyPairValue = encapsulationKeyPair;\n this.seedPhraseValue = seedPhrase;\n this.signingFingerprintValue = signingFingerprint;\n this.publishSnapshot();\n this.log(\"Key pair generated\");\n return {\n ...this.snapshot,\n ...generationContext,\n };\n }\n\n async importKeyPackage(keyPackage: unknown): Promise<IdentitySnapshot> {\n const parsed = await parseIdentityKeyPackage(keyPackage);\n this.encapsulationKeyPairValue = parsed.encapsulationKeyPair;\n this.seedPhraseValue = parsed.package.seedPhrase ?? null;\n this.signingKeyPairValue = parsed.signingKeyPair;\n this.signingFingerprintValue = parsed.package.signingFingerprint;\n this.publishSnapshot();\n this.log(\"Key package imported\");\n return this.snapshot;\n }\n\n async importSeedPhrase(seedPhrase: string): Promise<IdentitySnapshot> {\n const derived = generateIdentityKeyPairsFromSeedPhrase(seedPhrase);\n this.encapsulationKeyPairValue = derived.encapsulationKeyPair;\n this.seedPhraseValue = derived.seedPhrase;\n this.signingKeyPairValue = derived.signingKeyPair;\n this.signingFingerprintValue = await toFingerprint(\n derived.signingKeyPair.signingPublicKey,\n );\n this.publishSnapshot();\n this.log(\"Seed phrase imported\");\n return this.snapshot;\n }\n\n requireSigningKeyPair(operation = \"This operation\"): SigningKeyPair {\n if (!this.signingKeyPairValue) {\n throw new Error(`${operation} requires a signing key pair.`);\n }\n\n return this.signingKeyPairValue;\n }\n\n async refreshSigningFingerprint(): Promise<string | null> {\n if (!this.signingKeyPairValue) {\n this.signingFingerprintValue = null;\n this.publishSnapshot();\n return null;\n }\n\n this.signingFingerprintValue = await toFingerprint(\n this.signingKeyPairValue.signingPublicKey,\n );\n this.publishSnapshot();\n return this.signingFingerprintValue;\n }\n\n async setKeyPairs(options: {\n encapsulationKeyPair: EncapsulationKeyPair | null;\n seedPhrase?: string | null | undefined;\n signingFingerprint?: string | null | undefined;\n signingKeyPair: SigningKeyPair | null;\n }): Promise<IdentitySnapshot> {\n this.encapsulationKeyPairValue = options.encapsulationKeyPair;\n this.seedPhraseValue = options.seedPhrase ?? null;\n this.signingKeyPairValue = options.signingKeyPair;\n this.signingFingerprintValue = options.signingFingerprint ?? null;\n\n if (!this.signingFingerprintValue) {\n await this.refreshSigningFingerprint();\n } else {\n this.publishSnapshot();\n }\n\n return this.snapshot;\n }\n\n subscribe = (listener: IdentityListener): (() => void) =>\n this.listeners.subscribe(listener);\n\n private createSnapshot(): IdentitySnapshot {\n return {\n encapsulationKeyPair: this.encapsulationKeyPairValue,\n seedPhrase: this.seedPhraseValue,\n signingFingerprint: this.signingFingerprintValue,\n signingKeyPair: this.signingKeyPairValue,\n };\n }\n\n private async createGenerationContext(): Promise<IdentityGenerationContext> {\n try {\n const bootstrapLocalRootContainer =\n this.runtimeHooks.bootstrapLocalRootContainer;\n if (!bootstrapLocalRootContainer) {\n throw new Error(\n \"identity.generate requires local root container bootstrap.\",\n );\n }\n\n const rootContainer = await bootstrapLocalRootContainer();\n\n return {\n rootContainerCreated: rootContainer.created,\n rootContainerId: rootContainer.containerId,\n userId: this.runtimeHooks.getUserId?.() ?? null,\n };\n } catch (error: unknown) {\n const message = errorMessage(error);\n this.log(`Root container bootstrap failed: ${message}`);\n throw error;\n }\n }\n\n private publishSnapshot(): void {\n const nextSnapshot = this.createSnapshot();\n const previousSnapshot = this.snapshotValue;\n if (\n previousSnapshot.encapsulationKeyPair ===\n nextSnapshot.encapsulationKeyPair &&\n previousSnapshot.seedPhrase === nextSnapshot.seedPhrase &&\n previousSnapshot.signingFingerprint === nextSnapshot.signingFingerprint &&\n previousSnapshot.signingKeyPair === nextSnapshot.signingKeyPair\n ) {\n return;\n }\n\n this.snapshotValue = nextSnapshot;\n this.onIdentityChanged(nextSnapshot.signingFingerprint);\n this.listeners.notify();\n }\n}\n"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"identityKeyPackage.js","sourceRoot":"","sources":["identityKeyPackage.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,kBAAkB,EAElB,oBAAoB,EACpB,sCAAsC,EACtC,yBAAyB,EACzB,yBAAyB,EACzB,2BAA2B,EAC3B,2BAA2B,EAE3B,IAAI,EACJ,aAAa,EACb,MAAM,GACP,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,aAAa,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AACnE,OAAO,EAAE,aAAa,EAAE,MAAM,qCAAqC,CAAC;AAEpE,MAAM,CAAC,MAAM,2BAA2B,GAAG,gCAAgC,CAAC;AAE5E,MAAM,yBAAyB,GAAG,IAAI,WAAW,EAAE,CAAC,MAAM,CACxD,sCAAsC,CACvC,CAAC;AAwBF,SAAS,kBAAkB,CACzB,KAAa,EACb,QAAgB,EAChB,KAAa;IAEb,MAAM,QAAQ,GAAG,OAAO,CAAC,GAAG,C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kB;YAClB,cAAc,EAAE;gBACd,iBAAiB,EAAE,aAAa,CAAC,cAAc,CAAC,iBAAiB,CAAC;gBAClE,gBAAgB,EAAE,aAAa,CAAC,cAAc,CAAC,gBAAgB,CAAC;aACjE;YACD,OAAO;SACR;QACD,cAAc;KACf,CAAC;AACJ,CAAC","sourcesContent":["import {\n decryptAsRecipient,\n type EncapsulationKeyPair,\n encryptForRecipients,\n generateIdentityKeyPairsFromSeedPhrase,\n ML_DSA87_PUBLIC_KEY_BYTES,\n ML_DSA87_SECRET_KEY_BYTES,\n ML_KEM1024_PUBLIC_KEY_BYTES,\n ML_KEM1024_SECRET_KEY_BYTES,\n type SigningKeyPair,\n sign,\n toFingerprint,\n verify,\n} from \"@tearleads/crypto\";\nimport { base64ToBytes, bytesToBase64 } from \"@tearleads/encoding\";\nimport { isPlainObject } from \"@tearleads/validators/isPlainObject\";\n\nexport const IDENTITY_KEY_PACKAGE_FORMAT = \"tearleads.identity-key-package\";\n\nconst KEY_PACKAGE_PROBE_MESSAGE = new TextEncoder().encode(\n \"tearleads.identity-key-package.probe\",\n);\n\nexport interface IdentityKeyPackage {\n readonly createdAt: string;\n readonly encapsulationKeyPair: {\n readonly publicKey: string;\n readonly secretKey: string;\n };\n readonly format: typeof IDENTITY_KEY_PACKAGE_FORMAT;\n readonly seedPhrase?: string | undefined;\n readonly signingFingerprint: string;\n readonly signingKeyPair: {\n readonly signingPrivateKey: string;\n readonly signingPublicKey: string;\n };\n readonly version: 1;\n}\n\ninterface ParsedIdentityKeyPackage {\n readonly encapsulationKeyPair: EncapsulationKeyPair;\n readonly package: IdentityKeyPackage;\n readonly signingKeyPair: SigningKeyPair;\n}\n\nfunction readStringProperty(\n value: object,\n property: string,\n label: string,\n): string {\n const rawValue = Reflect.get(value, property);\n if (typeof rawValue !== \"string\" || rawValue.length === 0) {\n throw new Error(`Invalid identity key package: ${label} is required.`);\n }\n\n return rawValue;\n}\n\nfunction readOptionalStringProperty(\n value: object,\n property: string,\n label: string,\n): string | null {\n const rawValue = Reflect.get(value, property);\n if (rawValue === undefined || rawValue === null) {\n return null;\n }\n if (typeof rawValue !== \"string\" || rawValue.length === 0) {\n throw new Error(`Invalid identity key package: ${label} must be a string.`);\n }\n\n return rawValue;\n}\n\nfunction readBase64Bytes(input: {\n expectedLength: number;\n label: string;\n value: string;\n}): Uint8Array {\n let bytes: Uint8Array;\n try {\n bytes = base64ToBytes(input.value);\n } catch (error) {\n throw new Error(\n `Invalid identity key package: ${input.label} must be base64.`,\n { cause: error },\n );\n }\n\n if (bytes.length !== input.expectedLength) {\n throw new Error(\n `Invalid identity key package: ${input.label} has ${bytes.length} bytes, expected ${input.expectedLength}.`,\n );\n }\n\n return bytes;\n}\n\nfunction bytesEqual(left: Uint8Array, right: Uint8Array): boolean {\n if (left.length !== right.length) {\n return false;\n }\n\n let result = 0;\n for (let index = 0; index < left.length; index += 1) {\n result |= (left[index] ?? 0) ^ (right[index] ?? 0);\n }\n return result === 0;\n}\n\nfunction readMatchingSeedPhrase(input: {\n encapsulationKeyPair: EncapsulationKeyPair;\n seedPhrase: string | null;\n signingKeyPair: SigningKeyPair;\n}): string | undefined {\n if (!input.seedPhrase) {\n return undefined;\n }\n\n let derived: ReturnType<typeof generateIdentityKeyPairsFromSeedPhrase>;\n try {\n derived = generateIdentityKeyPairsFromSeedPhrase(input.seedPhrase);\n } catch (error) {\n throw new Error(\"Invalid identity key package: seed phrase is invalid.\", {\n cause: error,\n });\n }\n\n if (\n !bytesEqual(\n derived.signingKeyPair.signingPrivateKey,\n input.signingKeyPair.signingPrivateKey,\n ) ||\n !bytesEqual(\n derived.signingKeyPair.signingPublicKey,\n input.signingKeyPair.signingPublicKey,\n ) ||\n !bytesEqual(\n derived.encapsulationKeyPair.secretKey,\n input.encapsulationKeyPair.secretKey,\n ) ||\n !bytesEqual(\n derived.encapsulationKeyPair.publicKey,\n input.encapsulationKeyPair.publicKey,\n )\n ) {\n throw new Error(\n \"Invalid identity key package: seed phrase does not match the key pairs.\",\n );\n }\n\n return derived.seedPhrase;\n}\n\nfunction readSigningKeyPair(value: unknown): SigningKeyPair {\n if (!isPlainObject(value)) {\n throw new Error(\n \"Invalid identity key package: signingKeyPair is required.\",\n );\n }\n\n return {\n signingPrivateKey: readBase64Bytes({\n expectedLength: ML_DSA87_SECRET_KEY_BYTES,\n label: \"signing private key\",\n value: readStringProperty(\n value,\n \"signingPrivateKey\",\n \"signing private key\",\n ),\n }),\n signingPublicKey: readBase64Bytes({\n expectedLength: ML_DSA87_PUBLIC_KEY_BYTES,\n label: \"signing public key\",\n value: readStringProperty(\n value,\n \"signingPublicKey\",\n \"signing public key\",\n ),\n }),\n };\n}\n\nfunction readEncapsulationKeyPair(value: unknown): EncapsulationKeyPair {\n if (!isPlainObject(value)) {\n throw new Error(\n \"Invalid identity key package: encapsulationKeyPair is required.\",\n );\n }\n\n return {\n publicKey: readBase64Bytes({\n expectedLength: ML_KEM1024_PUBLIC_KEY_BYTES,\n label: \"encapsulation public key\",\n value: readStringProperty(value, \"publicKey\", \"encapsulation public key\"),\n }),\n secretKey: readBase64Bytes({\n expectedLength: ML_KEM1024_SECRET_KEY_BYTES,\n label: \"encapsulation secret key\",\n value: readStringProperty(value, \"secretKey\", \"encapsulation secret key\"),\n }),\n };\n}\n\nfunction assertSigningKeyPairMatches(signingKeyPair: SigningKeyPair): void {\n let signature: Uint8Array;\n try {\n signature = sign(\n KEY_PACKAGE_PROBE_MESSAGE,\n signingKeyPair.signingPrivateKey,\n );\n } catch (error) {\n throw new Error(\n \"Invalid identity key package: signing private key could not sign.\",\n { cause: error },\n );\n }\n\n if (\n !verify(\n signature,\n KEY_PACKAGE_PROBE_MESSAGE,\n signingKeyPair.signingPublicKey,\n )\n ) {\n throw new Error(\n \"Invalid identity key package: signing private key does not match the public key.\",\n );\n }\n}\n\nasync function assertEncapsulationKeyPairMatches(\n encapsulationKeyPair: EncapsulationKeyPair,\n): Promise<void> {\n try {\n const envelope = await encryptForRecipients(KEY_PACKAGE_PROBE_MESSAGE, [\n encapsulationKeyPair.publicKey,\n ]);\n const decrypted = await decryptAsRecipient(\n envelope,\n encapsulationKeyPair.secretKey,\n );\n\n if (\n decrypted.length !== KEY_PACKAGE_PROBE_MESSAGE.length ||\n decrypted.some((byte, index) => byte !== KEY_PACKAGE_PROBE_MESSAGE[index])\n ) {\n throw new Error(\"probe plaintext mismatch\");\n }\n } catch (error) {\n throw new Error(\n \"Invalid identity key package: encapsulation secret key does not match the public key.\",\n { cause: error },\n );\n }\n}\n\nexport async function createIdentityKeyPackage(input: {\n encapsulationKeyPair: EncapsulationKeyPair | null;\n seedPhrase?: string | null | undefined;\n signingFingerprint: string | null;\n signingKeyPair: SigningKeyPair | null;\n}): Promise<IdentityKeyPackage> {\n if (!input.signingKeyPair || !input.encapsulationKeyPair) {\n throw new Error(\"Cannot export an identity key package without key pairs.\");\n }\n\n const signingFingerprint =\n input.signingFingerprint ??\n (await toFingerprint(input.signingKeyPair.signingPublicKey));\n const seedPhrase = readMatchingSeedPhrase({\n encapsulationKeyPair: input.encapsulationKeyPair,\n seedPhrase: input.seedPhrase ?? null,\n signingKeyPair: input.signingKeyPair,\n });\n\n return {\n createdAt: new Date().toISOString(),\n encapsulationKeyPair: {\n publicKey: bytesToBase64(input.encapsulationKeyPair.publicKey),\n secretKey: bytesToBase64(input.encapsulationKeyPair.secretKey),\n },\n format: IDENTITY_KEY_PACKAGE_FORMAT,\n ...(seedPhrase ? { seedPhrase } : {}),\n signingFingerprint,\n signingKeyPair: {\n signingPrivateKey: bytesToBase64(input.signingKeyPair.signingPrivateKey),\n signingPublicKey: bytesToBase64(input.signingKeyPair.signingPublicKey),\n },\n version: 1,\n };\n}\n\nexport async function parseIdentityKeyPackage(\n value: unknown,\n): Promise<ParsedIdentityKeyPackage> {\n if (!isPlainObject(value)) {\n throw new Error(\"Invalid identity key package: expected an object.\");\n }\n\n const format = readStringProperty(value, \"format\", \"format\");\n if (format !== IDENTITY_KEY_PACKAGE_FORMAT) {\n throw new Error(\"Invalid identity key package: unsupported format.\");\n }\n\n const version = Reflect.get(value, \"version\");\n if (version !== 1) {\n throw new Error(\"Invalid identity key package: unsupported version.\");\n }\n\n const signingFingerprint = readStringProperty(\n value,\n \"signingFingerprint\",\n \"signing fingerprint\",\n );\n const signingKeyPair = readSigningKeyPair(\n Reflect.get(value, \"signingKeyPair\"),\n );\n const computedSigningFingerprint = await toFingerprint(\n signingKeyPair.signingPublicKey,\n );\n if (computedSigningFingerprint !== signingFingerprint) {\n throw new Error(\n \"Invalid identity key package: signing fingerprint does not match the public key.\",\n );\n }\n assertSigningKeyPairMatches(signingKeyPair);\n\n const encapsulationKeyPair = readEncapsulationKeyPair(\n Reflect.get(value, \"encapsulationKeyPair\"),\n );\n await assertEncapsulationKeyPairMatches(encapsulationKeyPair);\n const seedPhrase = readMatchingSeedPhrase({\n encapsulationKeyPair,\n seedPhrase: readOptionalStringProperty(value, \"seedPhrase\", \"seed phrase\"),\n signingKeyPair,\n });\n\n return {\n encapsulationKeyPair,\n package: {\n createdAt: readStringProperty(value, \"createdAt\", \"created at\"),\n encapsulationKeyPair: {\n publicKey: bytesToBase64(encapsulationKeyPair.publicKey),\n secretKey: bytesToBase64(encapsulationKeyPair.secretKey),\n },\n format,\n ...(seedPhrase ? { seedPhrase } : {}),\n signingFingerprint,\n signingKeyPair: {\n signingPrivateKey: bytesToBase64(signingKeyPair.signingPrivateKey),\n signingPublicKey: bytesToBase64(signingKeyPair.signingPublicKey),\n },\n version,\n },\n signingKeyPair,\n };\n}\n"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"principalHistoryProtection.js","sourceRoot":"","sources":["principalHistoryProtection.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAC5D,OAAO,EAAE,mCAAmC,EAAE,MAAM,4CAA4C,CAAC;AAkBjG,SAAS,YAAY,CACnB,CAAgC,EAChC,CAAyB;IAEzB,OAAO,CACL,CAAC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C,CAAC;YACH,OAAO,KAAK,EAAE,SAAS,EAAE,EAAE;gBACzB,mCAAmC,CAAC,YAAY,CAAC,CAAC;gBAClD,IAAI,GAA2B,CAAC;gBAChC,IAAI,CAAC;oBACH,IAAI,KAAK,CAAC,WAAW,EAAE,CAAC;wBACtB,GAAG,GAAG,MAAM,KAAK,CAAC,WAAW,CAAC;4BAC5B,mBAAmB,EAAE,KAAK,CAAC,mBAAmB;4BAC9C,kBAAkB,EAAE,KAAK,CAAC,kBAAkB;yBAC7C,CAAC,CAAC;oBACL,CAAC;yBAAM,CAAC;wBACN,SAAS,KAAK;4BACZ,KAAK;4BACL,GAAG,EAAE,MAAM,CAAC,eAAe,CAAC,IAAI,UAAU,CAAC,EAAE,CAAC,CAAC;yBAChD,CAAC;wBACF,GAAG,GAAG,IAAI,UAAU,CAAC,SAAS,CAAC,GAAG,CAAC,CAAC;oBACtC,CAAC;oBACD,IAAI,CAAC,CAAC,GAAG,YAAY,UAAU,CAAC,IAAI,GAAG,CAAC,UAAU,KAAK,EAAE;wBACvD,MAAM,IAAI,uBAAuB,CAC/B,eAAe,EACf,6DAA6D,CAC9D,CAAC;oBACJ,mCAAmC,CAAC,YAAY,CAAC,CAAC;oBAClD,MAAM,MAAM,GAAG,MAAM,SAAS,CAAC;wBAC7B,UAAU,EAAE,EAAE,QAAQ,EAAE,GAAG,EAAE,OAAO,EAAE;wBACtC,YAAY;qBACb,CAAC,CAAC;oBACH,mCAAmC,CAAC,YAAY,CAAC,CAAC;oBAClD,OAAO,MAAM,CAAC;gBAChB,CAAC;wBAAS,CAAC;oBACT,IAAI,GAAG,YAAY,UAAU;wBAAE,GAAG,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;gBAC7C,CAAC;YACH,CAAC,CAAC;QACJ,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["import { KeyingVerificationError } from \"@tearleads/crypto\";\nimport { assertProjectionVerificationCurrent } from \"../data/keyingProjectionVerification/types\";\nimport type { PrincipalHistoryProtectionLease } from \"../data/principals/principalHistoryProtection\";\n\nexport interface PrincipalHistoryKeyScope {\n readonly identityTrustDomain: string;\n readonly signingFingerprint: string;\n}\n\n/** Return a fresh owned 32-byte key. The SDK clears it after each operation. */\nexport type PrincipalHistoryKeyProvider = (\n scope: PrincipalHistoryKeyScope,\n) => Promise<Uint8Array>;\n\ninterface RuntimeProtectionScope extends PrincipalHistoryKeyScope {\n readonly database: object;\n readonly generation: number;\n}\n\nfunction sameKeyScope(\n a: RuntimeProtectionScope | null,\n b: RuntimeProtectionScope,\n): boolean {\n return (\n a?.database === b.database &&\n a.identityTrustDomain === b.identityTrustDomain &&\n a.signingFingerprint === b.signingFingerprint\n );\n}\n\nexport function createPrincipalHistoryProtectionCustody(input: {\n readonly readScope: () => RuntimeProtectionScope | null;\n readonly keyProvider?: PrincipalHistoryKeyProvider | undefined;\n}) {\n let retirement = 0;\n let ephemeral: { scope: RuntimeProtectionScope; key: Uint8Array } | null =\n null;\n const clearEphemeral = () => {\n ephemeral?.key.fill(0);\n ephemeral = null;\n };\n return {\n retire() {\n retirement += 1;\n clearEphemeral();\n },\n bind(): PrincipalHistoryProtectionLease | undefined {\n const scope = input.readScope();\n if (!scope) {\n clearEphemeral();\n return undefined;\n }\n if (ephemeral && !sameKeyScope(ephemeral.scope, scope)) clearEphemeral();\n const boundRetirement = retirement;\n const boundGeneration = scope.generation;\n const stillCurrent = () => {\n const current = input.readScope();\n return (\n retirement === boundRetirement &&\n current?.generation === boundGeneration &&\n sameKeyScope(current, scope)\n );\n };\n const context = JSON.stringify([\n \"tearleads.sdk.principal-history.runtime.v1\",\n scope.identityTrustDomain,\n scope.signingFingerprint,\n ]);\n return async (operation) => {\n assertProjectionVerificationCurrent(stillCurrent);\n let key: Uint8Array | undefined;\n try {\n if (input.keyProvider) {\n key = await input.keyProvider({\n identityTrustDomain: scope.identityTrustDomain,\n signingFingerprint: scope.signingFingerprint,\n });\n } else {\n ephemeral ??= {\n scope,\n key: crypto.getRandomValues(new Uint8Array(32)),\n };\n key = new Uint8Array(ephemeral.key);\n }\n if (!(key instanceof Uint8Array) || key.byteLength !== 32)\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"Principal history key provider must return 32 private bytes\",\n );\n assertProjectionVerificationCurrent(stillCurrent);\n const result = await operation({\n protection: { localKey: key, context },\n stillCurrent,\n });\n assertProjectionVerificationCurrent(stillCurrent);\n return result;\n } finally {\n if (key instanceof Uint8Array) key.fill(0);\n }\n };\n },\n };\n}\n"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"principalMutationApi.js","sourceRoot":"","sources":["principalMutationApi.ts"],"names":[],"mappings":"AAGA,OAAO,EACL,iCAAiC,EACjC,2CAA2C,EAE3C,8BAA8B,GAC/B,MAAM,+DAA+D,CAAC;AACvE,OAAO,EAAE,iCAAiC,EAAE,MAAM,4DAA4D,CAAC;AAC/G,OAAO,EAAE,iCAAiC,EAAE,MAAM,6BAA6B,CAAC;AAChF,OAAO,EACL,iCAAiC,EACjC,iCAAiC,GAElC,MAAM,6BAA6B,CAAC;AAYrC,SAAS,SAAS,CAChB,OAA6C,EAC7C,KAA2C;IAE3C,IAAI,CAAC,OAAO,IAAI,CAAC,KAAK;QAAE,OAAO,OAAO,KAAK,KAAK,CAAC;IACjD,OAAO,CACL,OAAO,CAAC,QAAQ,KAAK,KAAK,CAAC,QAAQ;QACnC,OAAO,CAAC,OAAO,KAAK,KAAK,CAAC,OAAO;QACjC,OAAO,CAAC,UAAU,KAAK,KAAK,CAAC,UAAU;QACvC,OAAO,CAAC,mBAAmB,KAAK,KAAK,CAAC,mBAAmB;QACzD,OAAO,CAAC,kBAAkB,KAAK,KAAK,CAAC,kBAAkB;QACvD,OAAO,CAAC,cAAc,KAAK,KAAK,CAAC,cAAc;QAC/C,OAAO,CAAC,MAAM,KAAK,KAAK,CAAC,MAAM,CAChC,CAAC;AACJ,CAAC;AAYD,SAAS,eAAe,CACtB,KAAuC,EACvC,KAA2C,EAC3C,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AAK,GAAY,OAAO,CAAC,GAAG,CAAC,MAAM,EAAE,QAAQ,EAAE,MAAM,CAAC,CAAC;YAC7D,IAAI,OAAO,KAAK,KAAK,UAAU;gBAAE,OAAO,KAAK,CAAC;YAC9C,MAAM,QAAQ,GAAG,YAAY,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC;YAC5C,IAAI,QAAQ,EAAE,MAAM,KAAK,KAAK;gBAAE,OAAO,QAAQ,CAAC,KAAK,CAAC;YACtD,MAAM,KAAK,GAAG,KAAK,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;YACjC,YAAY,CAAC,GAAG,CAAC,QAAQ,EAAE,EAAE,MAAM,EAAE,KAAK,EAAE,KAAK,EAAE,CAAC,CAAC;YACrD,OAAO,KAAK,CAAC;QACf,CAAC;KACF,CAAC,CAAC;IACH,6EAA6E;IAC7E,uEAAuE;IACvE,IAAI,CAAC,kBAAkB,CAAC,KAAK,CAAC;QAC5B,MAAM,IAAI,KAAK,CAAC,qDAAqD,CAAC,CAAC;IACzE,OAAO,KAAK,CAAC;AACf,CAAC;AAED,SAAS,kBAAkB,CAAC,GAAc;IACxC,OAAO,CACL,OAAO,OAAO,CAAC,GAAG,CAAC,GAAG,EAAE,8BAA8B,CAAC,KAAK,UAAU;QACtE,OAAO,OAAO,CAAC,GAAG,CAAC,GAAG,EAAE,iCAAiC,CAAC,KAAK,UAAU;QACzE,OAAO,OAAO,CAAC,GAAG,CAAC,GAAG,EAAE,iCAAiC,CAAC,KAAK,UAAU;QACzE,OAAO,OAAO,CAAC,GAAG,CAAC,GAAG,EAAE,oCAAoC,CAAC,KAAK,UAAU,CAC7E,CAAC;AACJ,CAAC","sourcesContent":["import type { ApiClient } from \"@tearleads/api-client\";\nimport type { SigningKeyPair } from \"@tearleads/crypto\";\nimport type { ExecSql } from \"../data/sqlite/sqlSchema\";\nimport {\n abandonJournaledPrincipalMutation,\n discardUnreadableJournaledPrincipalMutation,\n type PrincipalMutationRecoveryApi,\n readJournaledPrincipalMutation,\n} from \"../workflows/organizations/principalMutationJournalManagement\";\nimport { recoverJournaledPrincipalMutation } from \"../workflows/organizations/principalMutationJournalSession\";\nimport { createPrincipalMutationDispatcher } from \"./principalMutationDeadline\";\nimport {\n createJournaledPrincipalMutations,\n dispatchAuthoredPrincipalMutation,\n type JournaledPrincipalMutationMethods,\n} from \"./principalMutationDispatch\";\n\nexport interface PrincipalMutationRuntimeScope {\n readonly database: object;\n readonly execSql: ExecSql;\n readonly generation: number;\n readonly identityTrustDomain: string;\n readonly signingFingerprint: string;\n readonly signingKeyPair: SigningKeyPair;\n readonly userId: string;\n}\n\nfunction sameScope(\n current: PrincipalMutationRuntimeScope | null,\n bound: PrincipalMutationRuntimeScope | null,\n): boolean {\n if (!current || !bound) return current === bound;\n return (\n current.database === bound.database &&\n current.execSql === bound.execSql &&\n current.generation === bound.generation &&\n current.identityTrustDomain === bound.identityTrustDomain &&\n current.signingFingerprint === bound.signingFingerprint &&\n current.signingKeyPair === bound.signingKeyPair &&\n current.userId === bound.userId\n );\n}\n\nexport type PrincipalMutationApi = ApiClient & PrincipalMutationRecoveryApi;\ntype MutationOverrides = JournaledPrincipalMutationMethods &\n PrincipalMutationRecoveryApi;\n\ninterface PrincipalMutationApiCustodyInput {\n readonly api: ApiClient;\n readonly readScope: () => PrincipalMutationRuntimeScope | null;\n readonly principalMutationTimeoutMs?: number | undefined;\n}\n\nfunction mutationContext(\n input: PrincipalMutationApiCustodyInput,\n scope: PrincipalMutationRuntimeScope | null,\n organizationId: string,\n) {\n if (!scope)\n throw new Error(\n \"Principal mutations require an authenticated signing identity, a trusted API origin and durable local storage\",\n );\n return {\n execSql: scope.execSql,\n signingKeyPair: scope.signingKeyPair,\n scope: {\n identityTrustDomain: scope.identityTrustDomain,\n organizationId,\n signingFingerprint: scope.signingFingerprint,\n userId: scope.userId,\n },\n stillCurrent: () => sameScope(input.readScope(), scope),\n };\n}\n\n/** Keep API methods bound to their real receiver and journal principal policy and group lifecycle writes. */\nexport function createPrincipalMutationApiCustody(\n input: PrincipalMutationApiCustodyInput,\n) {\n const dispatch = createPrincipalMutationDispatcher(\n input.principalMutationTimeoutMs,\n );\n let cached: {\n scope: PrincipalMutationRuntimeScope | null;\n api: PrincipalMutationApi;\n } | null = null;\n return {\n bind(): PrincipalMutationApi {\n const scope = input.readScope();\n if (cached && sameScope(scope, cached.scope)) return cached.api;\n const context = (organizationId: string) =>\n mutationContext(input, scope, organizationId);\n const read: PrincipalMutationRecoveryApi[\"readPendingPrincipalMutation\"] =\n async (organizationId) =>\n scope\n ? readJournaledPrincipalMutation(context(organizationId))\n : null;\n const abandon: PrincipalMutationRecoveryApi[\"abandonPendingPrincipalMutation\"] =\n async (organizationId, mutation, acknowledgeUnknownOutcome) =>\n abandonJournaledPrincipalMutation({\n ...context(organizationId),\n mutation,\n acknowledgeUnknownOutcome,\n });\n const methods = {\n ...createJournaledPrincipalMutations(input.api, context, dispatch),\n discardUnreadablePrincipalMutation: async (\n organizationId,\n recordId,\n acknowledgeUnknownOutcome,\n ) =>\n discardUnreadableJournaledPrincipalMutation({\n ...context(organizationId),\n recordId,\n acknowledgeUnknownOutcome,\n }),\n readPendingPrincipalMutation: read,\n abandonPendingPrincipalMutation: abandon,\n recoverPendingPrincipalMutation: async (organizationId) => {\n await recoverJournaledPrincipalMutation({\n ...context(organizationId),\n submit: (mutation) =>\n dispatch({ reportErrors: false }, (dispatchOptions) =>\n dispatchAuthoredPrincipalMutation(\n input.api,\n organizationId,\n mutation,\n dispatchOptions,\n ),\n ),\n });\n },\n } satisfies MutationOverrides;\n const api = bindMutationMethods(input.api, methods);\n cached = { scope, api };\n return api;\n },\n };\n}\n\nfunction bindMutationMethods(\n api: ApiClient,\n methods: MutationOverrides,\n): PrincipalMutationApi {\n const boundMethods = new Map<\n PropertyKey,\n { source: unknown; bound: unknown }\n >();\n const bound = new Proxy(api, {\n get(target, property) {\n if (Object.hasOwn(methods, property))\n return Reflect.get(methods, property);\n const value: unknown = Reflect.get(target, property, target);\n if (typeof value !== \"function\") return value;\n const previous = boundMethods.get(property);\n if (previous?.source === value) return previous.bound;\n const bound = value.bind(target);\n boundMethods.set(property, { source: value, bound });\n return bound;\n },\n });\n // The checked overrides supply the signatures; verify their presence through\n // the reflective boundary before exposing the extended API to callers.\n if (!hasRecoveryMethods(bound))\n throw new Error(\"Principal mutation recovery methods are unavailable\");\n return bound;\n}\n\nfunction hasRecoveryMethods(api: ApiClient): api is PrincipalMutationApi {\n return (\n typeof Reflect.get(api, \"readPendingPrincipalMutation\") === \"function\" &&\n typeof Reflect.get(api, \"recoverPendingPrincipalMutation\") === \"function\" &&\n typeof Reflect.get(api, \"abandonPendingPrincipalMutation\") === \"function\" &&\n typeof Reflect.get(api, \"discardUnreadablePrincipalMutation\") === \"function\"\n );\n}\n"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"principalMutationDispatch.js","sourceRoot":"","sources":["principalMutationDispatch.ts"],"names":[],"mappings":"AAKA,OAAO,EACL,uCAAuC,EACvC,iCAAiC,EACjC,iCAAiC,EACjC,iCAAiC,GAClC,MAAM,gCAAgC,CAAC;AAExC,OAAO,EAEL,gCAAgC,GACjC,MAAM,4DAA4D,CAAC;AAiBpE,mFAAmF;AACnF,MAAM,UAAU,iCAAiC,CAC/C,GAAc,EACd,cAAsB,EACtB,QAAmC,EACnC,UAAgC,EAAE;IAElC,QAAQ,QAAQ,CAAC,IAAI,EAAE,CAAC;QACtB,KAAK,cAAc;YACjB,OAAO,GAAG,CAAC,wBAAwB,CACjC,cAAc,EACd,cAAc,EACd,QAAQ,CAAC,OAAO,EAChB,OAAO,CACR,CAAC;QACJ,KAAK,cAAc;YACjB,OAAO,GAAG,CAAC,6BAA6B,CACtC,cAAc,EACd,QAAQ,CAAC,OAAO,EAChB,OAAO,CACR,CAAC;QACJ,KAAK,cAAc;YACjB,OAAO,GAAG,CAAC,6BAA6B,CACtC,cAAc,EACd,QAAQ,CAAC,OAAO,EAChB,QAAQ,CAA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,CAAC,CAAC;KACpE,CAAC;AACJ,CAAC;AAED,SAAS,QAAQ,CAAI,MAAwB;IAC3C,OAAO,MAAM,CAAC,EAAE,CAAC,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC;AACxC,CAAC","sourcesContent":["import type {\n ApiClient,\n RequestResult,\n RequestResultOptions,\n} from \"@tearleads/api-client\";\nimport {\n isCommitOrganizationGroupPolicyResponse,\n isCreateOrganizationGroupResponse,\n isDeleteOrganizationGroupResponse,\n isPrincipalPolicyMutationResponse,\n} from \"@tearleads/validators/response\";\nimport type { AuthoredPrincipalMutation } from \"../data/principals/principalMutationJournal\";\nimport {\n type PrincipalMutationJournalContext,\n submitJournaledPrincipalMutation,\n} from \"../workflows/organizations/principalMutationJournalSession\";\nimport type { PrincipalMutationResponse } from \"../workflows/organizations/principalOperationReceipt\";\n\nimport type { createPrincipalMutationDispatcher } from \"./principalMutationDeadline\";\n\nexport type JournaledPrincipalMutationMethods = Pick<\n ApiClient,\n | \"commitOrganizationGroupPolicy\"\n | \"commitOrganizationGroupPolicyResult\"\n | \"createOrganizationGroup\"\n | \"createOrganizationGroupResult\"\n | \"deleteOrganizationGroup\"\n | \"deleteOrganizationGroupResult\"\n | \"putPrincipalPolicy\"\n | \"putPrincipalPolicyResult\"\n>;\n\n/** Dispatch the authenticated operation, with no application planning callback. */\nexport function dispatchAuthoredPrincipalMutation(\n api: ApiClient,\n organizationId: string,\n mutation: AuthoredPrincipalMutation,\n options: RequestResultOptions = {},\n): Promise<RequestResult<PrincipalMutationResponse>> {\n switch (mutation.kind) {\n case \"organization\":\n return api.putPrincipalPolicyResult(\n \"organization\",\n organizationId,\n mutation.request,\n options,\n );\n case \"group-create\":\n return api.createOrganizationGroupResult(\n organizationId,\n mutation.request,\n options,\n );\n case \"group-delete\":\n return api.deleteOrganizationGroupResult(\n organizationId,\n mutation.groupId,\n mutation.request,\n options,\n );\n case \"compound\":\n return api.commitOrganizationGroupPolicyResult(\n organizationId,\n mutation.groupId,\n mutation.request,\n options,\n );\n default:\n return unsupportedMutation(mutation);\n }\n}\n\nfunction unsupportedMutation(_mutation: never): never {\n throw new Error(\"Unsupported principal mutation operation\");\n}\n\nexport function createJournaledPrincipalMutations(\n api: ApiClient,\n context: (\n organizationId: string,\n ) => Omit<PrincipalMutationJournalContext, \"submit\">,\n dispatch: ReturnType<typeof createPrincipalMutationDispatcher>,\n): JournaledPrincipalMutationMethods {\n async function submit<T extends PrincipalMutationResponse>(\n organizationId: string,\n mutation: AuthoredPrincipalMutation,\n validator: (value: unknown) => value is T,\n options: RequestResultOptions = {},\n ): Promise<RequestResult<T>> {\n const result = await submitJournaledPrincipalMutation({\n ...context(organizationId),\n mutation,\n submit: (saved) =>\n dispatch(options, (dispatchOptions) =>\n dispatchAuthoredPrincipalMutation(\n api,\n organizationId,\n saved,\n dispatchOptions,\n ),\n ),\n });\n if (!result.ok) return result;\n // The session already verified this operation before clearing its row.\n // This check narrows the union for each existing public API signature.\n if (!validator(result.data))\n throw new Error(\"Unexpected principal receipt operation\");\n return { ok: true, data: result.data };\n }\n const commit: ApiClient[\"commitOrganizationGroupPolicyResult\"] = (\n organizationId,\n groupId,\n request,\n options,\n ) =>\n submit(\n organizationId,\n { kind: \"compound\", groupId, request },\n isCommitOrganizationGroupPolicyResponse,\n options,\n );\n const create: ApiClient[\"createOrganizationGroupResult\"] = (\n organizationId,\n request,\n options,\n ) =>\n submit(\n organizationId,\n { kind: \"group-create\", groupId: request.groupId, request },\n isCreateOrganizationGroupResponse,\n options,\n );\n const remove: ApiClient[\"deleteOrganizationGroupResult\"] = (\n organizationId,\n groupId,\n request,\n options,\n ) =>\n submit(\n organizationId,\n { kind: \"group-delete\", groupId, request },\n isDeleteOrganizationGroupResponse,\n options,\n );\n const put: ApiClient[\"putPrincipalPolicyResult\"] = (\n _type,\n organizationId,\n request,\n options,\n ) =>\n submit(\n organizationId,\n { kind: \"organization\", groupId: null, request },\n isPrincipalPolicyMutationResponse,\n options,\n );\n return {\n commitOrganizationGroupPolicyResult: commit,\n commitOrganizationGroupPolicy: async (...args) =>\n nullable(await commit(...args)),\n createOrganizationGroupResult: create,\n createOrganizationGroup: async (...args) => nullable(await create(...args)),\n deleteOrganizationGroupResult: remove,\n deleteOrganizationGroup: async (...args) => nullable(await remove(...args)),\n putPrincipalPolicyResult: put,\n putPrincipalPolicy: async (...args) => nullable(await put(...args)),\n };\n}\n\nfunction nullable<T>(result: RequestResult<T>): T | null {\n return result.ok ? result.data : null;\n}\n"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"reconciledDocumentContentPull.js","sourceRoot":"","sources":["reconciledDocumentContentPull.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,qBAAqB,EAAE,MAAM,8BAA8B,CAAC;AAgBrE,SAAS,mBAAmB,CAC1B,KAAc,EACd,WAA4C,EAC5C,UAAkB;IAElB,OAAO,KAAK,IAAI,CAAC,CAAC,WAAW,IAAI,WAAW,CAAC,GAAG,CAAC,UAAU,CAAC,CAAC,CAAC;AAChE,CAAC;AAED;;;;;;;GAOG;AACH,MAAM,UAAU,qCAAqC,CACnD,IAAuC;IAEvC,4EAA4E;IAC5E,4EAA4E;IAC5E,kDAAkD;IAClD,MAAM,4BAA4B,GAAG,IAAI,GAAG,EAAkB,CAAC;IAE/D,OAAO,CAAC,WAAW,EAAE,SAAS,EAAE,KAAK,EAAE,WAAW,EAAE,EAAE;QACpD,MAAM,eAAe,GAAG,qBAAqB,CAC3C,IAAI,CAAC,YAAY,CAAC,WAAW,CAAC,IAAI,EAAE,UAAU,EAAE,IAAI,EAAE,CACvD,CAAC;QAEF,KAAK,MAAM,QAAQ,IAAI,SAAS,EAAE,CAAC;YACjC,IAAI,CAAC,QAAQ,CAAC,UAAU,EAAE,CAAC;gBACzB,SAAS;YACX,CAAC;YAED,MAAM,aAAa,GAAG,mBAAmB,CACvC,KAAK,EACL,WAAW,EACX,QAAQ,CAAC,UAAU,CACpB,CAAC;YAEF,IAAI,eAAe,EAAE,CAAC;gBACpB,uEAAuE;gBACvE,uEAAuE;gBACvE,oCAAoC;gBACpC,MAAM,WAAW,GAAG,GAAG,WAAW,IAAI,QAAQ,CAAC,UAAU,EAAE,CAAC;gBAC5D,IACE,4BAA4B,CAAC,GAAG,CAAC,WAAW,CAAC,KAAK,QAAQ,CAAC,SAAS,EACpE,CAAC;oBACD,IAAI,CAAC,mBAAmB,CAAC;wBACvB,WAAW;wBACX,UAAU,EAAE,QAAQ,CAAC,UAAU;wBAC/B,OAAO,EAAE,QAAQ,CAAC,EAAE;qBACrB,CAAC,CAAC;oBACH,4BAA4B,CAAC,GAAG,CAAC,WAAW,EAAE,QAAQ,CAAC,SAAS,CAAC,CAAC;gBACpE,CAAC;qBAAM,IAAI,aAAa,EAAE,CAAC;oBACzB,oEAAoE;oBACpE,qEAAqE;oBACrE,oEAAoE;oBACpE,qBAAqB;oBACrB,IAAI,CAAC,mCAAmC,CACtC,QAAQ,CAAC,EAAE,EACX,QAAQ,CAAC,UAAU,CACpB,CAAC;gBACJ,CAAC;gBACD,SAAS;YACX,CAAC;YAED,IAAI,aAAa,EAAE,CAAC;gBAClB,IAAI,CAAC,mCAAmC,CACtC,QAAQ,CAAC,EAAE,EACX,QAAQ,CAAC,UAAU,CACpB,CAAC;YACJ,CAAC;QACH,CAAC;IACH,CAAC,CAAC;AACJ,CAAC","sourcesContent":["import type { ContainerNode } from \"../stores/container-contents\";\nimport { isSystemContainerNode } from \"../stores/container-contents\";\nimport type { ReconciliationHost } from \"../sync/reconciliation\";\n\ninterface ReconciledDocumentContentPullHost {\n readonly getContainer: (containerId: string) => ContainerNode | null;\n readonly pullDocumentContent: (input: {\n readonly containerId: string;\n readonly documentId: string;\n readonly localId: string;\n }) => void;\n readonly requestRegisteredDocumentRemoteSync: (\n localId: string,\n documentId: string,\n ) => void;\n}\n\nfunction shouldForceDocument(\n force: boolean,\n documentIds: ReadonlySet<string> | undefined,\n documentId: string,\n): boolean {\n return force && (!documentIds || documentIds.has(documentId));\n}\n\n/**\n * Routes reconciled summaries into the appropriate content-sync policy.\n *\n * System-container contents cannot rely on a mini-app opening them on this\n * device, especially during identity recovery. Pull each remote version once.\n * Ordinary documents stay lazy unless an explicit refresh asks an already-open\n * store to revalidate.\n */\nexport function createReconciledDocumentContentPuller(\n host: ReconciledDocumentContentPullHost,\n): ReconciliationHost[\"requestDocumentContentPull\"] {\n // Retain only the last observed version for each system-container document.\n // Keeping the version in the key would grow this cache for every historical\n // updatedAt value over the reconciler's lifetime.\n const pulledSystemDocumentVersions = new Map<string, string>();\n\n return (containerId, documents, force, documentIds) => {\n const systemContainer = isSystemContainerNode(\n host.getContainer(containerId) ?? { systemSlot: null },\n );\n\n for (const document of documents) {\n if (!document.documentId) {\n continue;\n }\n\n const forceDocument = shouldForceDocument(\n force,\n documentIds,\n document.documentId,\n );\n\n if (systemContainer) {\n // Container scope is significant: the same document can be linked into\n // multiple system containers whose keys establish different decryption\n // contexts for the transient store.\n const documentKey = `${containerId}:${document.documentId}`;\n if (\n pulledSystemDocumentVersions.get(documentKey) !== document.updatedAt\n ) {\n host.pullDocumentContent({\n containerId,\n documentId: document.documentId,\n localId: document.id,\n });\n pulledSystemDocumentVersions.set(documentKey, document.updatedAt);\n } else if (forceDocument) {\n // The first eager pull registers a document store before scheduling\n // its async sync. If that sync failed, a later explicit Refresh must\n // be able to retry the same server version without defeating normal\n // background dedupe.\n host.requestRegisteredDocumentRemoteSync(\n document.id,\n document.documentId,\n );\n }\n continue;\n }\n\n if (forceDocument) {\n host.requestRegisteredDocumentRemoteSync(\n document.id,\n document.documentId,\n );\n }\n }\n };\n}\n"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"rootContainerAdoption.js","sourceRoot":"","sources":["rootContainerAdoption.ts"],"names":[],"mappings":"AAmBA,MAAM,UAAU,yBAAyB,CACvC,YAA+C,EAC/C,KAAyC;IAEzC,MAAM,OAAO,GAAG,YAAY,CAAC,OAAO,CAAC;IACrC,IACE,YAAY,CAAC,cAAc,EAAE,KAAK,KAAK,CAAC,WAAW;QACnD,CAAC,OAAO,CAAC,eAAe;QACxB,OAAO,CAAC,cAAc,KAAK,KAAK,CAAC,cAAc;QAC/C,OAAO,CAAC,MAAM,KAAK,KAAK,CAAC,MAAM,EAC/B,CAAC;QACD,OAAO,KAAK,CAAC;IACf,CAAC;IACD,IAAI,OAAO,CAAC,WAAW,KAAK,KAAK,CAAC,eAAe,EAAE,CAAC;QAClD,OAAO,iBAAiB,CAAC;IAC3B,CAAC;IACD,IAAI,OAAO,CAAC,WAAW,KAAK,KAAK,CAAC,mBAAmB,EAAE,CAAC;QACtD,OAAO,KAAK,CAAC;IACf,CAAC;IAED,OAAO,CAAC,cAAc,CAAC,KAAK,CAAC,eAAe,CAAC,CAAC;IAC9C,OAAO,IAAI,CAAC;AACd,CAAC","sourcesContent":["import type { DomainScope } from \"../data/shared/domainScope\";\nimport type {\n ContainerContentsRootAdopter,\n ContainerContentsRootAdoptionInput,\n} from \"../workflows/container-contents/runtime\";\nimport type { Session } from \"./session/sessionTypes\";\n\ninterface RootContainerAdoptionDependencies {\n readonly getDomainScope: () => DomainScope;\n readonly session: Pick<\n Session,\n | \"containerId\"\n | \"isAuthenticated\"\n | \"organizationId\"\n | \"setContainerId\"\n | \"userId\"\n >;\n}\n\nexport function adoptSessionRootContainer(\n dependencies: RootContainerAdoptionDependencies,\n input: ContainerContentsRootAdoptionInput,\n): ReturnType<ContainerContentsRootAdopter> {\n const session = dependencies.session;\n if (\n dependencies.getDomainScope() !== input.domainScope ||\n !session.isAuthenticated ||\n session.organizationId !== input.organizationId ||\n session.userId !== input.userId\n ) {\n return false;\n }\n if (session.containerId === input.nextContainerId) {\n return \"already-adopted\";\n }\n if (session.containerId !== input.expectedContainerId) {\n return false;\n }\n\n session.setContainerId(input.nextContainerId);\n return true;\n}\n"]}
|