@ankhorage/projects 0.7.3 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (67) hide show
  1. package/README.md +19 -12
  2. package/dist/capabilities/index.d.ts +330 -0
  3. package/dist/capabilities/index.js +194 -0
  4. package/dist/capabilities/socialManagerMediaAnalytics.d.ts +92 -0
  5. package/dist/capabilities/socialManagerMediaAnalytics.js +75 -0
  6. package/dist/features/projects/composition/composeGeneratedRuntimeMaterialization.d.ts +1 -0
  7. package/dist/features/projects/composition/composeGeneratedRuntimeMaterialization.js +13 -5
  8. package/dist/features/projects/composition/createExpoProjectMaterializer.js +27 -23
  9. package/dist/features/projects/composition/createRootNavigatorGenerationOptions.d.ts +9 -0
  10. package/dist/features/projects/composition/createRootNavigatorGenerationOptions.js +10 -0
  11. package/dist/features/projects/composition/createSocialManagerServerFiles.d.ts +6 -0
  12. package/dist/features/projects/composition/createSocialManagerServerFiles.js +16 -0
  13. package/dist/features/trusted-social-manager-host/adapters/createConnectionFileSystemRepositories.d.ts +16 -0
  14. package/dist/features/trusted-social-manager-host/adapters/createConnectionFileSystemRepositories.js +201 -0
  15. package/dist/features/trusted-social-manager-host/adapters/createConnectionFileSystemStoreAsync.d.ts +25 -0
  16. package/dist/features/trusted-social-manager-host/adapters/createConnectionFileSystemStoreAsync.js +72 -0
  17. package/dist/features/trusted-social-manager-host/adapters/createSocialManagerDraftStoreAsync.d.ts +7 -0
  18. package/dist/features/trusted-social-manager-host/adapters/createSocialManagerDraftStoreAsync.js +160 -0
  19. package/dist/features/trusted-social-manager-host/adapters/createSocialManagerFlowSecurityAsync.d.ts +19 -0
  20. package/dist/features/trusted-social-manager-host/adapters/createSocialManagerFlowSecurityAsync.js +176 -0
  21. package/dist/features/trusted-social-manager-host/adapters/createSocialManagerMediaPreflight.d.ts +4 -0
  22. package/dist/features/trusted-social-manager-host/adapters/createSocialManagerMediaPreflight.js +37 -0
  23. package/dist/features/trusted-social-manager-host/adapters/createSocialManagerMediaStoreAsync.d.ts +7 -0
  24. package/dist/features/trusted-social-manager-host/adapters/createSocialManagerMediaStoreAsync.js +242 -0
  25. package/dist/features/trusted-social-manager-host/adapters/createSocialOperationStoresAsync.d.ts +13 -0
  26. package/dist/features/trusted-social-manager-host/adapters/createSocialOperationStoresAsync.js +244 -0
  27. package/dist/features/trusted-social-manager-host/adapters/projectSocialManagerConnection.d.ts +53 -0
  28. package/dist/features/trusted-social-manager-host/adapters/projectSocialManagerConnection.js +42 -0
  29. package/dist/features/trusted-social-manager-host/application/createSocialManagerPublicationRuntime.d.ts +10 -0
  30. package/dist/features/trusted-social-manager-host/application/createSocialManagerPublicationRuntime.js +240 -0
  31. package/dist/features/trusted-social-manager-host/application/resolveSocialManagerPublication.d.ts +22 -0
  32. package/dist/features/trusted-social-manager-host/application/resolveSocialManagerPublication.js +97 -0
  33. package/dist/features/trusted-social-manager-host/composition/createSocialManagerCapabilityOperations.d.ts +22 -0
  34. package/dist/features/trusted-social-manager-host/composition/createSocialManagerCapabilityOperations.js +224 -0
  35. package/dist/features/trusted-social-manager-host/composition/createSocialManagerConnectionOperations.d.ts +20 -0
  36. package/dist/features/trusted-social-manager-host/composition/createSocialManagerConnectionOperations.js +152 -0
  37. package/dist/features/trusted-social-manager-host/composition/createSocialManagerLocalProviderFixtures.d.ts +22 -0
  38. package/dist/features/trusted-social-manager-host/composition/createSocialManagerLocalProviderFixtures.js +271 -0
  39. package/dist/features/trusted-social-manager-host/composition/createSocialManagerMediaOperations.d.ts +14 -0
  40. package/dist/features/trusted-social-manager-host/composition/createSocialManagerMediaOperations.js +72 -0
  41. package/dist/features/trusted-social-manager-host/composition/createSocialManagerProvider.d.ts +20 -0
  42. package/dist/features/trusted-social-manager-host/composition/createSocialManagerProvider.js +20 -0
  43. package/dist/features/trusted-social-manager-host/composition/createSocialManagerPublicationOperations.d.ts +15 -0
  44. package/dist/features/trusted-social-manager-host/composition/createSocialManagerPublicationOperations.js +185 -0
  45. package/dist/features/trusted-social-manager-host/composition/createTrustedSocialManagerFileSystemPersistenceAsync.d.ts +14 -0
  46. package/dist/features/trusted-social-manager-host/composition/createTrustedSocialManagerFileSystemPersistenceAsync.js +17 -0
  47. package/dist/features/trusted-social-manager-host/composition/createTrustedSocialManagerHost.d.ts +51 -0
  48. package/dist/features/trusted-social-manager-host/composition/createTrustedSocialManagerHost.js +188 -0
  49. package/dist/features/trusted-social-manager-host/composition/createTrustedSocialManagerLocalHostAsync.d.ts +18 -0
  50. package/dist/features/trusted-social-manager-host/composition/createTrustedSocialManagerLocalHostAsync.js +177 -0
  51. package/dist/features/trusted-social-manager-host/composition/createTrustedSocialManagerLocalServerAsync.d.ts +26 -0
  52. package/dist/features/trusted-social-manager-host/composition/createTrustedSocialManagerLocalServerAsync.js +66 -0
  53. package/dist/features/trusted-social-manager-host/domain/publicationConfig.d.ts +18 -0
  54. package/dist/features/trusted-social-manager-host/domain/publicationConfig.js +77 -0
  55. package/dist/features/trusted-social-manager-host/domain/readSocialManagerConnectionRequest.d.ts +54 -0
  56. package/dist/features/trusted-social-manager-host/domain/readSocialManagerConnectionRequest.js +77 -0
  57. package/dist/features/trusted-social-manager-host/domain/readSocialManagerDraftContent.d.ts +3 -0
  58. package/dist/features/trusted-social-manager-host/domain/readSocialManagerDraftContent.js +47 -0
  59. package/dist/features/trusted-social-manager-host/domain/socialManagerConnectionIdentity.d.ts +17 -0
  60. package/dist/features/trusted-social-manager-host/domain/socialManagerConnectionIdentity.js +17 -0
  61. package/dist/index.d.ts +16 -0
  62. package/dist/index.js +14 -0
  63. package/dist/types/socialManager.d.ts +77 -0
  64. package/dist/types/socialManager.js +1 -0
  65. package/dist/types/socialManagerPublication.d.ts +27 -0
  66. package/dist/types/socialManagerPublication.js +1 -0
  67. package/package.json +506 -8
