@tearleads/client-sdk 0.1.204 → 0.1.205
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/data/persistence/organizations/{organizationProvisioningAttemptPersistence.js → organizationProvisioningAttemptRepository.js} +26 -15
- package/data/persistence/organizations/organizationProvisioningAttemptRepository.js.map +1 -0
- package/package.json +1 -1
- package/workflows/organizations/provisioning/organizationProvisioningAttempt.js +5 -5
- package/workflows/organizations/provisioning/organizationProvisioningAttempt.js.map +1 -1
- package/data/persistence/organizations/organizationProvisioningAttemptPersistence.js.map +0 -1
|
@@ -2,10 +2,21 @@ import { and, eq } from "drizzle-orm";
|
|
|
2
2
|
import { organizationProvisioningAttempts, organizationProvisioningAttemptTables, } from "../../sqlite/schema/organizationProvisioningAttemptSchema.js";
|
|
3
3
|
import { getClientSQLitePersistenceRuntime, } from "../../sqlite/sqlitePersistenceRuntime.js";
|
|
4
4
|
import { ensureSqlTables, runSerializedSqlMutation, } from "../../sqlite/sqlSchema.js";
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
5
|
+
/**
|
|
6
|
+
* Organization provisioning attempts, bound to one executor and clock: the
|
|
7
|
+
* signed artifacts a replacement or creation reuses after a crash, keyed by the
|
|
8
|
+
* organization it replaces or the user's creation intent.
|
|
9
|
+
*/
|
|
10
|
+
export class OrganizationProvisioningAttemptRepository {
|
|
11
|
+
execSql;
|
|
12
|
+
now;
|
|
13
|
+
constructor(execSql, now = () => new Date()) {
|
|
14
|
+
this.execSql = execSql;
|
|
15
|
+
this.now = now;
|
|
16
|
+
}
|
|
17
|
+
async load(replacedOrganizationId) {
|
|
18
|
+
await ensureSqlTables(this.execSql, organizationProvisioningAttemptTables);
|
|
19
|
+
const [stored] = await getClientSQLitePersistenceRuntime(this.execSql)
|
|
9
20
|
.db.select({
|
|
10
21
|
replacedOrganizationId: organizationProvisioningAttempts.replacedOrganizationId,
|
|
11
22
|
userId: organizationProvisioningAttempts.userId,
|
|
@@ -16,16 +27,16 @@ export const sqlOrganizationProvisioningAttemptPersistence = {
|
|
|
16
27
|
.from(organizationProvisioningAttempts)
|
|
17
28
|
.where(eq(organizationProvisioningAttempts.replacedOrganizationId, replacedOrganizationId));
|
|
18
29
|
return stored ?? null;
|
|
19
|
-
}
|
|
20
|
-
async loadOrSave(
|
|
21
|
-
return runSerializedSqlMutation(execSql, async (lockedExecSql) => {
|
|
30
|
+
}
|
|
31
|
+
async loadOrSave(candidate, canSave) {
|
|
32
|
+
return runSerializedSqlMutation(this.execSql, async (lockedExecSql) => {
|
|
22
33
|
await ensureSqlTables(lockedExecSql, organizationProvisioningAttemptTables);
|
|
23
34
|
if (canSave && !canSave())
|
|
24
35
|
return null;
|
|
25
36
|
const { db } = getClientSQLitePersistenceRuntime(lockedExecSql);
|
|
26
37
|
await db
|
|
27
38
|
.insert(organizationProvisioningAttempts)
|
|
28
|
-
.values({ ...candidate, createdAt:
|
|
39
|
+
.values({ ...candidate, createdAt: this.now().toISOString() })
|
|
29
40
|
.onConflictDoNothing()
|
|
30
41
|
.run();
|
|
31
42
|
const [stored] = await db
|
|
@@ -45,12 +56,12 @@ export const sqlOrganizationProvisioningAttemptPersistence = {
|
|
|
45
56
|
}
|
|
46
57
|
return stored;
|
|
47
58
|
});
|
|
48
|
-
}
|
|
49
|
-
async remove(
|
|
50
|
-
await ensureSqlTables(execSql, organizationProvisioningAttemptTables);
|
|
59
|
+
}
|
|
60
|
+
async remove(input, canCommit) {
|
|
61
|
+
await ensureSqlTables(this.execSql, organizationProvisioningAttemptTables);
|
|
51
62
|
if (canCommit && !canCommit())
|
|
52
63
|
return false;
|
|
53
|
-
const runtime = getClientSQLitePersistenceRuntime(execSql);
|
|
64
|
+
const runtime = getClientSQLitePersistenceRuntime(this.execSql);
|
|
54
65
|
const remove = async (tx) => {
|
|
55
66
|
await tx
|
|
56
67
|
.delete(organizationProvisioningAttempts)
|
|
@@ -66,6 +77,6 @@ export const sqlOrganizationProvisioningAttemptPersistence = {
|
|
|
66
77
|
return true;
|
|
67
78
|
}
|
|
68
79
|
return (await runtime.guardedTransaction(remove, canCommit)).committed;
|
|
69
|
-
}
|
|
70
|
-
}
|
|
71
|
-
//# sourceMappingURL=
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
//# sourceMappingURL=organizationProvisioningAttemptRepository.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"organizationProvisioningAttemptRepository.js","sourceRoot":"","sources":["organizationProvisioningAttemptRepository.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,EAAE,EAAE,MAAM,aAAa,CAAC;AACtC,OAAO,EACL,gCAAgC,EAChC,qCAAqC,GACtC,MAAM,2DAA2D,CAAC;AACnE,OAAO,EAEL,iCAAiC,GAClC,MAAM,uCAAuC,CAAC;AAC/C,OAAO,EAEL,eAAe,EACf,wBAAwB,GACzB,MAAM,wBAAwB,CAAC;AAUhC;;;;GAIG;AACH,MAAM,OAAO,yCAAyC;IACnC,OAAO,CAAU;IACjB,GAAG,CAAa;IAEjC,YAAY,OAAgB,EAAE,MAAkB,GAAG,EAAE,CAAC,IAAI,IAAI,EAAE;QAC9D,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;QACvB,IAAI,CAAC,GAAG,GAAG,GAAG,CAAC;IACjB,CAAC;IAED,KAAK,CAAC,IAAI,CACR,sBAA8B;QAE9B,MAAM,eAAe,CAAC,IAAI,CAAC,OAAO,EAAE,qCAAqC,CAAC,CAAC;QAC3E,MAAM,CAAC,MAAM,CAAC,GAAG,MAAM,iCAAiC,CAAC,IAAI,CAAC,OAAO,CAAC;aACnE,EAAE,CAAC,MAAM,CAAC;YACT,sBAAsB,EACpB,gCAAgC,CAAC,sBAAsB;YACzD,MAAM,EAAE,gCAAgC,CAAC,MAAM;YAC/C,cAAc,EAAE,gCAAgC,CAAC,cAAc;YAC/D,eAAe,EAAE,gCAAgC,CAAC,eAAe;YACjE,m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C;IACzE,CAAC;CACF","sourcesContent":["import { and, eq } from \"drizzle-orm\";\nimport {\n organizationProvisioningAttempts,\n organizationProvisioningAttemptTables,\n} from \"../../sqlite/schema/organizationProvisioningAttemptSchema\";\nimport {\n type ClientSQLiteTransactionScope,\n getClientSQLitePersistenceRuntime,\n} from \"../../sqlite/sqlitePersistenceRuntime\";\nimport {\n type ExecSql,\n ensureSqlTables,\n runSerializedSqlMutation,\n} from \"../../sqlite/sqlSchema\";\n\ninterface OrganizationProvisioningAttemptRecord {\n readonly replacedOrganizationId: string;\n readonly userId: string;\n readonly organizationId: string;\n readonly rootContainerId: string;\n readonly serializedArtifacts: string;\n}\n\n/**\n * Organization provisioning attempts, bound to one executor and clock: the\n * signed artifacts a replacement or creation reuses after a crash, keyed by the\n * organization it replaces or the user's creation intent.\n */\nexport class OrganizationProvisioningAttemptRepository {\n private readonly execSql: ExecSql;\n private readonly now: () => Date;\n\n constructor(execSql: ExecSql, now: () => Date = () => new Date()) {\n this.execSql = execSql;\n this.now = now;\n }\n\n async load(\n replacedOrganizationId: string,\n ): Promise<OrganizationProvisioningAttemptRecord | null> {\n await ensureSqlTables(this.execSql, organizationProvisioningAttemptTables);\n const [stored] = await getClientSQLitePersistenceRuntime(this.execSql)\n .db.select({\n replacedOrganizationId:\n organizationProvisioningAttempts.replacedOrganizationId,\n userId: organizationProvisioningAttempts.userId,\n organizationId: organizationProvisioningAttempts.organizationId,\n rootContainerId: organizationProvisioningAttempts.rootContainerId,\n serializedArtifacts:\n organizationProvisioningAttempts.serializedArtifacts,\n })\n .from(organizationProvisioningAttempts)\n .where(\n eq(\n organizationProvisioningAttempts.replacedOrganizationId,\n replacedOrganizationId,\n ),\n );\n return stored ?? null;\n }\n\n async loadOrSave(\n candidate: OrganizationProvisioningAttemptRecord & {\n readonly creationIntent?: string | undefined;\n },\n canSave?: (() => boolean) | undefined,\n ): Promise<OrganizationProvisioningAttemptRecord | null> {\n return runSerializedSqlMutation(this.execSql, async (lockedExecSql) => {\n await ensureSqlTables(\n lockedExecSql,\n organizationProvisioningAttemptTables,\n );\n if (canSave && !canSave()) return null;\n const { db } = getClientSQLitePersistenceRuntime(lockedExecSql);\n await db\n .insert(organizationProvisioningAttempts)\n .values({ ...candidate, createdAt: this.now().toISOString() })\n .onConflictDoNothing()\n .run();\n const [stored] = await db\n .select({\n replacedOrganizationId:\n organizationProvisioningAttempts.replacedOrganizationId,\n userId: organizationProvisioningAttempts.userId,\n organizationId: organizationProvisioningAttempts.organizationId,\n rootContainerId: organizationProvisioningAttempts.rootContainerId,\n serializedArtifacts:\n organizationProvisioningAttempts.serializedArtifacts,\n })\n .from(organizationProvisioningAttempts)\n .where(\n candidate.creationIntent\n ? and(\n eq(organizationProvisioningAttempts.userId, candidate.userId),\n eq(\n organizationProvisioningAttempts.creationIntent,\n candidate.creationIntent,\n ),\n )\n : eq(\n organizationProvisioningAttempts.replacedOrganizationId,\n candidate.replacedOrganizationId,\n ),\n );\n if (!stored) {\n throw new Error(\"Organization provisioning attempt was not persisted\");\n }\n return stored;\n });\n }\n\n async remove(\n input: {\n organizationId?: string | undefined;\n replacedOrganizationId: string;\n userId: string;\n },\n canCommit?: (() => boolean) | undefined,\n ): Promise<boolean> {\n await ensureSqlTables(this.execSql, organizationProvisioningAttemptTables);\n if (canCommit && !canCommit()) return false;\n const runtime = getClientSQLitePersistenceRuntime(this.execSql);\n const remove = async (tx: ClientSQLiteTransactionScope) => {\n await tx\n .delete(organizationProvisioningAttempts)\n .where(\n and(\n eq(\n organizationProvisioningAttempts.replacedOrganizationId,\n input.replacedOrganizationId,\n ),\n eq(organizationProvisioningAttempts.userId, input.userId),\n ...(input.organizationId\n ? [\n eq(\n organizationProvisioningAttempts.organizationId,\n input.organizationId,\n ),\n ]\n : []),\n ),\n )\n .run();\n };\n if (!canCommit) {\n await runtime.transaction(remove);\n return true;\n }\n return (await runtime.guardedTransaction(remove, canCommit)).committed;\n }\n}\n"]}
|
package/package.json
CHANGED
|
@@ -2,7 +2,7 @@ import { base64ToBytes, bytesToBase64 } from "../../../internal/encoding/index.j
|
|
|
2
2
|
import { isPlainObject } from "../../../internal/validators/isPlainObject.js";
|
|
3
3
|
import { isCreateOrganizationRequest, } from "../../../internal/validators/request/index.js";
|
|
4
4
|
import { isOrganizationReplacementAuthorization } from "../../../internal/validators/util/index.js";
|
|
5
|
-
import {
|
|
5
|
+
import { OrganizationProvisioningAttemptRepository } from "../../../data/persistence/organizations/organizationProvisioningAttemptRepository.js";
|
|
6
6
|
import { createExecSql } from "../../../data/sqlite/sqlSchema.js";
|
|
7
7
|
const BYTE_MARKER = "__tearleadsProvisioningBytes";
|
|
8
8
|
function buildCreateOrganizationRequest(input) {
|
|
@@ -35,7 +35,7 @@ function buildCreateOrganizationRequest(input) {
|
|
|
35
35
|
};
|
|
36
36
|
}
|
|
37
37
|
export async function loadOrganizationReplacementFinalizationRequest(input) {
|
|
38
|
-
const stored = await
|
|
38
|
+
const stored = await new OrganizationProvisioningAttemptRepository(input.execSql).load(input.replacedOrganizationId);
|
|
39
39
|
if (!stored) {
|
|
40
40
|
throw new Error("Organization replacement attempt is unavailable");
|
|
41
41
|
}
|
|
@@ -146,7 +146,7 @@ export async function makeOrganizationProvisioningAttemptDurable(input) {
|
|
|
146
146
|
(input.nativeSubscriptionRestore
|
|
147
147
|
? `native-subscription-restore:${input.userId}`
|
|
148
148
|
: input.artifacts.organizationId);
|
|
149
|
-
const stored = await
|
|
149
|
+
const stored = await new OrganizationProvisioningAttemptRepository(createExecSql(input.dbClient)).loadOrSave({
|
|
150
150
|
replacedOrganizationId: attemptKey,
|
|
151
151
|
userId: input.userId,
|
|
152
152
|
organizationId: input.artifacts.organizationId,
|
|
@@ -178,7 +178,7 @@ export async function makeOrganizationProvisioningAttemptDurable(input) {
|
|
|
178
178
|
export async function removeNativeSubscriptionRestoreProvisioningAttempt(input) {
|
|
179
179
|
const attemptKey = `native-subscription-restore:${input.userId}`;
|
|
180
180
|
const execSql = createExecSql(input.dbClient);
|
|
181
|
-
const stored = await
|
|
181
|
+
const stored = await new OrganizationProvisioningAttemptRepository(execSql).load(attemptKey);
|
|
182
182
|
if (!stored)
|
|
183
183
|
return true;
|
|
184
184
|
if (stored.userId !== input.userId ||
|
|
@@ -194,6 +194,6 @@ export async function removeNativeSubscriptionRestoreProvisioningAttempt(input)
|
|
|
194
194
|
});
|
|
195
195
|
}
|
|
196
196
|
export async function removeOrganizationProvisioningAttempt(input) {
|
|
197
|
-
return
|
|
197
|
+
return new OrganizationProvisioningAttemptRepository(input.execSql).remove(input, input.canCommit);
|
|
198
198
|
}
|
|
199
199
|
//# sourceMappingURL=organizationProvisioningAttempt.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"organizationProvisioningAttempt.js","sourceRoot":"","sources":["organizationProvisioningAttempt.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AACnE,OAAO,EAAE,aAAa,EAAE,MAAM,qCAAqC,CAAC;AACpE,OAAO,EAEL,2BAA2B,GAC5B,MAAM,+BAA+B,CAAC;AACvC,OAAO,EAAE,sCAAsC,EAAE,MAAM,4BAA4B,CAAC;AACpF,OAAO,EAAE,6CAA6C,EAAE,MAAM,oFAAoF,CAAC;AAKnJ,OAAO,EAAE,aAAa,EAAE,MAAM,gCAAgC,CAAC;AAG/D,MAAM,WAAW,GAAG,8BAA8B,CAAC;AAQnD,SAAS,8BAA8B,CAAC,KAOvC;IACC,MAAM,EAAE,SAAS,EAAE,GAAG,KAAK,CAAC;IAC5B,OAAO;QACL,MAAM,EAAE,KAAK,CAAC,MAAM;QACpB,GAAG,CAAC,SAAS,CAAC,wBAAwB;YACpC,CAAC,CAAC,EAAE,wBAAwB,EAAE,SAAS,CAAC,wBAAwB,EAAE;YAClE,CAAC,CAAC,EAAE,CAAC;QACP,cAAc,EAAE,SAAS,CAAC,cAAc;QACxC,eAAe,EAAE,KAAK,CAAC,eAAe;QACtC,iBAAi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AA+B,KAAK,CAAC,MAAM,EAAE,CAAC;IACjE,MAAM,OAAO,GAAG,aAAa,CAAC,KAAK,CAAC,QAAQ,CAAC,CAAC;IAC9C,MAAM,MAAM,GAAG,MAAM,6CAA6C,CAAC,IAAI,CACrE,OAAO,EACP,UAAU,CACX,CAAC;IACF,IAAI,CAAC,MAAM;QAAE,OAAO,IAAI,CAAC;IACzB,IACE,MAAM,CAAC,MAAM,KAAK,KAAK,CAAC,MAAM;QAC9B,MAAM,CAAC,cAAc,KAAK,KAAK,CAAC,cAAc,EAC9C,CAAC;QACD,MAAM,IAAI,KAAK,CACb,yEAAyE,CAC1E,CAAC;IACJ,CAAC;IACD,OAAO,qCAAqC,CAAC;QAC3C,SAAS,EAAE,KAAK,CAAC,SAAS;QAC1B,OAAO;QACP,cAAc,EAAE,KAAK,CAAC,cAAc;QACpC,sBAAsB,EAAE,UAAU;QAClC,MAAM,EAAE,KAAK,CAAC,MAAM;KACrB,CAAC,CAAC;AACL,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,qCAAqC,CAAC,KAM3D;IACC,OAAO,6CAA6C,CAAC,MAAM,CACzD,KAAK,CAAC,OAAO,EACb,KAAK,EACL,KAAK,CAAC,SAAS,CAChB,CAAC;AACJ,CAAC","sourcesContent":["import { base64ToBytes, bytesToBase64 } from \"@tearleads/encoding\";\nimport { isPlainObject } from \"@tearleads/validators/isPlainObject\";\nimport {\n type CreateOrganizationRequest,\n isCreateOrganizationRequest,\n} from \"@tearleads/validators/request\";\nimport { isOrganizationReplacementAuthorization } from \"@tearleads/validators/util\";\nimport { sqlOrganizationProvisioningAttemptPersistence } from \"../../../data/persistence/organizations/organizationProvisioningAttemptPersistence\";\nimport type {\n ExecSql,\n ExecSqlClientLike,\n} from \"../../../data/sqlite/sqlSchema\";\nimport { createExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport type { OrganizationProvisioningArtifacts } from \"../../registration/organizationProvisioning\";\n\nconst BYTE_MARKER = \"__tearleadsProvisioningBytes\";\n\ninterface DurableOrganizationProvisioningAttempt {\n readonly artifacts: OrganizationProvisioningArtifacts;\n readonly request: CreateOrganizationRequest;\n readonly rootContainerId: string;\n}\n\nfunction buildCreateOrganizationRequest(input: {\n artifacts: OrganizationProvisioningArtifacts;\n finalizeReplacement?: boolean | undefined;\n nativeSubscriptionRestore?: boolean | undefined;\n replacesOrganizationId?: string | undefined;\n rootContainerId: string;\n userId: string;\n}): CreateOrganizationRequest {\n const { artifacts } = input;\n return {\n userId: input.userId,\n ...(artifacts.replacementAuthorization\n ? { replacementAuthorization: artifacts.replacementAuthorization }\n : {}),\n organizationId: artifacts.organizationId,\n rootContainerId: input.rootContainerId,\n initialAdminGroup: artifacts.initialAdminGroup,\n initialMemberGroup: artifacts.initialMemberGroup,\n initialOrganizationPolicy: artifacts.initialOrganizationPolicy,\n initialRootContainer: artifacts.initialRootContainer,\n initialRootMetadataDocument: artifacts.rootMetadataDocumentRequest,\n initialRosterProfileContainer:\n artifacts.rosterProfileBootstrap.containerRequest,\n initialRosterProfileDocument:\n artifacts.rosterProfileBootstrap.profileDocumentRequest,\n initialOrganizationMetadataContainer:\n artifacts.organizationMetadataBootstrap.containerRequest,\n initialOrganizationProfileDocument:\n artifacts.organizationMetadataBootstrap\n .organizationProfileDocumentRequest,\n initialSystemContainers: artifacts.systemContainerBootstraps.map(\n (systemContainer) => systemContainer.containerRequest,\n ),\n ...(input.finalizeReplacement ? { finalizeReplacement: true } : {}),\n ...(input.nativeSubscriptionRestore\n ? { nativeSubscriptionRestore: true as const }\n : {}),\n ...(input.replacesOrganizationId\n ? { replacesOrganizationId: input.replacesOrganizationId }\n : {}),\n };\n}\n\nexport async function loadOrganizationReplacementFinalizationRequest(input: {\n execSql: ExecSql;\n replacedOrganizationId: string;\n userId: string;\n}): Promise<CreateOrganizationRequest> {\n const stored = await sqlOrganizationProvisioningAttemptPersistence.load(\n input.execSql,\n input.replacedOrganizationId,\n );\n if (!stored) {\n throw new Error(\"Organization replacement attempt is unavailable\");\n }\n if (stored.userId !== input.userId) {\n throw new Error(\n \"Stored organization provisioning attempt belongs to another user\",\n );\n }\n const artifacts = deserializeArtifacts(stored.serializedArtifacts);\n const request = buildCreateOrganizationRequest({\n artifacts,\n finalizeReplacement: true,\n replacesOrganizationId: input.replacedOrganizationId,\n rootContainerId: stored.rootContainerId,\n userId: stored.userId,\n });\n if (\n artifacts.organizationId !== stored.organizationId ||\n request.organizationId !== stored.organizationId ||\n request.rootContainerId !== stored.rootContainerId ||\n !isCreateOrganizationRequest(request)\n ) {\n throw new Error(\"Stored organization provisioning attempt is inconsistent\");\n }\n return request;\n}\n\nfunction serializeArtifacts(artifacts: OrganizationProvisioningArtifacts) {\n return JSON.stringify(artifacts, (_key, value: unknown) => {\n if (value instanceof Uint8Array) {\n return { [BYTE_MARKER]: bytesToBase64(value) };\n }\n return value;\n });\n}\n\nfunction hasRecord(value: Record<string, unknown>, key: string): boolean {\n return isPlainObject(Reflect.get(value, key));\n}\n\nfunction hasBytes(value: Record<string, unknown>, key: string): boolean {\n return Reflect.get(value, key) instanceof Uint8Array;\n}\n\nfunction isMaterializedDocument(value: unknown): boolean {\n return (\n isPlainObject(value) &&\n hasBytes(value, \"contentKey\") &&\n hasRecord(value, \"plan\")\n );\n}\n\nfunction isMaterializedContainer(value: unknown): boolean {\n return (\n isPlainObject(value) &&\n hasBytes(value, \"containerKey\") &&\n hasRecord(value, \"plan\")\n );\n}\n\nfunction hasContainerBootstrapCore(value: Record<string, unknown>): boolean {\n return (\n typeof Reflect.get(value, \"containerId\") === \"string\" &&\n isMaterializedDocument(Reflect.get(value, \"containerMetadataDocument\")) &&\n hasBytes(value, \"containerMetadataInitialUpdate\") &&\n isMaterializedContainer(Reflect.get(value, \"containerPlan\")) &&\n hasRecord(value, \"containerRequest\") &&\n Reflect.get(value, \"systemSlot\") !== undefined\n );\n}\n\nfunction isOrganizationProvisioningArtifacts(\n value: unknown,\n): value is OrganizationProvisioningArtifacts {\n if (!isPlainObject(value)) return false;\n const bootstrap = Reflect.get(value, \"bootstrap\");\n const roster = Reflect.get(value, \"rosterProfileBootstrap\");\n const metadata = Reflect.get(value, \"organizationMetadataBootstrap\");\n const systemContainers = Reflect.get(value, \"systemContainerBootstraps\");\n return (\n (Reflect.get(value, \"replacementAuthorization\") === null ||\n isOrganizationReplacementAuthorization(\n Reflect.get(value, \"replacementAuthorization\"),\n )) &&\n typeof Reflect.get(value, \"organizationId\") === \"string\" &&\n isPlainObject(bootstrap) &&\n hasBytes(bootstrap, \"initialUpdate\") &&\n typeof Reflect.get(bootstrap, \"metadataDocumentId\") === \"string\" &&\n hasRecord(value, \"initialAdminGroup\") &&\n hasRecord(value, \"initialMemberGroup\") &&\n hasRecord(value, \"initialOrganizationPolicy\") &&\n hasRecord(value, \"initialRootContainer\") &&\n isMaterializedContainer(Reflect.get(value, \"rootContainer\")) &&\n isMaterializedDocument(Reflect.get(value, \"rootMetadataDocument\")) &&\n hasRecord(value, \"rootMetadataDocumentRequest\") &&\n isPlainObject(roster) &&\n hasContainerBootstrapCore(roster) &&\n isMaterializedDocument(Reflect.get(roster, \"profileDocument\")) &&\n hasBytes(roster, \"profileDocumentInitialUpdate\") &&\n hasRecord(roster, \"profileDocumentRequest\") &&\n isPlainObject(metadata) &&\n hasContainerBootstrapCore(metadata) &&\n isMaterializedDocument(\n Reflect.get(metadata, \"organizationProfileDocument\"),\n ) &&\n hasRecord(metadata, \"organizationProfileDocumentRequest\") &&\n typeof Reflect.get(metadata, \"organizationProfileSnapshot\") === \"string\" &&\n Array.isArray(systemContainers) &&\n systemContainers.every(\n (container) =>\n isPlainObject(container) && hasContainerBootstrapCore(container),\n )\n );\n}\n\nfunction deserializeArtifacts(\n value: string,\n): OrganizationProvisioningArtifacts {\n const parsed: unknown = JSON.parse(value, (_key, candidate: unknown) => {\n if (\n typeof candidate === \"object\" &&\n candidate !== null &&\n Object.keys(candidate).length === 1 &&\n BYTE_MARKER in candidate\n ) {\n const encoded = Reflect.get(candidate, BYTE_MARKER);\n if (typeof encoded === \"string\") {\n return base64ToBytes(encoded);\n }\n }\n return candidate;\n });\n if (!isOrganizationProvisioningArtifacts(parsed)) {\n throw new Error(\"Stored organization provisioning attempt is invalid\");\n }\n return parsed;\n}\n\nexport async function makeOrganizationProvisioningAttemptDurable(input: {\n artifacts: OrganizationProvisioningArtifacts;\n canStartDurableMutation?: (() => boolean) | undefined;\n dbClient: ExecSqlClientLike;\n creationIntent?: string | undefined;\n nativeSubscriptionRestore?: boolean | undefined;\n replacesOrganizationId?: string | undefined;\n rootContainerId: string;\n userId: string;\n}): Promise<DurableOrganizationProvisioningAttempt | null> {\n const attemptKey =\n input.replacesOrganizationId ??\n (input.nativeSubscriptionRestore\n ? `native-subscription-restore:${input.userId}`\n : input.artifacts.organizationId);\n const stored = await sqlOrganizationProvisioningAttemptPersistence.loadOrSave(\n createExecSql(input.dbClient),\n {\n replacedOrganizationId: attemptKey,\n userId: input.userId,\n organizationId: input.artifacts.organizationId,\n rootContainerId: input.rootContainerId,\n serializedArtifacts: serializeArtifacts(input.artifacts),\n creationIntent: input.creationIntent,\n },\n input.canStartDurableMutation,\n );\n if (!stored) return null;\n if (stored.userId !== input.userId) {\n throw new Error(\n \"Stored organization provisioning attempt belongs to another user\",\n );\n }\n const artifacts = deserializeArtifacts(stored.serializedArtifacts);\n const request = buildCreateOrganizationRequest({\n artifacts,\n nativeSubscriptionRestore: input.nativeSubscriptionRestore,\n replacesOrganizationId: input.replacesOrganizationId,\n rootContainerId: stored.rootContainerId,\n userId: stored.userId,\n });\n if (\n artifacts.organizationId !== stored.organizationId ||\n request.organizationId !== stored.organizationId ||\n request.rootContainerId !== stored.rootContainerId ||\n !isCreateOrganizationRequest(request)\n ) {\n throw new Error(\"Stored organization provisioning attempt is inconsistent\");\n }\n return { artifacts, request, rootContainerId: stored.rootContainerId };\n}\n\nexport async function removeNativeSubscriptionRestoreProvisioningAttempt(input: {\n canCommit?: (() => boolean) | undefined;\n dbClient: ExecSqlClientLike;\n organizationId: string;\n userId: string;\n}): Promise<boolean> {\n const attemptKey = `native-subscription-restore:${input.userId}`;\n const execSql = createExecSql(input.dbClient);\n const stored = await sqlOrganizationProvisioningAttemptPersistence.load(\n execSql,\n attemptKey,\n );\n if (!stored) return true;\n if (\n stored.userId !== input.userId ||\n stored.organizationId !== input.organizationId\n ) {\n throw new Error(\n \"Stored native restore organization provisioning attempt is inconsistent\",\n );\n }\n return removeOrganizationProvisioningAttempt({\n canCommit: input.canCommit,\n execSql,\n organizationId: input.organizationId,\n replacedOrganizationId: attemptKey,\n userId: input.userId,\n });\n}\n\nexport async function removeOrganizationProvisioningAttempt(input: {\n canCommit?: (() => boolean) | undefined;\n execSql: ExecSql;\n organizationId?: string | undefined;\n replacedOrganizationId: string;\n userId: string;\n}): Promise<boolean> {\n return sqlOrganizationProvisioningAttemptPersistence.remove(\n input.execSql,\n input,\n input.canCommit,\n );\n}\n"]}
|
|
1
|
+
{"version":3,"file":"organizationProvisioningAttempt.js","sourceRoot":"","sources":["organizationProvisioningAttempt.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AACnE,OAAO,EAAE,aAAa,EAAE,MAAM,qCAAqC,CAAC;AACpE,OAAO,EAEL,2BAA2B,GAC5B,MAAM,+BAA+B,CAAC;AACvC,OAAO,EAAE,sCAAsC,EAAE,MAAM,4BAA4B,CAAC;AACpF,OAAO,EAAE,yCAAyC,EAAE,MAAM,mFAAmF,CAAC;AAK9I,OAAO,EAAE,aAAa,EAAE,MAAM,gCAAgC,CAAC;AAG/D,MAAM,WAAW,GAAG,8BAA8B,CAAC;AAQnD,SAAS,8BAA8B,CAAC,KAOvC;IACC,MAAM,EAAE,SAAS,EAAE,GAAG,KAAK,CAAC;IAC5B,OAAO;QACL,MAAM,EAAE,KAAK,CAAC,MAAM;QACpB,GAAG,CAAC,SAAS,CAAC,wBAAwB;YACpC,CAAC,CAAC,EAAE,wBAAwB,EAAE,SAAS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E,SAAS,EAAE,OAAO,EAAE,eAAe,EAAE,MAAM,CAAC,eAAe,EAAE,CAAC;AACzE,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,kDAAkD,CAAC,KAKxE;IACC,MAAM,UAAU,GAAG,+BAA+B,KAAK,CAAC,MAAM,EAAE,CAAC;IACjE,MAAM,OAAO,GAAG,aAAa,CAAC,KAAK,CAAC,QAAQ,CAAC,CAAC;IAC9C,MAAM,MAAM,GAAG,MAAM,IAAI,yCAAyC,CAChE,OAAO,CACR,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC;IACnB,IAAI,CAAC,MAAM;QAAE,OAAO,IAAI,CAAC;IACzB,IACE,MAAM,CAAC,MAAM,KAAK,KAAK,CAAC,MAAM;QAC9B,MAAM,CAAC,cAAc,KAAK,KAAK,CAAC,cAAc,EAC9C,CAAC;QACD,MAAM,IAAI,KAAK,CACb,yEAAyE,CAC1E,CAAC;IACJ,CAAC;IACD,OAAO,qCAAqC,CAAC;QAC3C,SAAS,EAAE,KAAK,CAAC,SAAS;QAC1B,OAAO;QACP,cAAc,EAAE,KAAK,CAAC,cAAc;QACpC,sBAAsB,EAAE,UAAU;QAClC,MAAM,EAAE,KAAK,CAAC,MAAM;KACrB,CAAC,CAAC;AACL,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,qCAAqC,CAAC,KAM3D;IACC,OAAO,IAAI,yCAAyC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,MAAM,CACxE,KAAK,EACL,KAAK,CAAC,SAAS,CAChB,CAAC;AACJ,CAAC","sourcesContent":["import { base64ToBytes, bytesToBase64 } from \"@tearleads/encoding\";\nimport { isPlainObject } from \"@tearleads/validators/isPlainObject\";\nimport {\n type CreateOrganizationRequest,\n isCreateOrganizationRequest,\n} from \"@tearleads/validators/request\";\nimport { isOrganizationReplacementAuthorization } from \"@tearleads/validators/util\";\nimport { OrganizationProvisioningAttemptRepository } from \"../../../data/persistence/organizations/organizationProvisioningAttemptRepository\";\nimport type {\n ExecSql,\n ExecSqlClientLike,\n} from \"../../../data/sqlite/sqlSchema\";\nimport { createExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport type { OrganizationProvisioningArtifacts } from \"../../registration/organizationProvisioning\";\n\nconst BYTE_MARKER = \"__tearleadsProvisioningBytes\";\n\ninterface DurableOrganizationProvisioningAttempt {\n readonly artifacts: OrganizationProvisioningArtifacts;\n readonly request: CreateOrganizationRequest;\n readonly rootContainerId: string;\n}\n\nfunction buildCreateOrganizationRequest(input: {\n artifacts: OrganizationProvisioningArtifacts;\n finalizeReplacement?: boolean | undefined;\n nativeSubscriptionRestore?: boolean | undefined;\n replacesOrganizationId?: string | undefined;\n rootContainerId: string;\n userId: string;\n}): CreateOrganizationRequest {\n const { artifacts } = input;\n return {\n userId: input.userId,\n ...(artifacts.replacementAuthorization\n ? { replacementAuthorization: artifacts.replacementAuthorization }\n : {}),\n organizationId: artifacts.organizationId,\n rootContainerId: input.rootContainerId,\n initialAdminGroup: artifacts.initialAdminGroup,\n initialMemberGroup: artifacts.initialMemberGroup,\n initialOrganizationPolicy: artifacts.initialOrganizationPolicy,\n initialRootContainer: artifacts.initialRootContainer,\n initialRootMetadataDocument: artifacts.rootMetadataDocumentRequest,\n initialRosterProfileContainer:\n artifacts.rosterProfileBootstrap.containerRequest,\n initialRosterProfileDocument:\n artifacts.rosterProfileBootstrap.profileDocumentRequest,\n initialOrganizationMetadataContainer:\n artifacts.organizationMetadataBootstrap.containerRequest,\n initialOrganizationProfileDocument:\n artifacts.organizationMetadataBootstrap\n .organizationProfileDocumentRequest,\n initialSystemContainers: artifacts.systemContainerBootstraps.map(\n (systemContainer) => systemContainer.containerRequest,\n ),\n ...(input.finalizeReplacement ? { finalizeReplacement: true } : {}),\n ...(input.nativeSubscriptionRestore\n ? { nativeSubscriptionRestore: true as const }\n : {}),\n ...(input.replacesOrganizationId\n ? { replacesOrganizationId: input.replacesOrganizationId }\n : {}),\n };\n}\n\nexport async function loadOrganizationReplacementFinalizationRequest(input: {\n execSql: ExecSql;\n replacedOrganizationId: string;\n userId: string;\n}): Promise<CreateOrganizationRequest> {\n const stored = await new OrganizationProvisioningAttemptRepository(\n input.execSql,\n ).load(input.replacedOrganizationId);\n if (!stored) {\n throw new Error(\"Organization replacement attempt is unavailable\");\n }\n if (stored.userId !== input.userId) {\n throw new Error(\n \"Stored organization provisioning attempt belongs to another user\",\n );\n }\n const artifacts = deserializeArtifacts(stored.serializedArtifacts);\n const request = buildCreateOrganizationRequest({\n artifacts,\n finalizeReplacement: true,\n replacesOrganizationId: input.replacedOrganizationId,\n rootContainerId: stored.rootContainerId,\n userId: stored.userId,\n });\n if (\n artifacts.organizationId !== stored.organizationId ||\n request.organizationId !== stored.organizationId ||\n request.rootContainerId !== stored.rootContainerId ||\n !isCreateOrganizationRequest(request)\n ) {\n throw new Error(\"Stored organization provisioning attempt is inconsistent\");\n }\n return request;\n}\n\nfunction serializeArtifacts(artifacts: OrganizationProvisioningArtifacts) {\n return JSON.stringify(artifacts, (_key, value: unknown) => {\n if (value instanceof Uint8Array) {\n return { [BYTE_MARKER]: bytesToBase64(value) };\n }\n return value;\n });\n}\n\nfunction hasRecord(value: Record<string, unknown>, key: string): boolean {\n return isPlainObject(Reflect.get(value, key));\n}\n\nfunction hasBytes(value: Record<string, unknown>, key: string): boolean {\n return Reflect.get(value, key) instanceof Uint8Array;\n}\n\nfunction isMaterializedDocument(value: unknown): boolean {\n return (\n isPlainObject(value) &&\n hasBytes(value, \"contentKey\") &&\n hasRecord(value, \"plan\")\n );\n}\n\nfunction isMaterializedContainer(value: unknown): boolean {\n return (\n isPlainObject(value) &&\n hasBytes(value, \"containerKey\") &&\n hasRecord(value, \"plan\")\n );\n}\n\nfunction hasContainerBootstrapCore(value: Record<string, unknown>): boolean {\n return (\n typeof Reflect.get(value, \"containerId\") === \"string\" &&\n isMaterializedDocument(Reflect.get(value, \"containerMetadataDocument\")) &&\n hasBytes(value, \"containerMetadataInitialUpdate\") &&\n isMaterializedContainer(Reflect.get(value, \"containerPlan\")) &&\n hasRecord(value, \"containerRequest\") &&\n Reflect.get(value, \"systemSlot\") !== undefined\n );\n}\n\nfunction isOrganizationProvisioningArtifacts(\n value: unknown,\n): value is OrganizationProvisioningArtifacts {\n if (!isPlainObject(value)) return false;\n const bootstrap = Reflect.get(value, \"bootstrap\");\n const roster = Reflect.get(value, \"rosterProfileBootstrap\");\n const metadata = Reflect.get(value, \"organizationMetadataBootstrap\");\n const systemContainers = Reflect.get(value, \"systemContainerBootstraps\");\n return (\n (Reflect.get(value, \"replacementAuthorization\") === null ||\n isOrganizationReplacementAuthorization(\n Reflect.get(value, \"replacementAuthorization\"),\n )) &&\n typeof Reflect.get(value, \"organizationId\") === \"string\" &&\n isPlainObject(bootstrap) &&\n hasBytes(bootstrap, \"initialUpdate\") &&\n typeof Reflect.get(bootstrap, \"metadataDocumentId\") === \"string\" &&\n hasRecord(value, \"initialAdminGroup\") &&\n hasRecord(value, \"initialMemberGroup\") &&\n hasRecord(value, \"initialOrganizationPolicy\") &&\n hasRecord(value, \"initialRootContainer\") &&\n isMaterializedContainer(Reflect.get(value, \"rootContainer\")) &&\n isMaterializedDocument(Reflect.get(value, \"rootMetadataDocument\")) &&\n hasRecord(value, \"rootMetadataDocumentRequest\") &&\n isPlainObject(roster) &&\n hasContainerBootstrapCore(roster) &&\n isMaterializedDocument(Reflect.get(roster, \"profileDocument\")) &&\n hasBytes(roster, \"profileDocumentInitialUpdate\") &&\n hasRecord(roster, \"profileDocumentRequest\") &&\n isPlainObject(metadata) &&\n hasContainerBootstrapCore(metadata) &&\n isMaterializedDocument(\n Reflect.get(metadata, \"organizationProfileDocument\"),\n ) &&\n hasRecord(metadata, \"organizationProfileDocumentRequest\") &&\n typeof Reflect.get(metadata, \"organizationProfileSnapshot\") === \"string\" &&\n Array.isArray(systemContainers) &&\n systemContainers.every(\n (container) =>\n isPlainObject(container) && hasContainerBootstrapCore(container),\n )\n );\n}\n\nfunction deserializeArtifacts(\n value: string,\n): OrganizationProvisioningArtifacts {\n const parsed: unknown = JSON.parse(value, (_key, candidate: unknown) => {\n if (\n typeof candidate === \"object\" &&\n candidate !== null &&\n Object.keys(candidate).length === 1 &&\n BYTE_MARKER in candidate\n ) {\n const encoded = Reflect.get(candidate, BYTE_MARKER);\n if (typeof encoded === \"string\") {\n return base64ToBytes(encoded);\n }\n }\n return candidate;\n });\n if (!isOrganizationProvisioningArtifacts(parsed)) {\n throw new Error(\"Stored organization provisioning attempt is invalid\");\n }\n return parsed;\n}\n\nexport async function makeOrganizationProvisioningAttemptDurable(input: {\n artifacts: OrganizationProvisioningArtifacts;\n canStartDurableMutation?: (() => boolean) | undefined;\n dbClient: ExecSqlClientLike;\n creationIntent?: string | undefined;\n nativeSubscriptionRestore?: boolean | undefined;\n replacesOrganizationId?: string | undefined;\n rootContainerId: string;\n userId: string;\n}): Promise<DurableOrganizationProvisioningAttempt | null> {\n const attemptKey =\n input.replacesOrganizationId ??\n (input.nativeSubscriptionRestore\n ? `native-subscription-restore:${input.userId}`\n : input.artifacts.organizationId);\n const stored = await new OrganizationProvisioningAttemptRepository(\n createExecSql(input.dbClient),\n ).loadOrSave(\n {\n replacedOrganizationId: attemptKey,\n userId: input.userId,\n organizationId: input.artifacts.organizationId,\n rootContainerId: input.rootContainerId,\n serializedArtifacts: serializeArtifacts(input.artifacts),\n creationIntent: input.creationIntent,\n },\n input.canStartDurableMutation,\n );\n if (!stored) return null;\n if (stored.userId !== input.userId) {\n throw new Error(\n \"Stored organization provisioning attempt belongs to another user\",\n );\n }\n const artifacts = deserializeArtifacts(stored.serializedArtifacts);\n const request = buildCreateOrganizationRequest({\n artifacts,\n nativeSubscriptionRestore: input.nativeSubscriptionRestore,\n replacesOrganizationId: input.replacesOrganizationId,\n rootContainerId: stored.rootContainerId,\n userId: stored.userId,\n });\n if (\n artifacts.organizationId !== stored.organizationId ||\n request.organizationId !== stored.organizationId ||\n request.rootContainerId !== stored.rootContainerId ||\n !isCreateOrganizationRequest(request)\n ) {\n throw new Error(\"Stored organization provisioning attempt is inconsistent\");\n }\n return { artifacts, request, rootContainerId: stored.rootContainerId };\n}\n\nexport async function removeNativeSubscriptionRestoreProvisioningAttempt(input: {\n canCommit?: (() => boolean) | undefined;\n dbClient: ExecSqlClientLike;\n organizationId: string;\n userId: string;\n}): Promise<boolean> {\n const attemptKey = `native-subscription-restore:${input.userId}`;\n const execSql = createExecSql(input.dbClient);\n const stored = await new OrganizationProvisioningAttemptRepository(\n execSql,\n ).load(attemptKey);\n if (!stored) return true;\n if (\n stored.userId !== input.userId ||\n stored.organizationId !== input.organizationId\n ) {\n throw new Error(\n \"Stored native restore organization provisioning attempt is inconsistent\",\n );\n }\n return removeOrganizationProvisioningAttempt({\n canCommit: input.canCommit,\n execSql,\n organizationId: input.organizationId,\n replacedOrganizationId: attemptKey,\n userId: input.userId,\n });\n}\n\nexport async function removeOrganizationProvisioningAttempt(input: {\n canCommit?: (() => boolean) | undefined;\n execSql: ExecSql;\n organizationId?: string | undefined;\n replacedOrganizationId: string;\n userId: string;\n}): Promise<boolean> {\n return new OrganizationProvisioningAttemptRepository(input.execSql).remove(\n input,\n input.canCommit,\n );\n}\n"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"organizationProvisioningAttemptPersistence.js","sourceRoot":"","sources":["organizationProvisioningAttemptPersistence.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,EAAE,EAAE,MAAM,aAAa,CAAC;AACtC,OAAO,EACL,gCAAgC,EAChC,qCAAqC,GACtC,MAAM,2DAA2D,CAAC;AACnE,OAAO,EAEL,iCAAiC,GAClC,MAAM,uCAAuC,CAAC;AAC/C,OAAO,EAEL,eAAe,EACf,wBAAwB,GACzB,MAAM,wBAAwB,CAAC;AAUhC,MAAM,CAAC,MAAM,6CAA6C,GAAG;IAC3D,KAAK,CAAC,IAAI,CACR,OAAgB,EAChB,sBAA8B;QAE9B,MAAM,eAAe,CAAC,OAAO,EAAE,qCAAq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ACR,CACF;iBACA,GAAG,EAAE,CAAC;QACX,CAAC,CAAC;QACF,IAAI,CAAC,SAAS,EAAE,CAAC;YACf,MAAM,OAAO,CAAC,WAAW,CAAC,MAAM,CAAC,CAAC;YAClC,OAAO,IAAI,CAAC;QACd,CAAC;QACD,OAAO,CAAC,MAAM,OAAO,CAAC,kBAAkB,CAAC,MAAM,EAAE,SAAS,CAAC,CAAC,CAAC,SAAS,CAAC;IACzE,CAAC;CACF,CAAC","sourcesContent":["import { and, eq } from \"drizzle-orm\";\nimport {\n organizationProvisioningAttempts,\n organizationProvisioningAttemptTables,\n} from \"../../sqlite/schema/organizationProvisioningAttemptSchema\";\nimport {\n type ClientSQLiteTransactionScope,\n getClientSQLitePersistenceRuntime,\n} from \"../../sqlite/sqlitePersistenceRuntime\";\nimport {\n type ExecSql,\n ensureSqlTables,\n runSerializedSqlMutation,\n} from \"../../sqlite/sqlSchema\";\n\ninterface OrganizationProvisioningAttemptRecord {\n readonly replacedOrganizationId: string;\n readonly userId: string;\n readonly organizationId: string;\n readonly rootContainerId: string;\n readonly serializedArtifacts: string;\n}\n\nexport const sqlOrganizationProvisioningAttemptPersistence = {\n async load(\n execSql: ExecSql,\n replacedOrganizationId: string,\n ): Promise<OrganizationProvisioningAttemptRecord | null> {\n await ensureSqlTables(execSql, organizationProvisioningAttemptTables);\n const [stored] = await getClientSQLitePersistenceRuntime(execSql)\n .db.select({\n replacedOrganizationId:\n organizationProvisioningAttempts.replacedOrganizationId,\n userId: organizationProvisioningAttempts.userId,\n organizationId: organizationProvisioningAttempts.organizationId,\n rootContainerId: organizationProvisioningAttempts.rootContainerId,\n serializedArtifacts:\n organizationProvisioningAttempts.serializedArtifacts,\n })\n .from(organizationProvisioningAttempts)\n .where(\n eq(\n organizationProvisioningAttempts.replacedOrganizationId,\n replacedOrganizationId,\n ),\n );\n return stored ?? null;\n },\n\n async loadOrSave(\n execSql: ExecSql,\n candidate: OrganizationProvisioningAttemptRecord & {\n readonly creationIntent?: string | undefined;\n },\n canSave?: (() => boolean) | undefined,\n ): Promise<OrganizationProvisioningAttemptRecord | null> {\n return runSerializedSqlMutation(execSql, async (lockedExecSql) => {\n await ensureSqlTables(\n lockedExecSql,\n organizationProvisioningAttemptTables,\n );\n if (canSave && !canSave()) return null;\n const { db } = getClientSQLitePersistenceRuntime(lockedExecSql);\n await db\n .insert(organizationProvisioningAttempts)\n .values({ ...candidate, createdAt: new Date().toISOString() })\n .onConflictDoNothing()\n .run();\n const [stored] = await db\n .select({\n replacedOrganizationId:\n organizationProvisioningAttempts.replacedOrganizationId,\n userId: organizationProvisioningAttempts.userId,\n organizationId: organizationProvisioningAttempts.organizationId,\n rootContainerId: organizationProvisioningAttempts.rootContainerId,\n serializedArtifacts:\n organizationProvisioningAttempts.serializedArtifacts,\n })\n .from(organizationProvisioningAttempts)\n .where(\n candidate.creationIntent\n ? and(\n eq(organizationProvisioningAttempts.userId, candidate.userId),\n eq(\n organizationProvisioningAttempts.creationIntent,\n candidate.creationIntent,\n ),\n )\n : eq(\n organizationProvisioningAttempts.replacedOrganizationId,\n candidate.replacedOrganizationId,\n ),\n );\n if (!stored) {\n throw new Error(\"Organization provisioning attempt was not persisted\");\n }\n return stored;\n });\n },\n\n async remove(\n execSql: ExecSql,\n input: {\n organizationId?: string | undefined;\n replacedOrganizationId: string;\n userId: string;\n },\n canCommit?: (() => boolean) | undefined,\n ): Promise<boolean> {\n await ensureSqlTables(execSql, organizationProvisioningAttemptTables);\n if (canCommit && !canCommit()) return false;\n const runtime = getClientSQLitePersistenceRuntime(execSql);\n const remove = async (tx: ClientSQLiteTransactionScope) => {\n await tx\n .delete(organizationProvisioningAttempts)\n .where(\n and(\n eq(\n organizationProvisioningAttempts.replacedOrganizationId,\n input.replacedOrganizationId,\n ),\n eq(organizationProvisioningAttempts.userId, input.userId),\n ...(input.organizationId\n ? [\n eq(\n organizationProvisioningAttempts.organizationId,\n input.organizationId,\n ),\n ]\n : []),\n ),\n )\n .run();\n };\n if (!canCommit) {\n await runtime.transaction(remove);\n return true;\n }\n return (await runtime.guardedTransaction(remove, canCommit)).committed;\n },\n};\n"]}
|