@@ -0,0 +1,51 @@
1
+ import type { ApiRequest, ComposeAuthorizedApiRuntimeOptions } from '@ankhorage/api';
2
+ import { type FastifyInstance, type RegisterFastifyApiOptions } from '@ankhorage/api-fastify';
3
+ import type { InternalRestApiDefinition } from '@ankhorage/contracts/data';
4
+ import type { SocialManagerCaller, SocialManagerDraftStore, SocialManagerScope } from '../../../types/socialManager.js';
5
+ import type { SocialManagerPublicationDependencies } from '../../../types/socialManagerPublication.js';
6
+ import { type CreateSocialManagerFlowSecurityInput } from '../adapters/createSocialManagerFlowSecurityAsync.js';
7
+ import { type SocialManagerCapabilityHostDependencies } from './createSocialManagerCapabilityOperations.js';
8
+ import { type SocialManagerConnectionHostDependencies } from './createSocialManagerConnectionOperations.js';
9
+ import { type SocialManagerMediaHostDependencies } from './createSocialManagerMediaOperations.js';
10
+ import { type SocialManagerPublicationHostDependencies } from './createSocialManagerPublicationOperations.js';
11
+ export type CreateTrustedSocialManagerHostInput = Readonly<{
12
+ appId: string;
13
+ scope: SocialManagerScope;
14
+ definition: InternalRestApiDefinition;
15
+ drafts: SocialManagerDraftStore;
16
+ connection?: SocialManagerConnectionHostDependencies;
17
+ media?: SocialManagerMediaHostDependencies;
18
+ capabilities?: SocialManagerCapabilityHostDependencies;
19
+ publication?: SocialManagerPublicationHostDependencies;
20
+ authenticateCallerAsync: (request: ApiRequest) => Promise<SocialManagerCaller | undefined>;
21
+ authorizeCallerAsync: (input: Readonly<{
22
+ caller: SocialManagerCaller;
23
+ appId: string;
24
+ operationId: string;
25
+ }>) => Promise<boolean>;
26
+ }>;
27
+ export type CreateTrustedSocialManagerHostAsyncInput = Omit<CreateTrustedSocialManagerHostInput, 'publication'> & Readonly<{
28
+ publication: Omit<SocialManagerPublicationDependencies, 'flow'> & {
29
+ readonly flow: Omit<SocialManagerPublicationDependencies['flow'], 'security'>;
30
+ readonly security: Omit<CreateSocialManagerFlowSecurityInput, 'scope' | 'store'> & {
31
+ readonly directory: string;
32
+ };
33
+ };
34
+ }>;
35
+ export type TrustedSocialManagerHost = Readonly<{
36
+ composition: ComposeAuthorizedApiRuntimeOptions;
37
+ registerFastifyAsync: (server: FastifyInstance, options?: RegisterFastifyApiOptions) => Promise<unknown>;
38
+ startWorkerAsync?: () => Readonly<{
39
+ stop: () => Promise<void>;
40
+ }>;
41
+ }>;
42
+ /***
43
+ * Compose the Social Manager draft operations with authenticated, scoped API delivery.
44
+ * Unimplemented provider or execution operations are not registered or simulated.
45
+ */
46
+ export declare function createTrustedSocialManagerHost(input: CreateTrustedSocialManagerHostInput): TrustedSocialManagerHost;
47
+ /***
48
+ * Compose the canonical durable Flow security port and publication runtime before HTTP delivery.
49
+ * The embedding host supplies its durable store, audit, grant, rate-limit, and secret boundaries.
50
+ */
51
+ export declare function createTrustedSocialManagerHostAsync(input: CreateTrustedSocialManagerHostAsyncInput): Promise<TrustedSocialManagerHost>;
@@ -0,0 +1,188 @@
1
+ import { registerAuthorizedFastifyApiAsync, } from '@ankhorage/api-fastify';
2
+ import { startFlowWorkerAsync } from '@ankhorage/flow/server';
3
+ import { isRecord } from '@ankhorage/utility/object';
4
+ import { CAPABILITIES } from '../../../capabilities/index.js';
5
+ import { createSocialManagerFlowSecurityAsync, } from '../adapters/createSocialManagerFlowSecurityAsync.js';
6
+ import { createSocialManagerPublicationRuntime } from '../application/createSocialManagerPublicationRuntime.js';
7
+ import { readSocialManagerDraftContent } from '../domain/readSocialManagerDraftContent.js';
8
+ import { createSocialManagerCapabilityOperations, } from './createSocialManagerCapabilityOperations.js';
9
+ import { createSocialManagerConnectionOperations, } from './createSocialManagerConnectionOperations.js';
10
+ import { createSocialManagerMediaOperations, } from './createSocialManagerMediaOperations.js';
11
+ import { createSocialManagerPublicationOperations, } from './createSocialManagerPublicationOperations.js';
12
+ /***
13
+ * Compose the Social Manager draft operations with authenticated, scoped API delivery.
14
+ * Unimplemented provider or execution operations are not registered or simulated.
15
+ */
16
+ export function createTrustedSocialManagerHost(input) {
17
+ const scope = Object.freeze({ ...input.scope });
18
+ assertHostIdentity(input.appId, scope);
19
+ const callers = new WeakMap();
20
+ const operations = {
21
+ ...createDraftOperations(input.drafts, scope),
22
+ ...(input.connection === undefined
23
+ ? {}
24
+ : createSocialManagerConnectionOperations(input.connection, (request) => callers.get(request))),
25
+ ...(input.media === undefined
26
+ ? {}
27
+ : createSocialManagerMediaOperations(input.media, (request) => callers.get(request))),
28
+ ...(input.capabilities === undefined
29
+ ? {}
30
+ : createSocialManagerCapabilityOperations(input.capabilities, (request) => callers.get(request))),
31
+ ...(input.publication === undefined
32
+ ? {}
33
+ : createSocialManagerPublicationOperations(input.publication, (request) => callers.get(request))),
34
+ };
35
+ const composition = createHostComposition(input, scope, operations, callers);
36
+ return {
37
+ composition,
38
+ registerFastifyAsync: (server, options) => registerAuthorizedFastifyApiAsync(server, composition, options),
39
+ };
40
+ }
41
+ /***
42
+ * Compose the canonical durable Flow security port and publication runtime before HTTP delivery.
43
+ * The embedding host supplies its durable store, audit, grant, rate-limit, and secret boundaries.
44
+ */
45
+ export async function createTrustedSocialManagerHostAsync(input) {
46
+ const { publication } = input;
47
+ const security = await createSocialManagerFlowSecurityAsync(publication.security.directory, {
48
+ ...publication.security,
49
+ scope: input.scope,
50
+ store: publication.flow.store,
51
+ });
52
+ const runtime = createSocialManagerPublicationRuntime({
53
+ ...publication,
54
+ flow: { ...publication.flow, security },
55
+ });
56
+ return {
57
+ ...createTrustedSocialManagerHost({ ...input, publication: { runtime } }),
58
+ // The worker is deliberately created from this exact runtime; a second scheduler would
59
+ // break durable publication and approval ownership across the HTTP and worker boundaries.
60
+ startWorkerAsync: () => startFlowWorkerAsync({ runtime: runtime.runtime }),
61
+ };
62
+ }
63
+ /*** Bind declared API operations to the verified caller and canonical capability catalog. */
64
+ function createHostComposition(input, scope, operations, callers) {
65
+ return {
66
+ definition: input.definition,
67
+ context: { appId: input.appId, projectId: scope.projectId },
68
+ authorizeAsync: async ({ binding, request }) => authorizeAsync(input, scope, binding.operationId, request, callers),
69
+ resolveHandler: ({ binding, declaration, context }) => {
70
+ const capability = CAPABILITIES.find((candidate) => candidate.id === declaration.capability);
71
+ const operation = Object.hasOwn(operations, binding.operationId)
72
+ ? operations[binding.operationId]
73
+ : undefined;
74
+ if (!capability ||
75
+ !operation ||
76
+ binding.operationId !== capability.id ||
77
+ binding.operation.intent !== operation.intent ||
78
+ binding.method !== operation.method) {
79
+ return undefined;
80
+ }
81
+ return {
82
+ capability,
83
+ approval: {
84
+ operationId: binding.operationId,
85
+ intent: operation.intent,
86
+ method: operation.method,
87
+ capabilityId: capability.id,
88
+ owner: capability.owner,
89
+ scope: context,
90
+ },
91
+ handler: operation.handler,
92
+ };
93
+ },
94
+ };
95
+ }
96
+ /*** Reject incomplete server-owned identity before exposing operations. */
97
+ function assertHostIdentity(appId, scope) {
98
+ if (!appId.trim() ||
99
+ !scope.tenantId.trim() ||
100
+ !scope.projectId.trim() ||
101
+ !scope.environmentId.trim()) {
102
+ throw new Error('Social Manager host identity is incomplete.');
103
+ }
104
+ }
105
+ /*** Authorize the real caller before exposing any draft state or mutation. */
106
+ async function authorizeAsync(input, scope, operationId, request, callers) {
107
+ try {
108
+ const caller = await input.authenticateCallerAsync(request);
109
+ const authorized = caller !== undefined &&
110
+ typeof caller.actorId === 'string' &&
111
+ caller.actorId.trim().length > 0 &&
112
+ caller.tenantId === scope.tenantId &&
113
+ caller.projectId === scope.projectId &&
114
+ caller.environmentId === scope.environmentId &&
115
+ (await input.authorizeCallerAsync({ caller, appId: input.appId, operationId }));
116
+ if (authorized)
117
+ callers.set(request, caller);
118
+ return authorized;
119
+ }
120
+ catch {
121
+ return false;
122
+ }
123
+ }
124
+ /*** Bind only the implemented draft operations to the trusted project scope. */
125
+ function createDraftOperations(drafts, scope) {
126
+ return {
127
+ 'projects.social.drafts.create': {
128
+ intent: 'create',
129
+ method: 'POST',
130
+ handler: async (request) => {
131
+ const content = readSocialManagerDraftContent(request.body);
132
+ return content
133
+ ? { status: 201, body: await drafts.createAsync(scope, content) }
134
+ : invalidResponse();
135
+ },
136
+ },
137
+ 'projects.social.drafts.list': {
138
+ intent: 'read',
139
+ method: 'GET',
140
+ handler: async () => ({ body: await drafts.listAsync(scope) }),
141
+ },
142
+ 'projects.social.drafts.read': {
143
+ intent: 'read',
144
+ method: 'GET',
145
+ handler: async (request) => {
146
+ const id = request.params.draftId;
147
+ if (!id)
148
+ return invalidResponse();
149
+ const draft = await drafts.readAsync(scope, id);
150
+ return draft ? { body: draft } : missingResponse();
151
+ },
152
+ },
153
+ 'projects.social.drafts.update': {
154
+ intent: 'update',
155
+ method: 'PATCH',
156
+ handler: async (request) => updateDraftAsync(drafts, scope, request),
157
+ },
158
+ };
159
+ }
160
+ /*** Apply an optimistic revision check; edits never mutate already approved content revisions. */
161
+ async function updateDraftAsync(drafts, scope, request) {
162
+ const id = request.params.draftId;
163
+ const { body } = request;
164
+ if (!id ||
165
+ !isRecord(body) ||
166
+ typeof body.expectedRevision !== 'number' ||
167
+ !Number.isSafeInteger(body.expectedRevision) ||
168
+ body.expectedRevision < 1) {
169
+ return invalidResponse();
170
+ }
171
+ const content = readSocialManagerDraftContent(body.content);
172
+ if (!content)
173
+ return invalidResponse();
174
+ const result = await drafts.updateAsync(scope, id, body.expectedRevision, content);
175
+ if (result.status === 'updated')
176
+ return { body: result.draft };
177
+ return result.status === 'not-found'
178
+ ? missingResponse()
179
+ : { status: 409, body: { error: { code: 'draft_revision_conflict' } } };
180
+ }
181
+ /*** Return a stable validation error without echoing untrusted input. */
182
+ function invalidResponse() {
183
+ return { status: 400, body: { error: { code: 'invalid_draft' } } };
184
+ }
185
+ /*** Do not distinguish an absent draft from one outside the authorized scope. */
186
+ function missingResponse() {
187
+ return { status: 404, body: { error: { code: 'draft_not_found' } } };
188
+ }
@@ -0,0 +1,18 @@
1
+ import type { createSocialManagerLocalProviderFixtures } from './createSocialManagerLocalProviderFixtures.js';
2
+ import type { createTrustedSocialManagerFileSystemPersistenceAsync } from './createTrustedSocialManagerFileSystemPersistenceAsync.js';
3
+ import type { CreateTrustedSocialManagerLocalServerAsyncInput } from './createTrustedSocialManagerLocalServerAsync.js';
4
+ type LocalHostInput = Readonly<{
5
+ input: CreateTrustedSocialManagerLocalServerAsyncInput;
6
+ persistence: Awaited<ReturnType<typeof createTrustedSocialManagerFileSystemPersistenceAsync>>;
7
+ fixtures: ReturnType<typeof createSocialManagerLocalProviderFixtures>;
8
+ now: () => string;
9
+ }>;
10
+ /*** Compose a local host from the durable stores and deterministic provider fixtures selected by the loopback server. */
11
+ export declare function createTrustedSocialManagerLocalHostAsync({ input, persistence, fixtures, now, }: LocalHostInput): Promise<Readonly<{
12
+ composition: import("@ankhorage/api").ComposeAuthorizedApiRuntimeOptions;
13
+ registerFastifyAsync: (server: import("fastify").FastifyInstance, options?: import("@ankhorage/api-fastify").RegisterFastifyApiOptions) => Promise<unknown>;
14
+ startWorkerAsync?: () => Readonly<{
15
+ stop: () => Promise<void>;
16
+ }>;
17
+ }>>;
18
+ export {};
@@ -0,0 +1,177 @@
1
+ import { join } from 'node:path';
2
+ import { FileFlowPersistenceAdapter, FileFlowRuntimeStore } from '@ankhorage/flow';
3
+ import { createSocialManagerMediaPreflight } from '../adapters/createSocialManagerMediaPreflight.js';
4
+ import { createTrustedSocialManagerHostAsync } from './createTrustedSocialManagerHost.js';
5
+ /*** Compose a local host from the durable stores and deterministic provider fixtures selected by the loopback server. */
6
+ export async function createTrustedSocialManagerLocalHostAsync({ input, persistence, fixtures, now, }) {
7
+ const resolveBindingAsync = createBindingResolver(persistence.connection, fixtures, input.caller);
8
+ const resolveMediaAsync = createMediaResolver(persistence.media);
9
+ return createTrustedSocialManagerHostAsync({
10
+ appId: input.appId,
11
+ scope: input.scope,
12
+ definition: input.definition,
13
+ drafts: persistence.drafts,
14
+ connection: createConnectionDependencies(persistence, fixtures, now),
15
+ media: {
16
+ store: persistence.media,
17
+ isReferencedAsync: (caller, mediaId) => persistence.drafts.isMediaReferencedAsync(caller, mediaId),
18
+ },
19
+ capabilities: createCapabilityDependencies(persistence, fixtures, resolveBindingAsync, resolveMediaAsync, now),
20
+ publication: createPublicationDependencies(input, persistence, fixtures, resolveBindingAsync, resolveMediaAsync),
21
+ authenticateCallerAsync: (request) => Promise.resolve(request.headers.authorization === `Bearer ${input.development.token}`
22
+ ? input.caller
23
+ : undefined),
24
+ authorizeCallerAsync: () => Promise.resolve(true),
25
+ });
26
+ }
27
+ /*** Bind the released Connection lifecycle implementation to its durable local store and deterministic fixture ports. */
28
+ function createConnectionDependencies(persistence, fixtures, now) {
29
+ return {
30
+ store: persistence.connection,
31
+ authorization: fixtures.authorization,
32
+ now,
33
+ healthAsync: fixtures.healthAsync,
34
+ revocation: fixtures.revocation,
35
+ };
36
+ }
37
+ /*** Bind capability queries to the same server-resolved target and immutable media paths as publication. */
38
+ function createCapabilityDependencies(persistence, fixtures, resolveBindingAsync, resolveMediaAsync, now) {
39
+ return {
40
+ drafts: persistence.drafts,
41
+ resolveBindingAsync,
42
+ resolveAnalyticsBindingAsync: async (caller, destination) => {
43
+ const binding = await resolveBindingAsync(caller, destination);
44
+ return binding === undefined
45
+ ? undefined
46
+ : { ...binding, analytics: analyticsFor(fixtures, binding.target) };
47
+ },
48
+ resolveMediaAsync,
49
+ now,
50
+ };
51
+ }
52
+ /*** Bind one durable Flow runtime to publication, security, provider discovery, and fixture-only media validation. */
53
+ function createPublicationDependencies(input, persistence, fixtures, resolveBindingAsync, resolveMediaAsync) {
54
+ return {
55
+ scope: input.scope,
56
+ drafts: persistence.drafts,
57
+ flow: {
58
+ store: FileFlowRuntimeStore(join(input.dataDirectory, 'social-flow-runtime.json')),
59
+ persistence: FileFlowPersistenceAdapter(join(input.dataDirectory, 'social-flow-worker.json')),
60
+ },
61
+ security: {
62
+ directory: input.dataDirectory,
63
+ grants: [
64
+ {
65
+ actorId: input.caller.actorId,
66
+ capability: 'projects.social.publication.execute',
67
+ tenantId: input.scope.tenantId,
68
+ projectId: input.scope.projectId,
69
+ environment: input.scope.environmentId,
70
+ },
71
+ ],
72
+ audit: { writeAsync: () => Promise.resolve(undefined) },
73
+ rateLimit: { acquireAsync: () => Promise.resolve(true) },
74
+ secretStore: createDevelopmentSecretStore(),
75
+ },
76
+ discovery: persistence.connection.targetDiscovery,
77
+ resolveBindingAsync,
78
+ resolveMediaAsync,
79
+ mediaPreflight: createSocialManagerMediaPreflight(persistence.media, (command) => providerFor(fixtures, command.target).getCapabilityAsync(command.target)),
80
+ };
81
+ }
82
+ /*** Resolve a caller-owned durable connection and provider-specific target without accepting target details from HTTP. */
83
+ function createBindingResolver(store, fixtures, configuredCaller) {
84
+ return async (caller, destination) => {
85
+ if (!sameCaller(caller, configuredCaller))
86
+ return undefined;
87
+ const connection = await store.delegatedAuthorizationRepository.loadConnectionAsync(destination.connectionId);
88
+ const target = connection && targetForConnection(connection, destination.targetId);
89
+ return connection && target
90
+ ? { connection, target, provider: providerFor(fixtures, target) }
91
+ : undefined;
92
+ };
93
+ }
94
+ /*** Load immutable caller-owned media and retain the exact order requested by the stored draft. */
95
+ function createMediaResolver(media) {
96
+ return async (caller, mediaIds) => {
97
+ const items = await Promise.all(mediaIds.map((mediaId) => media.loadAsync(caller, mediaId)));
98
+ return items.flatMap((item) => (item === undefined ? [] : [item.media]));
99
+ };
100
+ }
101
+ /*** Verify the durable connection owner and map its selected authorized target to the published provider vocabulary. */
102
+ function targetForConnection(connection, targetId) {
103
+ const target = connection.targets.find((candidate) => candidate.targetId === targetId);
104
+ if (!target || connection.status !== 'connected')
105
+ return undefined;
106
+ const base = { accountId: connection.accountId, destinationId: target.targetId };
107
+ switch (connection.provider) {
108
+ case 'facebook-login':
109
+ return { ...base, provider: 'facebook', accountType: 'page', destinationType: 'page' };
110
+ case 'instagram-login':
111
+ return {
112
+ ...base,
113
+ provider: 'instagram',
114
+ accountType: 'business',
115
+ destinationType: 'account',
116
+ };
117
+ case 'linkedin':
118
+ return { ...base, provider: 'linkedin', accountType: 'member', destinationType: 'member' };
119
+ case 'pinterest':
120
+ return { ...base, provider: 'pinterest', accountType: 'business', destinationType: 'board' };
121
+ }
122
+ }
123
+ /*** Select exactly one local provider fixture from the server-resolved target provider. */
124
+ function providerFor(fixtures, target) {
125
+ switch (target.provider) {
126
+ case 'facebook':
127
+ return fixtures.providers.facebook;
128
+ case 'instagram':
129
+ return fixtures.providers.instagram;
130
+ case 'linkedin':
131
+ return fixtures.providers.linkedin;
132
+ case 'pinterest':
133
+ return fixtures.providers.pinterest;
134
+ default:
135
+ throw new Error('Social Manager provider is unsupported.');
136
+ }
137
+ }
138
+ /*** Select analytics from the same server-resolved provider as publication. */
139
+ function analyticsFor(fixtures, target) {
140
+ switch (target.provider) {
141
+ case 'facebook':
142
+ return fixtures.analytics.facebook;
143
+ case 'instagram':
144
+ return fixtures.analytics.instagram;
145
+ case 'linkedin':
146
+ return fixtures.analytics.linkedin;
147
+ case 'pinterest':
148
+ return fixtures.analytics.pinterest;
149
+ default:
150
+ throw new Error('Social Manager analytics provider is unsupported.');
151
+ }
152
+ }
153
+ /*** Compare every server-owned scope and actor field before reusing a configured development caller. */
154
+ function sameCaller(left, right) {
155
+ return (left.tenantId === right.tenantId &&
156
+ left.projectId === right.projectId &&
157
+ left.environmentId === right.environmentId &&
158
+ left.actorId === right.actorId);
159
+ }
160
+ /*** Provide the fixture-only empty secret boundary; local providers never request credentials. */
161
+ function createDevelopmentSecretStore() {
162
+ const unavailable = () => Promise.resolve({
163
+ ok: false,
164
+ error: {
165
+ code: 'not_found',
166
+ message: 'Development fixtures do not store credentials.',
167
+ },
168
+ });
169
+ return {
170
+ list: unavailable,
171
+ getMetadata: unavailable,
172
+ create: unavailable,
173
+ replace: unavailable,
174
+ remove: unavailable,
175
+ resolve: unavailable,
176
+ };
177
+ }
@@ -0,0 +1,26 @@
1
+ import type { AppManifest } from '@ankhorage/contracts';
2
+ import type { InternalRestApiDefinition } from '@ankhorage/contracts/data';
3
+ import type { SocialManagerCaller, SocialManagerScope } from '../../../types/socialManager.js';
4
+ export type CreateTrustedSocialManagerLocalServerAsyncInput = Readonly<{
5
+ readonly appId: string;
6
+ readonly dataDirectory: string;
7
+ readonly definition: InternalRestApiDefinition;
8
+ readonly development: Readonly<{
9
+ readonly enabled: true;
10
+ readonly hostname: '127.0.0.1' | '::1';
11
+ readonly token: string;
12
+ }>;
13
+ readonly scope: SocialManagerScope;
14
+ readonly caller: SocialManagerCaller;
15
+ }>;
16
+ export type TrustedSocialManagerLocalServer = Readonly<{
17
+ readonly closeAsync: () => Promise<void>;
18
+ readonly listenAsync: (port: number) => Promise<void>;
19
+ }>;
20
+ /*** Find the manifest-declared internal API that binds one or more Social Manager capabilities. */
21
+ export declare function findTrustedSocialManagerApiDefinition(manifest: AppManifest): InternalRestApiDefinition | undefined;
22
+ /***
23
+ * Compose the explicitly enabled loopback-only Social Manager development server.
24
+ * It shares one durable Flow runtime between authenticated HTTP operations and the worker.
25
+ */
26
+ export declare function createTrustedSocialManagerLocalServerAsync(input: CreateTrustedSocialManagerLocalServerAsyncInput): Promise<TrustedSocialManagerLocalServer>;
@@ -0,0 +1,66 @@
1
+ import { createFastifyApiServer } from '@ankhorage/api-fastify';
2
+ import { createSocialManagerLocalProviderFixtures } from './createSocialManagerLocalProviderFixtures.js';
3
+ import { createTrustedSocialManagerFileSystemPersistenceAsync } from './createTrustedSocialManagerFileSystemPersistenceAsync.js';
4
+ import { createTrustedSocialManagerLocalHostAsync } from './createTrustedSocialManagerLocalHostAsync.js';
5
+ /*** Find the manifest-declared internal API that binds one or more Social Manager capabilities. */
6
+ export function findTrustedSocialManagerApiDefinition(manifest) {
7
+ return Object.values(manifest.infra.apis ?? {}).find((api) => api.origin === 'internal' &&
8
+ Object.values(api.handlers ?? {}).some((handler) => handler.capability.startsWith('projects.social.')));
9
+ }
10
+ /***
11
+ * Compose the explicitly enabled loopback-only Social Manager development server.
12
+ * It shares one durable Flow runtime between authenticated HTTP operations and the worker.
13
+ */
14
+ export async function createTrustedSocialManagerLocalServerAsync(input) {
15
+ assertDevelopmentConfiguration(input);
16
+ const persistence = await createTrustedSocialManagerFileSystemPersistenceAsync(input.dataDirectory);
17
+ const now = () => new Date().toISOString();
18
+ const fixtures = createSocialManagerLocalProviderFixtures({
19
+ operations: persistence.operations,
20
+ now,
21
+ });
22
+ const host = await createTrustedSocialManagerLocalHostAsync({
23
+ input,
24
+ persistence,
25
+ fixtures,
26
+ now,
27
+ });
28
+ const worker = host.startWorkerAsync?.();
29
+ if (!worker)
30
+ throw new Error('Social Manager host did not expose its Flow worker lifecycle.');
31
+ const server = createFastifyApiServer();
32
+ try {
33
+ await host.registerFastifyAsync(server, { prefix: input.definition.basePath });
34
+ }
35
+ catch (error) {
36
+ await worker.stop();
37
+ await server.close();
38
+ throw error;
39
+ }
40
+ return {
41
+ listenAsync: async (port) => {
42
+ if (!Number.isSafeInteger(port) || port < 1 || port > 65_535)
43
+ throw new Error('Social Manager server port is invalid.');
44
+ await server.listen({ host: input.development.hostname, port });
45
+ },
46
+ closeAsync: async () => {
47
+ await worker.stop();
48
+ await server.close();
49
+ },
50
+ };
51
+ }
52
+ /*** Reject production-shaped, non-loopback, or incomplete development configuration before storage is opened. */
53
+ function assertDevelopmentConfiguration(input) {
54
+ if (!isLoopbackHost(input.development.hostname) ||
55
+ !input.development.token.trim() ||
56
+ input.caller.tenantId !== input.scope.tenantId ||
57
+ input.caller.projectId !== input.scope.projectId ||
58
+ input.caller.environmentId !== input.scope.environmentId ||
59
+ !input.caller.actorId.trim()) {
60
+ throw new Error('Social Manager development fixtures require an explicit loopback configuration.');
61
+ }
62
+ }
63
+ /*** Accept only literal loopback listeners so development fixtures cannot become remotely reachable. */
64
+ function isLoopbackHost(hostname) {
65
+ return hostname === '127.0.0.1' || hostname === '::1';
66
+ }
@@ -0,0 +1,18 @@
1
+ import type { FlowNode } from '@ankhorage/contracts/flow';
2
+ import type { SocialTargetRef } from '@ankhorage/social';
3
+ import type { SocialManagerCaller, SocialManagerScope } from '../../../types/socialManager.js';
4
+ export interface PublicationConfig {
5
+ readonly caller: SocialManagerCaller;
6
+ readonly draftId: string;
7
+ readonly revision: number;
8
+ readonly destinationIndex: number;
9
+ readonly runAt: string;
10
+ readonly connectionRevision: string;
11
+ readonly target: SocialTargetRef;
12
+ }
13
+ /*** Reject a cross-scope or incomplete authenticated caller. */
14
+ export declare function assertCallerScope(scope: SocialManagerScope, caller: SocialManagerScope): void;
15
+ /*** Narrow the persisted server-owned graph configuration before using it. */
16
+ export declare function readPublicationConfig(node: FlowNode, scope: SocialManagerScope): PublicationConfig;
17
+ /*** Compare every provider-neutral destination identity component. */
18
+ export declare function sameTarget(left: SocialTargetRef, right: SocialTargetRef): boolean;
@@ -0,0 +1,77 @@
1
+ import { isRecord } from '@ankhorage/utility/object';
2
+ /*** Reject a cross-scope or incomplete authenticated caller. */
3
+ export function assertCallerScope(scope, caller) {
4
+ if (!scope.tenantId ||
5
+ !scope.projectId ||
6
+ !scope.environmentId ||
7
+ caller.tenantId !== scope.tenantId ||
8
+ caller.projectId !== scope.projectId ||
9
+ caller.environmentId !== scope.environmentId)
10
+ throw new Error('Social publication scope mismatch.');
11
+ }
12
+ /*** Narrow the persisted server-owned graph configuration before using it. */
13
+ export function readPublicationConfig(node, scope) {
14
+ const ref = node.config?.publication;
15
+ const value = ref?.kind === 'inline' ? ref.value : undefined;
16
+ if (!isRecord(value) ||
17
+ !isRecord(value.caller) ||
18
+ !isRecord(value.target) ||
19
+ typeof value.draftId !== 'string' ||
20
+ typeof value.revision !== 'number' ||
21
+ typeof value.destinationIndex !== 'number' ||
22
+ typeof value.runAt !== 'string' ||
23
+ typeof value.connectionRevision !== 'string')
24
+ throw new Error('Invalid publication graph configuration.');
25
+ const caller = readCaller(value.caller);
26
+ const target = readTarget(value.target);
27
+ const config = {
28
+ caller,
29
+ target,
30
+ draftId: value.draftId,
31
+ revision: value.revision,
32
+ destinationIndex: value.destinationIndex,
33
+ runAt: value.runAt,
34
+ connectionRevision: value.connectionRevision,
35
+ };
36
+ assertCallerScope(scope, config.caller);
37
+ return config;
38
+ }
39
+ /*** Project the authenticated actor recorded in the server-created graph. */
40
+ function readCaller(value) {
41
+ if (typeof value.actorId !== 'string' ||
42
+ !value.actorId.trim() ||
43
+ typeof value.tenantId !== 'string' ||
44
+ typeof value.projectId !== 'string' ||
45
+ typeof value.environmentId !== 'string')
46
+ throw new Error('Invalid publication caller.');
47
+ return {
48
+ actorId: value.actorId,
49
+ tenantId: value.tenantId,
50
+ projectId: value.projectId,
51
+ environmentId: value.environmentId,
52
+ };
53
+ }
54
+ /*** Project the exact provider-neutral target pinned by the server. */
55
+ function readTarget(value) {
56
+ if (typeof value.provider !== 'string' ||
57
+ typeof value.accountId !== 'string' ||
58
+ typeof value.accountType !== 'string' ||
59
+ typeof value.destinationId !== 'string' ||
60
+ typeof value.destinationType !== 'string')
61
+ throw new Error('Invalid publication target.');
62
+ return {
63
+ provider: value.provider,
64
+ accountId: value.accountId,
65
+ accountType: value.accountType,
66
+ destinationId: value.destinationId,
67
+ destinationType: value.destinationType,
68
+ };
69
+ }
70
+ /*** Compare every provider-neutral destination identity component. */
71
+ export function sameTarget(left, right) {
72
+ return (left.provider === right.provider &&
73
+ left.accountId === right.accountId &&
74
+ left.accountType === right.accountType &&
75
+ left.destinationId === right.destinationId &&
76
+ left.destinationType === right.destinationType);
77
+ }