@ms-cloudpack/api-server 0.59.0 → 0.60.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 (36) hide show
  1. package/lib/apis/ensurePackageBundled.d.ts +13 -7
  2. package/lib/apis/ensurePackageBundled.d.ts.map +1 -1
  3. package/lib/apis/ensurePackageBundled.js +8 -4
  4. package/lib/apis/ensurePackageBundled.js.map +1 -1
  5. package/lib/apis/syncUpload.d.ts +5 -2
  6. package/lib/apis/syncUpload.d.ts.map +1 -1
  7. package/lib/apis/syncUpload.js +1 -0
  8. package/lib/apis/syncUpload.js.map +1 -1
  9. package/lib/common/createApiContext.d.ts +29 -0
  10. package/lib/common/createApiContext.d.ts.map +1 -0
  11. package/lib/common/createApiContext.js +62 -0
  12. package/lib/common/createApiContext.js.map +1 -0
  13. package/lib/index.d.ts +1 -2
  14. package/lib/index.d.ts.map +1 -1
  15. package/lib/index.js +1 -1
  16. package/lib/index.js.map +1 -1
  17. package/lib/types/Context.d.ts +5 -3
  18. package/lib/types/Context.d.ts.map +1 -1
  19. package/lib/types/Context.js.map +1 -1
  20. package/lib/utilities/TaskRunner.d.ts +22 -11
  21. package/lib/utilities/TaskRunner.d.ts.map +1 -1
  22. package/lib/utilities/TaskRunner.js +24 -25
  23. package/lib/utilities/TaskRunner.js.map +1 -1
  24. package/package.json +2 -2
  25. package/lib/common/createPartialApiContext.d.ts +0 -17
  26. package/lib/common/createPartialApiContext.d.ts.map +0 -1
  27. package/lib/common/createPartialApiContext.js +0 -163
  28. package/lib/common/createPartialApiContext.js.map +0 -1
  29. package/lib/types/TaskOptions.d.ts +0 -6
  30. package/lib/types/TaskOptions.d.ts.map +0 -1
  31. package/lib/types/TaskOptions.js +0 -2
  32. package/lib/types/TaskOptions.js.map +0 -1
  33. package/lib/types/TaskRunnerContext.d.ts +0 -3
  34. package/lib/types/TaskRunnerContext.d.ts.map +0 -1
  35. package/lib/types/TaskRunnerContext.js +0 -2
  36. package/lib/types/TaskRunnerContext.js.map +0 -1
@@ -1,6 +1,6 @@
1
1
  import type { BundleRequest } from '../types/BundleRequest.js';
2
- import type { ApiParams } from '../types/ApiParams.js';
3
- import type { TargetEnvironment } from '@ms-cloudpack/common-types';
2
+ import type { Context } from '../types/Context.js';
3
+ import type { TargetEnvironment, WithOptional } from '@ms-cloudpack/common-types';
4
4
  /**
5
5
  * Input for `ensurePackageBundled`.
6
6
  */
@@ -16,7 +16,10 @@ export interface EnsurePackageBundledInput extends Pick<BundleRequest, 'outputPa
16
16
  enqueueDependencies?: boolean;
17
17
  /** Whether to re-run the bundle task */
18
18
  shouldRerun?: boolean;
19
- /** Whether to watch for changes (internal packages only) */
19
+ /**
20
+ * Whether to watch for changes (internal packages only).
21
+ * NOTE: requires `ctx.bus` and `ctx.watcher` to be set.
22
+ */
20
23
  shouldWatch?: boolean;
21
24
  /** Whether to force re-bundling */
22
25
  shouldForce?: boolean;
@@ -57,10 +60,13 @@ export interface EnsurePackageBundledOutput {
57
60
  /** Results of bundling dependencies */
58
61
  dependencies: Promise<EnsurePackageBundledResult[]>;
59
62
  }
63
+ export type EnsurePackageBundledContext = WithOptional<Context, 'bus' | 'watcher'>;
60
64
  /**
61
- * Checks if the package is bundled or needs bundling, and returns the result. For internal packages,
62
- * we also notify the watcher to monitor for code changes.
65
+ * Checks if the package is bundled or needs bundling, and returns the result.
66
+ * For internal packages, we also notify the watcher to monitor for code changes.
63
67
  */
64
- export declare function ensurePackageBundled(params: ApiParams<EnsurePackageBundledInput, 'bus' | 'taskRunner' | 'session' | 'watcher' | 'packages' | 'reporter' | 'telemetryClient' | 'packageHashes' | 'remoteCacheClient'>): Promise<EnsurePackageBundledOutput>;
65
- export type EnsurePackageBundledContext = Parameters<typeof ensurePackageBundled>[0]['ctx'];
68
+ export declare function ensurePackageBundled(params: {
69
+ input: EnsurePackageBundledInput;
70
+ ctx: EnsurePackageBundledContext;
71
+ }): Promise<EnsurePackageBundledOutput>;
66
72
  //# sourceMappingURL=ensurePackageBundled.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"ensurePackageBundled.d.ts","sourceRoot":"","sources":["../../src/apis/ensurePackageBundled.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,2BAA2B,CAAC;AAE/D,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,uBAAuB,CAAC;AAGvD,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,4BAA4B,CAAC;AAEpE;;GAEG;AACH,MAAM,WAAW,yBACf,SAAQ,IAAI,CAAC,aAAa,EAAE,YAAY,GAAG,SAAS,GAAG,mBAAmB,GAAG,qBAAqB,CAAC;IACnG,mBAAmB;IACnB,IAAI,EAAE,MAAM,CAAC;IACb;;;OAGG;IACH,iBAAiB,CAAC,EAAE,iBAAiB,CAAC;IACtC,sDAAsD;IACtD,mBAAmB,CAAC,EAAE,OAAO,CAAC;IAC9B,wCAAwC;IACxC,WAAW,CAAC,EAAE,OAAO,CAAC;IACtB,4DAA4D;IAC5D,WAAW,CAAC,EAAE,OAAO,CAAC;IACtB,mCAAmC;IACnC,WAAW,CAAC,EAAE,OAAO,CAAC;IACtB,kCAAkC;IAClC,YAAY,CAAC,EAAE,OAAO,CAAC;IACvB,wFAAwF;IACxF,aAAa,CAAC,EAAE,OAAO,CAAC;IACxB;;;;OAIG;IACH,WAAW,CAAC,EAAE,OAAO,CAAC;IACtB,uFAAuF;IACvF,QAAQ,CAAC,EAAE,MAAM,CAAC;CACnB;AAED;;GAEG;AACH,MAAM,WAAW,0BACf,SAAQ,IAAI,CAAC,WAAW,CAAC,aAAa,CAAC,QAAQ,CAAC,CAAC,EAAE,SAAS,GAAG,SAAS,GAAG,aAAa,GAAG,WAAW,CAAC;IACvG,mBAAmB;IACnB,IAAI,EAAE,MAAM,CAAC;IACb,sBAAsB;IACtB,OAAO,EAAE,MAAM,CAAC;IAChB,+CAA+C;IAC/C,YAAY,CAAC,EAAE,MAAM,EAAE,CAAC;IACxB,2FAA2F;IAC3F,UAAU,CAAC,EAAE,OAAO,CAAC;IACrB,oFAAoF;IACpF,SAAS,CAAC,EAAE,MAAM,CAAC;CACpB;AAED;;GAEG;AACH,MAAM,WAAW,0BAA0B;IACzC,sCAAsC;IACtC,MAAM,EAAE,0BAA0B,CAAC;IACnC,uCAAuC;IACvC,YAAY,EAAE,OAAO,CAAC,0BAA0B,EAAE,CAAC,CAAC;CACrD;AAED;;;GAGG;AACH,wBAAsB,oBAAoB,CACxC,MAAM,EAAE,SAAS,CACf,yBAAyB,EACvB,KAAK,GACL,YAAY,GACZ,SAAS,GACT,SAAS,GACT,UAAU,GACV,UAAU,GACV,iBAAiB,GACjB,eAAe,GACf,mBAAmB,CACtB,GACA,OAAO,CAAC,0BAA0B,CAAC,CAyDrC;AAyJD,MAAM,MAAM,2BAA2B,GAAG,UAAU,CAAC,OAAO,oBAAoB,CAAC,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC"}
1
+ {"version":3,"file":"ensurePackageBundled.d.ts","sourceRoot":"","sources":["../../src/apis/ensurePackageBundled.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,2BAA2B,CAAC;AAE/D,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,qBAAqB,CAAC;AAGnD,OAAO,KAAK,EAAE,iBAAiB,EAAE,YAAY,EAAE,MAAM,4BAA4B,CAAC;AAElF;;GAEG;AACH,MAAM,WAAW,yBACf,SAAQ,IAAI,CAAC,aAAa,EAAE,YAAY,GAAG,SAAS,GAAG,mBAAmB,GAAG,qBAAqB,CAAC;IACnG,mBAAmB;IACnB,IAAI,EAAE,MAAM,CAAC;IACb;;;OAGG;IACH,iBAAiB,CAAC,EAAE,iBAAiB,CAAC;IACtC,sDAAsD;IACtD,mBAAmB,CAAC,EAAE,OAAO,CAAC;IAC9B,wCAAwC;IACxC,WAAW,CAAC,EAAE,OAAO,CAAC;IACtB;;;OAGG;IACH,WAAW,CAAC,EAAE,OAAO,CAAC;IACtB,mCAAmC;IACnC,WAAW,CAAC,EAAE,OAAO,CAAC;IACtB,kCAAkC;IAClC,YAAY,CAAC,EAAE,OAAO,CAAC;IACvB,wFAAwF;IACxF,aAAa,CAAC,EAAE,OAAO,CAAC;IACxB;;;;OAIG;IACH,WAAW,CAAC,EAAE,OAAO,CAAC;IACtB,uFAAuF;IACvF,QAAQ,CAAC,EAAE,MAAM,CAAC;CACnB;AAED;;GAEG;AACH,MAAM,WAAW,0BACf,SAAQ,IAAI,CAAC,WAAW,CAAC,aAAa,CAAC,QAAQ,CAAC,CAAC,EAAE,SAAS,GAAG,SAAS,GAAG,aAAa,GAAG,WAAW,CAAC;IACvG,mBAAmB;IACnB,IAAI,EAAE,MAAM,CAAC;IACb,sBAAsB;IACtB,OAAO,EAAE,MAAM,CAAC;IAChB,+CAA+C;IAC/C,YAAY,CAAC,EAAE,MAAM,EAAE,CAAC;IACxB,2FAA2F;IAC3F,UAAU,CAAC,EAAE,OAAO,CAAC;IACrB,oFAAoF;IACpF,SAAS,CAAC,EAAE,MAAM,CAAC;CACpB;AAED;;GAEG;AACH,MAAM,WAAW,0BAA0B;IACzC,sCAAsC;IACtC,MAAM,EAAE,0BAA0B,CAAC;IACnC,uCAAuC;IACvC,YAAY,EAAE,OAAO,CAAC,0BAA0B,EAAE,CAAC,CAAC;CACrD;AAED,MAAM,MAAM,2BAA2B,GAAG,YAAY,CAAC,OAAO,EAAE,KAAK,GAAG,SAAS,CAAC,CAAC;AAEnF;;;GAGG;AAEH,wBAAsB,oBAAoB,CAAC,MAAM,EAAE;IACjD,KAAK,EAAE,yBAAyB,CAAC;IACjC,GAAG,EAAE,2BAA2B,CAAC;CAClC,GAAG,OAAO,CAAC,0BAA0B,CAAC,CAyDtC"}
@@ -3,9 +3,10 @@ import { notifyReload } from '../utilities/notifyReload.js';
3
3
  import { createBundleTask } from '../utilities/createBundleTask.js';
4
4
  import { getConsumedDependencies } from '../utilities/getConsumedDependencies.js';
5
5
  /**
6
- * Checks if the package is bundled or needs bundling, and returns the result. For internal packages,
7
- * we also notify the watcher to monitor for code changes.
6
+ * Checks if the package is bundled or needs bundling, and returns the result.
7
+ * For internal packages, we also notify the watcher to monitor for code changes.
8
8
  */
9
+ // This is not actually a tRPC API, but it follows the same signature for now.
9
10
  export async function ensurePackageBundled(params) {
10
11
  const { input, ctx } = params;
11
12
  const results = [];
@@ -63,7 +64,7 @@ export async function ensurePackageBundled(params) {
63
64
  async function ensurePackageBundledInternal(params) {
64
65
  const { input, ctx, visited } = params;
65
66
  const { name, version, shouldWatch, disableSourceMaps, outputPath, shouldGetBundleInfo, shouldRerun, shouldForce, disableCache, isIncremental, useHashAsId, priority, targetEnvironment = 'browser', } = input;
66
- const { taskRunner, session, watcher, packageHashes } = ctx;
67
+ const { taskRunner, session, watcher, packageHashes, bus, telemetryClient } = ctx;
67
68
  const { resolveMap, config } = session;
68
69
  const { features } = config;
69
70
  const enqueueDependencies = input.enqueueDependencies ?? features?.enqueueDependencies;
@@ -121,6 +122,9 @@ async function ensurePackageBundledInternal(params) {
121
122
  }
122
123
  // For internal packages, make sure we're watching the source to re-trigger bundling.
123
124
  if (shouldWatch && !isExternal) {
125
+ if (!bus || !watcher) {
126
+ throw new Error('bus and watcher must be provided in context if shouldWatch is true (this is a bug).');
127
+ }
124
128
  const definition = await ctx.packages.get(packageEntry.path);
125
129
  const watchOptions = {
126
130
  id: bundleRequest.id,
@@ -131,7 +135,7 @@ async function ensurePackageBundledInternal(params) {
131
135
  const watchedResult = await taskRunner.add(task, { rerun: true });
132
136
  // If the result was successful, notify potential clients for reload.
133
137
  if (watchedResult.result?.errors?.length === 0) {
134
- await notifyReload({ reason: 'on-package-change' }, ctx);
138
+ await notifyReload({ reason: 'on-package-change' }, { bus, session, telemetryClient });
135
139
  }
136
140
  };
137
141
  watcher.watch(watchOptions, () => {
@@ -1 +1 @@
1
- {"version":3,"file":"ensurePackageBundled.js","sourceRoot":"","sources":["../../src/apis/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AACJ,CAAC;AAID,kGAAkG","sourcesContent":["import { findResolveMapEntry } from '@ms-cloudpack/package-utilities';\nimport { notifyReload } from '../utilities/notifyReload.js';\nimport type { BundleRequest } from '../types/BundleRequest.js';\nimport { createBundleTask } from '../utilities/createBundleTask.js';\nimport type { ApiParams } from '../types/ApiParams.js';\nimport type { WatchOptions } from '@ms-cloudpack/file-watcher';\nimport { getConsumedDependencies } from '../utilities/getConsumedDependencies.js';\nimport type { TargetEnvironment } from '@ms-cloudpack/common-types';\n\n/**\n * Input for `ensurePackageBundled`.\n */\nexport interface EnsurePackageBundledInput\n extends Pick<BundleRequest, 'outputPath' | 'version' | 'disableSourceMaps' | 'shouldGetBundleInfo'> {\n /** Package name */\n name: string;\n /**\n * Target environment for the bundle.\n * @default 'browser'\n */\n targetEnvironment?: TargetEnvironment;\n /** Whether to also ensure dependencies are bundled */\n enqueueDependencies?: boolean;\n /** Whether to re-run the bundle task */\n shouldRerun?: boolean;\n /** Whether to watch for changes (internal packages only) */\n shouldWatch?: boolean;\n /** Whether to force re-bundling */\n shouldForce?: boolean;\n /** Whether to disable caching. */\n disableCache?: boolean;\n /** Whether to support incremental rebuilds. Defaults to true for internal libraries. */\n isIncremental?: boolean;\n /**\n * Whether to use a hash as the bundle id instead of the path.\n * Reduces performance when used with shouldForce as it hashes twice,\n * but eliminates task cache artifacts when handling many apps.\n */\n useHashAsId?: boolean;\n /** Priority for bundling. Greater priority will be scheduled first (defaults to 0). */\n priority?: number;\n}\n\n/**\n * Result of ensuring a single package is bundled.\n */\nexport interface EnsurePackageBundledResult\n extends Omit<NonNullable<BundleRequest['result']>, 'rebuild' | 'dispose' | 'bundlerName' | 'inputPath'> {\n /** Package name */\n name: string;\n /** Package version */\n version: string;\n /** Package dependency names (prod and peer) */\n dependencies?: string[];\n /** Whether the package is external (not defined in this repo). Unset if it's not found. */\n isExternal?: boolean;\n /** Absolute path of the package. Will be unset if the package couldn't be found. */\n inputPath?: string;\n}\n\n/**\n * Complete output for `ensurePackageBundled`.\n */\nexport interface EnsurePackageBundledOutput {\n /** Result of bundling this package */\n result: EnsurePackageBundledResult;\n /** Results of bundling dependencies */\n dependencies: Promise<EnsurePackageBundledResult[]>;\n}\n\n/**\n * Checks if the package is bundled or needs bundling, and returns the result. For internal packages,\n * we also notify the watcher to monitor for code changes.\n */\nexport async function ensurePackageBundled(\n params: ApiParams<\n EnsurePackageBundledInput,\n | 'bus'\n | 'taskRunner'\n | 'session'\n | 'watcher'\n | 'packages'\n | 'reporter'\n | 'telemetryClient'\n | 'packageHashes'\n | 'remoteCacheClient'\n >,\n): Promise<EnsurePackageBundledOutput> {\n const { input, ctx } = params;\n const results: EnsurePackageBundledResult[] = [];\n const visited = new Set<`${string}@${string}`>();\n\n // Bundle the package itself\n let result: EnsurePackageBundledResult;\n let mainDependencies: EnsurePackageBundledInput[];\n try {\n ({ result, dependencyInputs: mainDependencies } = await ensurePackageBundledInternal({ input, ctx, visited }));\n } catch (err) {\n return {\n result: getErrorResult(input, err),\n dependencies: Promise.resolve([]),\n };\n }\n\n // Enqueue main dependencies\n // TODO: should processing this queue have a rate limit? right now if enqueueDependencies is enabled,\n // `await dependencies` will fire off all deps at once.\n let pending = 0;\n const dependencies = new Promise<EnsurePackageBundledResult[]>((resolve) => {\n const enqueue = (dependencyInputs: EnsurePackageBundledInput[]) => {\n for (const dependencyInput of dependencyInputs) {\n pending++;\n\n void ensurePackageBundledInternal({\n input: dependencyInput,\n ctx,\n visited,\n })\n .then((dependencyBundleResult) => {\n // Save result and enqueue this dep's deps\n results.push(dependencyBundleResult.result);\n enqueue(dependencyBundleResult.dependencyInputs);\n })\n .catch((err) => {\n // If there's an error (most likely that the dependency wasn't found in the resolve map),\n // save it in a result instead of throwing. This generally gives better logging.\n results.push(getErrorResult(dependencyInput, err));\n })\n .then(() => {\n pending--;\n if (!pending) {\n resolve(results);\n }\n });\n }\n };\n\n enqueue(mainDependencies);\n });\n\n return {\n result,\n dependencies,\n };\n}\n\nasync function ensurePackageBundledInternal(\n params: Parameters<typeof ensurePackageBundled>[0] & {\n visited: Set<`${string}@${string}`>;\n },\n): Promise<{ result: EnsurePackageBundledResult; dependencyInputs: EnsurePackageBundledInput[] }> {\n const { input, ctx, visited } = params;\n const {\n name,\n version,\n shouldWatch,\n disableSourceMaps,\n outputPath,\n shouldGetBundleInfo,\n shouldRerun,\n shouldForce,\n disableCache,\n isIncremental,\n useHashAsId,\n priority,\n targetEnvironment = 'browser',\n } = input;\n const { taskRunner, session, watcher, packageHashes } = ctx;\n const { resolveMap, config } = session;\n const { features } = config;\n const enqueueDependencies = input.enqueueDependencies ?? features?.enqueueDependencies;\n const dependencyInputs: EnsurePackageBundledInput[] = [];\n\n visited.add(`${name}@${version}`);\n\n // First, we find the resolve map entry. This helps us resolve the physical location of the package\n // according to the resolveMap used in the session. (This can change based on linking.)\n const packageEntry = findResolveMapEntry({ packageName: name, version, resolveMap });\n\n if (!packageEntry) {\n throw new Error(`Could not find package ${name} in the resolve map.`);\n }\n\n const isExternal = !!packageEntry.isExternal;\n\n let hash: string | undefined = undefined;\n let sourceHash: string | undefined = undefined;\n\n if (useHashAsId) {\n // If we are using the hash as the task id, we need to calculate it once and pass it to the task\n // to prevent a race condition in which we get a different hash than the one used in the task id.\n hash = await packageHashes.get({\n packagePath: packageEntry.path,\n isSourceHashingEnabled: false,\n shouldRecalculate: true,\n });\n\n if (!packageEntry.isExternal) {\n // We only need the source hash for internal packages for cache validation.\n sourceHash = await packageHashes.get({\n packagePath: packageEntry.path,\n isSourceHashingEnabled: true,\n shouldRecalculate: true,\n });\n }\n }\n\n const bundleRequest: BundleRequest = {\n // TODO: David had this as follows--think about what it should be\n // id: hash ?? `${packageEntry.path}--env:${targetEnvironment}`,\n id: (useHashAsId && hash) || packageEntry.path,\n packagePath: packageEntry.path,\n packageName: name,\n targetEnvironment,\n isExternal,\n isIncremental,\n outputPath,\n version,\n disableSourceMaps: disableSourceMaps ?? features?.disableSourceMaps,\n shouldGetBundleInfo: shouldGetBundleInfo || enqueueDependencies,\n disableCache,\n mode: config.mode,\n };\n\n // Make priority negative to have retry count set to positive values.\n const retryCount = priority ? -1 * priority : undefined;\n\n const task = createBundleTask({ bundleRequest, force: shouldForce, hash, sourceHash, retryCount }, ctx);\n\n // TODO: Add lage scheduling back.\n const { result } = await taskRunner.add<BundleRequest>(task, { rerun: shouldRerun, priority });\n\n if (!result) {\n throw new Error('Bundle failed, no result');\n }\n\n // For internal packages, make sure we're watching the source to re-trigger bundling.\n if (shouldWatch && !isExternal) {\n const definition = await ctx.packages.get(packageEntry.path);\n const watchOptions: WatchOptions = {\n id: bundleRequest.id,\n path: packageEntry.path,\n watchPaths: definition.cloudpack?.inputPaths,\n };\n\n const onPackageChange = async () => {\n const watchedResult = await taskRunner.add<BundleRequest>(task, { rerun: true });\n\n // If the result was successful, notify potential clients for reload.\n if (watchedResult.result?.errors?.length === 0) {\n await notifyReload({ reason: 'on-package-change' }, ctx);\n }\n };\n watcher.watch(watchOptions, () => {\n void onPackageChange();\n });\n }\n\n // If enabled, enqueue dependencies.\n if (enqueueDependencies && result.info) {\n for (const dependencyName of getConsumedDependencies(result.info)) {\n const dependencyVersion = packageEntry.dependencies[dependencyName];\n\n // If we've already visited this package from another package, skip it.\n if (visited.has(`${dependencyName}@${dependencyVersion}`)) {\n continue;\n }\n\n dependencyInputs.push({\n name: dependencyName,\n version: dependencyVersion,\n shouldWatch,\n enqueueDependencies,\n });\n }\n }\n\n return {\n result: {\n version,\n name,\n isExternal,\n ...result,\n },\n dependencyInputs,\n };\n}\n\nfunction getErrorResult(input: EnsurePackageBundledInput, error: unknown): EnsurePackageBundledResult {\n const text = `Error thrown while bundling: ${error instanceof Error ? error.stack || error.message : error}`;\n return {\n name: input.name,\n version: input.version,\n errors: [{ text, source: 'ensurePackageBundled' }],\n };\n}\n\nexport type EnsurePackageBundledContext = Parameters<typeof ensurePackageBundled>[0]['ctx'];\n\n// This function doesn't have an attached procedure because it's never called via the TRPC server.\n"]}
1
+ {"version":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AAK,IAAI,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,KAAK,EAAE,CAAC;IAC7G,OAAO;QACL,IAAI,EAAE,KAAK,CAAC,IAAI;QAChB,OAAO,EAAE,KAAK,CAAC,OAAO;QACtB,MAAM,EAAE,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,sBAAsB,EAAE,CAAC;KACnD,CAAC;AACJ,CAAC;AAED,kGAAkG","sourcesContent":["import { findResolveMapEntry } from '@ms-cloudpack/package-utilities';\nimport { notifyReload } from '../utilities/notifyReload.js';\nimport type { BundleRequest } from '../types/BundleRequest.js';\nimport { createBundleTask } from '../utilities/createBundleTask.js';\nimport type { Context } from '../types/Context.js';\nimport type { WatchOptions } from '@ms-cloudpack/file-watcher';\nimport { getConsumedDependencies } from '../utilities/getConsumedDependencies.js';\nimport type { TargetEnvironment, WithOptional } from '@ms-cloudpack/common-types';\n\n/**\n * Input for `ensurePackageBundled`.\n */\nexport interface EnsurePackageBundledInput\n extends Pick<BundleRequest, 'outputPath' | 'version' | 'disableSourceMaps' | 'shouldGetBundleInfo'> {\n /** Package name */\n name: string;\n /**\n * Target environment for the bundle.\n * @default 'browser'\n */\n targetEnvironment?: TargetEnvironment;\n /** Whether to also ensure dependencies are bundled */\n enqueueDependencies?: boolean;\n /** Whether to re-run the bundle task */\n shouldRerun?: boolean;\n /**\n * Whether to watch for changes (internal packages only).\n * NOTE: requires `ctx.bus` and `ctx.watcher` to be set.\n */\n shouldWatch?: boolean;\n /** Whether to force re-bundling */\n shouldForce?: boolean;\n /** Whether to disable caching. */\n disableCache?: boolean;\n /** Whether to support incremental rebuilds. Defaults to true for internal libraries. */\n isIncremental?: boolean;\n /**\n * Whether to use a hash as the bundle id instead of the path.\n * Reduces performance when used with shouldForce as it hashes twice,\n * but eliminates task cache artifacts when handling many apps.\n */\n useHashAsId?: boolean;\n /** Priority for bundling. Greater priority will be scheduled first (defaults to 0). */\n priority?: number;\n}\n\n/**\n * Result of ensuring a single package is bundled.\n */\nexport interface EnsurePackageBundledResult\n extends Omit<NonNullable<BundleRequest['result']>, 'rebuild' | 'dispose' | 'bundlerName' | 'inputPath'> {\n /** Package name */\n name: string;\n /** Package version */\n version: string;\n /** Package dependency names (prod and peer) */\n dependencies?: string[];\n /** Whether the package is external (not defined in this repo). Unset if it's not found. */\n isExternal?: boolean;\n /** Absolute path of the package. Will be unset if the package couldn't be found. */\n inputPath?: string;\n}\n\n/**\n * Complete output for `ensurePackageBundled`.\n */\nexport interface EnsurePackageBundledOutput {\n /** Result of bundling this package */\n result: EnsurePackageBundledResult;\n /** Results of bundling dependencies */\n dependencies: Promise<EnsurePackageBundledResult[]>;\n}\n\nexport type EnsurePackageBundledContext = WithOptional<Context, 'bus' | 'watcher'>;\n\n/**\n * Checks if the package is bundled or needs bundling, and returns the result.\n * For internal packages, we also notify the watcher to monitor for code changes.\n */\n// This is not actually a tRPC API, but it follows the same signature for now.\nexport async function ensurePackageBundled(params: {\n input: EnsurePackageBundledInput;\n ctx: EnsurePackageBundledContext;\n}): Promise<EnsurePackageBundledOutput> {\n const { input, ctx } = params;\n const results: EnsurePackageBundledResult[] = [];\n const visited = new Set<`${string}@${string}`>();\n\n // Bundle the package itself\n let result: EnsurePackageBundledResult;\n let mainDependencies: EnsurePackageBundledInput[];\n try {\n ({ result, dependencyInputs: mainDependencies } = await ensurePackageBundledInternal({ input, ctx, visited }));\n } catch (err) {\n return {\n result: getErrorResult(input, err),\n dependencies: Promise.resolve([]),\n };\n }\n\n // Enqueue main dependencies\n // TODO: should processing this queue have a rate limit? right now if enqueueDependencies is enabled,\n // `await dependencies` will fire off all deps at once.\n let pending = 0;\n const dependencies = new Promise<EnsurePackageBundledResult[]>((resolve) => {\n const enqueue = (dependencyInputs: EnsurePackageBundledInput[]) => {\n for (const dependencyInput of dependencyInputs) {\n pending++;\n\n void ensurePackageBundledInternal({\n input: dependencyInput,\n ctx,\n visited,\n })\n .then((dependencyBundleResult) => {\n // Save result and enqueue this dep's deps\n results.push(dependencyBundleResult.result);\n enqueue(dependencyBundleResult.dependencyInputs);\n })\n .catch((err) => {\n // If there's an error (most likely that the dependency wasn't found in the resolve map),\n // save it in a result instead of throwing. This generally gives better logging.\n results.push(getErrorResult(dependencyInput, err));\n })\n .then(() => {\n pending--;\n if (!pending) {\n resolve(results);\n }\n });\n }\n };\n\n enqueue(mainDependencies);\n });\n\n return {\n result,\n dependencies,\n };\n}\n\nasync function ensurePackageBundledInternal(\n params: Parameters<typeof ensurePackageBundled>[0] & {\n visited: Set<`${string}@${string}`>;\n },\n): Promise<{ result: EnsurePackageBundledResult; dependencyInputs: EnsurePackageBundledInput[] }> {\n const { input, ctx, visited } = params;\n const {\n name,\n version,\n shouldWatch,\n disableSourceMaps,\n outputPath,\n shouldGetBundleInfo,\n shouldRerun,\n shouldForce,\n disableCache,\n isIncremental,\n useHashAsId,\n priority,\n targetEnvironment = 'browser',\n } = input;\n const { taskRunner, session, watcher, packageHashes, bus, telemetryClient } = ctx;\n const { resolveMap, config } = session;\n const { features } = config;\n const enqueueDependencies = input.enqueueDependencies ?? features?.enqueueDependencies;\n const dependencyInputs: EnsurePackageBundledInput[] = [];\n\n visited.add(`${name}@${version}`);\n\n // First, we find the resolve map entry. This helps us resolve the physical location of the package\n // according to the resolveMap used in the session. (This can change based on linking.)\n const packageEntry = findResolveMapEntry({ packageName: name, version, resolveMap });\n\n if (!packageEntry) {\n throw new Error(`Could not find package ${name} in the resolve map.`);\n }\n\n const isExternal = !!packageEntry.isExternal;\n\n let hash: string | undefined = undefined;\n let sourceHash: string | undefined = undefined;\n\n if (useHashAsId) {\n // If we are using the hash as the task id, we need to calculate it once and pass it to the task\n // to prevent a race condition in which we get a different hash than the one used in the task id.\n hash = await packageHashes.get({\n packagePath: packageEntry.path,\n isSourceHashingEnabled: false,\n shouldRecalculate: true,\n });\n\n if (!packageEntry.isExternal) {\n // We only need the source hash for internal packages for cache validation.\n sourceHash = await packageHashes.get({\n packagePath: packageEntry.path,\n isSourceHashingEnabled: true,\n shouldRecalculate: true,\n });\n }\n }\n\n const bundleRequest: BundleRequest = {\n // TODO: David had this as follows--think about what it should be\n // id: hash ?? `${packageEntry.path}--env:${targetEnvironment}`,\n id: (useHashAsId && hash) || packageEntry.path,\n packagePath: packageEntry.path,\n packageName: name,\n targetEnvironment,\n isExternal,\n isIncremental,\n outputPath,\n version,\n disableSourceMaps: disableSourceMaps ?? features?.disableSourceMaps,\n shouldGetBundleInfo: shouldGetBundleInfo || enqueueDependencies,\n disableCache,\n mode: config.mode,\n };\n\n // Make priority negative to have retry count set to positive values.\n const retryCount = priority ? -1 * priority : undefined;\n\n const task = createBundleTask({ bundleRequest, force: shouldForce, hash, sourceHash, retryCount }, ctx);\n\n // TODO: Add lage scheduling back.\n const { result } = await taskRunner.add<BundleRequest>(task, { rerun: shouldRerun, priority });\n\n if (!result) {\n throw new Error('Bundle failed, no result');\n }\n\n // For internal packages, make sure we're watching the source to re-trigger bundling.\n if (shouldWatch && !isExternal) {\n if (!bus || !watcher) {\n throw new Error('bus and watcher must be provided in context if shouldWatch is true (this is a bug).');\n }\n\n const definition = await ctx.packages.get(packageEntry.path);\n const watchOptions: WatchOptions = {\n id: bundleRequest.id,\n path: packageEntry.path,\n watchPaths: definition.cloudpack?.inputPaths,\n };\n\n const onPackageChange = async () => {\n const watchedResult = await taskRunner.add<BundleRequest>(task, { rerun: true });\n\n // If the result was successful, notify potential clients for reload.\n if (watchedResult.result?.errors?.length === 0) {\n await notifyReload({ reason: 'on-package-change' }, { bus, session, telemetryClient });\n }\n };\n watcher.watch(watchOptions, () => {\n void onPackageChange();\n });\n }\n\n // If enabled, enqueue dependencies.\n if (enqueueDependencies && result.info) {\n for (const dependencyName of getConsumedDependencies(result.info)) {\n const dependencyVersion = packageEntry.dependencies[dependencyName];\n\n // If we've already visited this package from another package, skip it.\n if (visited.has(`${dependencyName}@${dependencyVersion}`)) {\n continue;\n }\n\n dependencyInputs.push({\n name: dependencyName,\n version: dependencyVersion,\n shouldWatch,\n enqueueDependencies,\n });\n }\n }\n\n return {\n result: {\n version,\n name,\n isExternal,\n ...result,\n },\n dependencyInputs,\n };\n}\n\nfunction getErrorResult(input: EnsurePackageBundledInput, error: unknown): EnsurePackageBundledResult {\n const text = `Error thrown while bundling: ${error instanceof Error ? error.stack || error.message : error}`;\n return {\n name: input.name,\n version: input.version,\n errors: [{ text, source: 'ensurePackageBundled' }],\n };\n}\n\n// This function doesn't have an attached procedure because it's never called via the TRPC server.\n"]}
@@ -1,4 +1,7 @@
1
- import type { ApiParams } from '../types/ApiParams.js';
1
+ import { type EnsurePackageBundledContext } from './ensurePackageBundled.js';
2
2
  import type { SyncResult } from '../types/SyncResult.js';
3
- export declare function syncUpload(params: ApiParams<undefined, 'session' | 'packages' | 'reporter' | 'bus' | 'taskRunner' | 'watcher' | 'telemetryClient' | 'packageHashes' | 'remoteCacheClient'>): Promise<SyncResult>;
3
+ export declare function syncUpload(params: {
4
+ input: undefined;
5
+ ctx: Omit<EnsurePackageBundledContext, 'bus' | 'watcher'>;
6
+ }): Promise<SyncResult>;
4
7
  //# sourceMappingURL=syncUpload.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"syncUpload.d.ts","sourceRoot":"","sources":["../../src/apis/syncUpload.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,uBAAuB,CAAC;AASvD,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,wBAAwB,CAAC;AAGzD,wBAAsB,UAAU,CAC9B,MAAM,EAAE,SAAS,CACf,SAAS,EACP,SAAS,GACT,UAAU,GACV,UAAU,GACV,KAAK,GACL,YAAY,GACZ,SAAS,GACT,iBAAiB,GACjB,eAAe,GACf,mBAAmB,CACtB,GACA,OAAO,CAAC,UAAU,CAAC,CAmErB"}
1
+ {"version":3,"file":"syncUpload.d.ts","sourceRoot":"","sources":["../../src/apis/syncUpload.ts"],"names":[],"mappings":"AAAA,OAAO,EAAwB,KAAK,2BAA2B,EAAE,MAAM,2BAA2B,CAAC;AAUnG,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,wBAAwB,CAAC;AAIzD,wBAAsB,UAAU,CAAC,MAAM,EAAE;IACvC,KAAK,EAAE,SAAS,CAAC;IACjB,GAAG,EAAE,IAAI,CAAC,2BAA2B,EAAE,KAAK,GAAG,SAAS,CAAC,CAAC;CAC3D,GAAG,OAAO,CAAC,UAAU,CAAC,CAmEtB"}
@@ -9,6 +9,7 @@ import { getBundleLocation } from '../utilities/getBundleLocation.js';
9
9
  import { cp } from 'fs/promises';
10
10
  import objectHash from 'object-hash';
11
11
  import { ensureRemoteCacheEnabled } from '../utilities/ensureRemoteCacheEnabled.js';
12
+ // This is not actually a tRPC API, but it follows the same signature for now.
12
13
  export async function syncUpload(params) {
13
14
  const { ctx } = params;
14
15
  const { session, telemetryClient, taskRunner, remoteCacheClient: client } = ctx;
@@ -1 +1 @@
1
- {"version":3,"file":"syncUpload.js","sourceRoot":"","sources":["../../src/apis/syncUpload.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,oBAAoB,EAAE,MAAM,2BAA2B,CAAC;AACjE,OAAO,EAAE,yBAAyB,EAAE,MAAM,2BAA2B,CAAC;AAEtE,OAAO,EAAE,iCAAiC,EAAE,MAAM,mDAAmD,CAAC;AACtG,OAAO,EAAE,uCAAuC,EAAE,MAAM,yDAAyD,CAAC;AAClH,OAAO,EAAE,gBAAgB,EAAE,MAAM,kCAAkC,CAAC;AACpE,OAAO,EAAE,aAAa,EAAE,MAAM,4BAA4B,CAAC;AAC3D,OAAO,IAAI,MAAM,MAAM,CAAC;AACxB,OAAO,EAAE,iBAAiB,EAAE,MAAM,mCAAmC,CAAC;AACtE,OAAO,EAAE,EAAE,EAAE,MAAM,aAAa,CAAC;AACjC,OAAO,UAAU,MAAM,aAAa,CAAC;AAErC,OAAO,EAAE,wBAAwB,EAAE,MAAM,0CAA0C,CAAC;AAEpF,MAAM,CAAC,KAAK,UAAU,UAAU,CAC9B,MAWC;IAED,MAAM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A2F;QAC3F,MAAM,cAAc,GAAG,MAAM,OAAO,CAAC,UAAU,CAAC,OAAO,CAAC,CAAC;QAEzD,MAAM,MAAM,GAAG,iCAAiC,CAAC,cAAc,CAAC,CAAC;QACjE,IAAI,CAAC,aAAa,CAAC,MAAM,CAAC,CAAC;QAE3B,OAAO,MAAM,CAAC;IAChB,CAAC,CAAC,CAAC;AACL,CAAC;AAED,kGAAkG","sourcesContent":["import { ensurePackageBundled } from './ensurePackageBundled.js';\nimport { PerfMeasurementSyncUpload } from '../performance/markers.js';\nimport type { ApiParams } from '../types/ApiParams.js';\nimport { getRemoteCachePromiseResultCounts } from '../utilities/getRemoteCachePromiseResultCounts.js';\nimport { createRemoteCacheClientOperationOptions } from '../utilities/createRemoteCacheClientOperationOptions.js';\nimport { createUploadTask } from '../utilities/createUploadTask.js';\nimport { isStaticRoute } from '@ms-cloudpack/common-types';\nimport path from 'path';\nimport { getBundleLocation } from '../utilities/getBundleLocation.js';\nimport { cp } from 'fs/promises';\nimport objectHash from 'object-hash';\nimport type { SyncResult } from '../types/SyncResult.js';\nimport { ensureRemoteCacheEnabled } from '../utilities/ensureRemoteCacheEnabled.js';\n\nexport async function syncUpload(\n params: ApiParams<\n undefined,\n | 'session'\n | 'packages'\n | 'reporter'\n | 'bus'\n | 'taskRunner'\n | 'watcher'\n | 'telemetryClient'\n | 'packageHashes'\n | 'remoteCacheClient'\n >,\n): Promise<SyncResult> {\n const { ctx } = params;\n const { session, telemetryClient, taskRunner, remoteCacheClient: client } = ctx;\n const { config } = session;\n const { appPath } = config;\n const syncInternalPackages = config?.features?.syncInternalPackages ?? false;\n\n ensureRemoteCacheEnabled(config);\n\n if (!client) {\n throw new Error('Remote cache client is required to sync upload');\n }\n\n // Glob pattern for the files to upload.\n const globMatches = ['**/*', '!**/*-input.json', '!**/*-output.json'];\n\n return await telemetryClient.tracer.startActiveSpan(PerfMeasurementSyncUpload, async (span) => {\n const { name, version } = await ctx.packages.get(appPath);\n\n const { dependencies, result: bundleResult } = await ensurePackageBundled({\n input: {\n name,\n version,\n enqueueDependencies: true,\n },\n ctx,\n });\n\n const bundledPackages = [bundleResult, ...(await dependencies)];\n const packagesToUpload = await Promise.all(\n bundledPackages\n .filter((p) => p.inputPath && (p.isExternal || syncInternalPackages))\n .map((p) =>\n createRemoteCacheClientOperationOptions(\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- verified above that it's set\n { packagePath: p.inputPath! },\n ctx,\n ),\n ),\n );\n\n if (config.features?.enableCloudHosted) {\n const appOutputPath = (await getBundleLocation({ packagePath: appPath }, ctx)).path;\n const destinationFolder = path.join(appOutputPath, '__cloudpack');\n const routesPath = path.join(destinationFolder, 'routes');\n for (const route of config.routes ?? []) {\n if (isStaticRoute(route)) {\n const staticPath = path.resolve(appPath, route.staticPath);\n const routeHash = objectHash(route);\n const folderPath = path.join(routesPath, routeHash);\n await cp(staticPath, path.join(folderPath, route.staticPath), { recursive: true });\n }\n }\n }\n\n const uploads = packagesToUpload.map((pkg) =>\n taskRunner.add(createUploadTask({ client, options: { ...pkg, globMatches } })),\n );\n\n // Do not reject if there is a failure. Failed uploads will be logged in the task reporter.\n const promiseResults = await Promise.allSettled(uploads);\n\n const result = getRemoteCachePromiseResultCounts(promiseResults);\n span.setAttributes(result);\n\n return result;\n });\n}\n\n// This function doesn't have an attached procedure because it's never called via the TRPC server.\n"]}
1
+ {"version":3,"file":"syncUpload.js","sourceRoot":"","sources":["../../src/apis/syncUpload.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,oBAAoB,EAAoC,MAAM,2BAA2B,CAAC;AACnG,OAAO,EAAE,yBAAyB,EAAE,MAAM,2BAA2B,CAAC;AACtE,OAAO,EAAE,iCAAiC,EAAE,MAAM,mDAAmD,CAAC;AACtG,OAAO,EAAE,uCAAuC,EAAE,MAAM,yDAAyD,CAAC;AAClH,OAAO,EAAE,gBAAgB,EAAE,MAAM,kCAAkC,CAAC;AACpE,OAAO,EAAE,aAAa,EAAE,MAAM,4B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CAAC,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC,CAAC;gBACrF,CAAC;YACH,CAAC;QACH,CAAC;QAED,MAAM,OAAO,GAAG,gBAAgB,CAAC,GAAG,CAAC,CAAC,GAAG,EAAE,EAAE,CAC3C,UAAU,CAAC,GAAG,CAAC,gBAAgB,CAAC,EAAE,MAAM,EAAE,OAAO,EAAE,EAAE,GAAG,GAAG,EAAE,WAAW,EAAE,EAAE,CAAC,CAAC,CAC/E,CAAC;QAEF,2FAA2F;QAC3F,MAAM,cAAc,GAAG,MAAM,OAAO,CAAC,UAAU,CAAC,OAAO,CAAC,CAAC;QAEzD,MAAM,MAAM,GAAG,iCAAiC,CAAC,cAAc,CAAC,CAAC;QACjE,IAAI,CAAC,aAAa,CAAC,MAAM,CAAC,CAAC;QAE3B,OAAO,MAAM,CAAC;IAChB,CAAC,CAAC,CAAC;AACL,CAAC;AAED,kGAAkG","sourcesContent":["import { ensurePackageBundled, type EnsurePackageBundledContext } from './ensurePackageBundled.js';\nimport { PerfMeasurementSyncUpload } from '../performance/markers.js';\nimport { getRemoteCachePromiseResultCounts } from '../utilities/getRemoteCachePromiseResultCounts.js';\nimport { createRemoteCacheClientOperationOptions } from '../utilities/createRemoteCacheClientOperationOptions.js';\nimport { createUploadTask } from '../utilities/createUploadTask.js';\nimport { isStaticRoute } from '@ms-cloudpack/common-types';\nimport path from 'path';\nimport { getBundleLocation } from '../utilities/getBundleLocation.js';\nimport { cp } from 'fs/promises';\nimport objectHash from 'object-hash';\nimport type { SyncResult } from '../types/SyncResult.js';\nimport { ensureRemoteCacheEnabled } from '../utilities/ensureRemoteCacheEnabled.js';\n\n// This is not actually a tRPC API, but it follows the same signature for now.\nexport async function syncUpload(params: {\n input: undefined;\n ctx: Omit<EnsurePackageBundledContext, 'bus' | 'watcher'>;\n}): Promise<SyncResult> {\n const { ctx } = params;\n const { session, telemetryClient, taskRunner, remoteCacheClient: client } = ctx;\n const { config } = session;\n const { appPath } = config;\n const syncInternalPackages = config?.features?.syncInternalPackages ?? false;\n\n ensureRemoteCacheEnabled(config);\n\n if (!client) {\n throw new Error('Remote cache client is required to sync upload');\n }\n\n // Glob pattern for the files to upload.\n const globMatches = ['**/*', '!**/*-input.json', '!**/*-output.json'];\n\n return await telemetryClient.tracer.startActiveSpan(PerfMeasurementSyncUpload, async (span) => {\n const { name, version } = await ctx.packages.get(appPath);\n\n const { dependencies, result: bundleResult } = await ensurePackageBundled({\n input: {\n name,\n version,\n enqueueDependencies: true,\n },\n ctx,\n });\n\n const bundledPackages = [bundleResult, ...(await dependencies)];\n const packagesToUpload = await Promise.all(\n bundledPackages\n .filter((p) => p.inputPath && (p.isExternal || syncInternalPackages))\n .map((p) =>\n createRemoteCacheClientOperationOptions(\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- verified above that it's set\n { packagePath: p.inputPath! },\n ctx,\n ),\n ),\n );\n\n if (config.features?.enableCloudHosted) {\n const appOutputPath = (await getBundleLocation({ packagePath: appPath }, ctx)).path;\n const destinationFolder = path.join(appOutputPath, '__cloudpack');\n const routesPath = path.join(destinationFolder, 'routes');\n for (const route of config.routes ?? []) {\n if (isStaticRoute(route)) {\n const staticPath = path.resolve(appPath, route.staticPath);\n const routeHash = objectHash(route);\n const folderPath = path.join(routesPath, routeHash);\n await cp(staticPath, path.join(folderPath, route.staticPath), { recursive: true });\n }\n }\n }\n\n const uploads = packagesToUpload.map((pkg) =>\n taskRunner.add(createUploadTask({ client, options: { ...pkg, globMatches } })),\n );\n\n // Do not reject if there is a failure. Failed uploads will be logged in the task reporter.\n const promiseResults = await Promise.allSettled(uploads);\n\n const result = getRemoteCachePromiseResultCounts(promiseResults);\n span.setAttributes(result);\n\n return result;\n });\n}\n\n// This function doesn't have an attached procedure because it's never called via the TRPC server.\n"]}
@@ -0,0 +1,29 @@
1
+ import type { Context } from '../types/Context.js';
2
+ import type { CreateSessionOptions } from './createSession.js';
3
+ import type { LoginMethod } from '@ms-cloudpack/remote-cache';
4
+ export interface CreateApiContextOptions extends CreateSessionOptions, Pick<Context, 'reporter' | 'telemetryClient' | 'taskRunner'> {
5
+ /**
6
+ * Login method for the remote cache.
7
+ * If this isn't provided, `context.remoteCacheClient` will not be set.
8
+ */
9
+ remoteCacheClientLoginMethod?: LoginMethod;
10
+ }
11
+ /**
12
+ * Asynchronously initialize a partial `Context`, encapsulating async importing of certain modules
13
+ * to speed up boot time.
14
+ *
15
+ * This version skips some properties that are only needed for starting an app.
16
+ * For a full context, use `createApiContext`.
17
+ */
18
+ export declare function createPartialApiContext(options: CreateApiContextOptions): Promise<Omit<Context, 'bus' | 'watcher' | 'dispose'>>;
19
+ /**
20
+ * Asynchronously initialize a `Context`, encapsulating async importing of certain packages/modules
21
+ * to speed up boot time.
22
+ *
23
+ * When finished with the context, call `dispose` to clean up resources.
24
+ *
25
+ * NOTE: This version initializes the data bus and the file watcher, which are only needed for when
26
+ * starting an app. For other commands, use `createPartialApiContext`.
27
+ */
28
+ export declare function createApiContext(options: CreateApiContextOptions): Promise<Context>;
29
+ //# sourceMappingURL=createApiContext.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"createApiContext.d.ts","sourceRoot":"","sources":["../../src/common/createApiContext.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,qBAAqB,CAAC;AACnD,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,oBAAoB,CAAC;AAC/D,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,4BAA4B,CAAC;AAI9D,MAAM,WAAW,uBACf,SAAQ,oBAAoB,EAC1B,IAAI,CAAC,OAAO,EAAE,UAAU,GAAG,iBAAiB,GAAG,YAAY,CAAC;IAC9D;;;OAGG;IACH,4BAA4B,CAAC,EAAE,WAAW,CAAC;CAC5C;AAED;;;;;;GAMG;AACH,wBAAgB,uBAAuB,CACrC,OAAO,EAAE,uBAAuB,GAC/B,OAAO,CAAC,IAAI,CAAC,OAAO,EAAE,KAAK,GAAG,SAAS,GAAG,SAAS,CAAC,CAAC,CA4BvD;AAED;;;;;;;;GAQG;AACH,wBAAsB,gBAAgB,CAAC,OAAO,EAAE,uBAAuB,GAAG,OAAO,CAAC,OAAO,CAAC,CAqBzF"}
@@ -0,0 +1,62 @@
1
+ import { createRemoteCacheClient } from '../utilities/createRemoteCacheClient.js';
2
+ import { createPackageDefinitions } from '@ms-cloudpack/config';
3
+ /**
4
+ * Asynchronously initialize a partial `Context`, encapsulating async importing of certain modules
5
+ * to speed up boot time.
6
+ *
7
+ * This version skips some properties that are only needed for starting an app.
8
+ * For a full context, use `createApiContext`.
9
+ */
10
+ export function createPartialApiContext(options) {
11
+ const { reporter, taskRunner, telemetryClient, config, remoteCacheClientLoginMethod } = options;
12
+ return telemetryClient.tracer.startActiveSpan('CREATE_PARTIAL_API_CONTEXT', async () => {
13
+ // Start by creating the properties that are always used
14
+ const packages = createPackageDefinitions({ config });
15
+ const { createSession } = await import('./createSession.js');
16
+ const session = await createSession(options, { reporter, packages, telemetryClient });
17
+ const { PackageHashes } = await import('@ms-cloudpack/package-hashes');
18
+ const packageHashes = new PackageHashes({
19
+ cwd: config.appPath,
20
+ context: { config, packages, resolveMap: session.resolveMap },
21
+ });
22
+ let remoteCacheClient;
23
+ if (remoteCacheClientLoginMethod) {
24
+ remoteCacheClient = await createRemoteCacheClient({
25
+ input: {
26
+ loginMethod: remoteCacheClientLoginMethod,
27
+ },
28
+ ctx: { session, reporter, telemetryClient },
29
+ });
30
+ }
31
+ return { reporter, taskRunner, telemetryClient, packageHashes, packages, session, remoteCacheClient };
32
+ });
33
+ }
34
+ /**
35
+ * Asynchronously initialize a `Context`, encapsulating async importing of certain packages/modules
36
+ * to speed up boot time.
37
+ *
38
+ * When finished with the context, call `dispose` to clean up resources.
39
+ *
40
+ * NOTE: This version initializes the data bus and the file watcher, which are only needed for when
41
+ * starting an app. For other commands, use `createPartialApiContext`.
42
+ */
43
+ export async function createApiContext(options) {
44
+ return options.telemetryClient.tracer.startActiveSpan('CREATE_API_CONTEXT', async () => {
45
+ const context = await createPartialApiContext(options);
46
+ const { createWatcher } = await import('@ms-cloudpack/file-watcher');
47
+ const watcher = createWatcher({
48
+ type: context.session.config.features?.enableWatcherInFork ? 'fork' : 'default',
49
+ });
50
+ const { createDataBus } = await import('@ms-cloudpack/data-bus');
51
+ const bus = createDataBus();
52
+ // Without this line, the overlay won't work.
53
+ context.taskRunner.connectToBus(bus);
54
+ return {
55
+ ...context,
56
+ bus,
57
+ watcher,
58
+ dispose: () => watcher.dispose(),
59
+ };
60
+ });
61
+ }
62
+ //# sourceMappingURL=createApiContext.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"createApiContext.js","sourceRoot":"","sources":["../../src/common/createApiContext.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,uBAAuB,EAAE,MAAM,yCAAyC,CAAC;AAClF,OAAO,EAAE,wBAAwB,EAAE,MAAM,sBAAsB,CAAC;AAYhE;;;;;;GAMG;AACH,MAAM,UAAU,uBAAuB,CACrC,OAAgC;IAEhC,MAAM,EAAE,QAAQ,EAAE,UAAU,EAAE,eAAe,EAAE,MAAM,EAAE,4BAA4B,EAAE,GAAG,OAAO,CAAC;IAEhG,OAAO,eAAe,CAAC,MAAM,CAAC,eAAe,CAAC,4BAA4B,EAAE,KAAK,IAAI,EAAE;QACrF,wDAAwD;QACxD,MAAM,QAAQ,GAAG,wBAAwB,CAAC,EAAE,MAAM,EAAE,CAAC,CAAC;QAEtD,MAAM,EAAE,aAAa,EAAE,GAAG,MAAM,MAAM,CAAC,oBAAoB,CAAC,CAAC;QAC7D,MAAM,OAAO,GAAG,MAAM,aAAa,CAAC,OAAO,EAAE,EAAE,QAAQ,EAAE,QAAQ,EAAE,eAAe,EAAE,CAAC,CAAC;QAEtF,MAAM,EAAE,aAAa,EAAE,GAAG,MAAM,MAAM,CAAC,8BAA8B,CAAC,CAAC;QACvE,MAAM,aAAa,GAAG,IAAI,aAAa,CAAC;YACtC,GAAG,EAAE,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,OAAO;YACP,OAAO,EAAE,GAAG,EAAE,CAAC,OAAO,CAAC,OAAO,EAAE;SACjC,CAAC;IACJ,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import type { Context } from '../types/Context.js';\nimport type { CreateSessionOptions } from './createSession.js';\nimport type { LoginMethod } from '@ms-cloudpack/remote-cache';\nimport { createRemoteCacheClient } from '../utilities/createRemoteCacheClient.js';\nimport { createPackageDefinitions } from '@ms-cloudpack/config';\n\nexport interface CreateApiContextOptions\n extends CreateSessionOptions,\n Pick<Context, 'reporter' | 'telemetryClient' | 'taskRunner'> {\n /**\n * Login method for the remote cache.\n * If this isn't provided, `context.remoteCacheClient` will not be set.\n */\n remoteCacheClientLoginMethod?: LoginMethod;\n}\n\n/**\n * Asynchronously initialize a partial `Context`, encapsulating async importing of certain modules\n * to speed up boot time.\n *\n * This version skips some properties that are only needed for starting an app.\n * For a full context, use `createApiContext`.\n */\nexport function createPartialApiContext(\n options: CreateApiContextOptions,\n): Promise<Omit<Context, 'bus' | 'watcher' | 'dispose'>> {\n const { reporter, taskRunner, telemetryClient, config, remoteCacheClientLoginMethod } = options;\n\n return telemetryClient.tracer.startActiveSpan('CREATE_PARTIAL_API_CONTEXT', async () => {\n // Start by creating the properties that are always used\n const packages = createPackageDefinitions({ config });\n\n const { createSession } = await import('./createSession.js');\n const session = await createSession(options, { reporter, packages, telemetryClient });\n\n const { PackageHashes } = await import('@ms-cloudpack/package-hashes');\n const packageHashes = new PackageHashes({\n cwd: config.appPath,\n context: { config, packages, resolveMap: session.resolveMap },\n });\n\n let remoteCacheClient: Context['remoteCacheClient'] | undefined;\n if (remoteCacheClientLoginMethod) {\n remoteCacheClient = await createRemoteCacheClient({\n input: {\n loginMethod: remoteCacheClientLoginMethod,\n },\n ctx: { session, reporter, telemetryClient },\n });\n }\n\n return { reporter, taskRunner, telemetryClient, packageHashes, packages, session, remoteCacheClient };\n });\n}\n\n/**\n * Asynchronously initialize a `Context`, encapsulating async importing of certain packages/modules\n * to speed up boot time.\n *\n * When finished with the context, call `dispose` to clean up resources.\n *\n * NOTE: This version initializes the data bus and the file watcher, which are only needed for when\n * starting an app. For other commands, use `createPartialApiContext`.\n */\nexport async function createApiContext(options: CreateApiContextOptions): Promise<Context> {\n return options.telemetryClient.tracer.startActiveSpan('CREATE_API_CONTEXT', async () => {\n const context = await createPartialApiContext(options);\n\n const { createWatcher } = await import('@ms-cloudpack/file-watcher');\n const watcher = createWatcher({\n type: context.session.config.features?.enableWatcherInFork ? 'fork' : 'default',\n });\n\n const { createDataBus } = await import('@ms-cloudpack/data-bus');\n const bus = createDataBus();\n // Without this line, the overlay won't work.\n context.taskRunner.connectToBus(bus);\n\n return {\n ...context,\n bus,\n watcher,\n dispose: () => watcher.dispose(),\n };\n });\n}\n"]}
package/lib/index.d.ts CHANGED
@@ -6,7 +6,6 @@ export type { Task } from './types/Task.js';
6
6
  export type { TaskDescription } from './types/TaskDescription.js';
7
7
  export type { TaskEndDescription } from './types/TaskEndDescription.js';
8
8
  export type { TaskMessage } from './types/TaskMessage.js';
9
- export type { TaskOptions } from './types/TaskOptions.js';
10
9
  export type { TaskStartDescription } from './types/TaskStartDescription.js';
11
10
  export type { EnsurePackageBundledContext, EnsurePackageBundledResult } from './apis/ensurePackageBundled.js';
12
11
  export { TaskRunner } from './utilities/TaskRunner.js';
@@ -16,7 +15,7 @@ export { createCloudpackServer, type CloudpackServer } from './trpc/createCloudp
16
15
  export { getActiveSessionsPath } from './utilities/getActiveSessionsPath.js';
17
16
  export { getConsumedDependencies } from './utilities/getConsumedDependencies.js';
18
17
  export { getConsumedPaths } from './utilities/getConsumedPaths.js';
19
- export { createPartialApiContext, type LazyApiContextOptions } from './common/createPartialApiContext.js';
18
+ export { createApiContext, createPartialApiContext, type CreateApiContextOptions } from './common/createApiContext.js';
20
19
  export { addPackageOverride } from './apis/addPackageOverride.js';
21
20
  export { ensurePackageBundled } from './apis/ensurePackageBundled.js';
22
21
  export { syncDownload } from './apis/syncDownload.js';
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,EAAE,MAAM,iCAAiC,CAAC;AAGnE,OAAO,EAAE,gBAAgB,EAAE,uBAAuB,EAAE,KAAK,uBAAuB,EAAE,MAAM,8BAA8B,CAAC;AAGvH,OAAO,EAAE,kBAAkB,EAAE,MAAM,8BAA8B,CAAC;AAClE,OAAO,EAAE,oBAAoB,EAAE,MAAM,gCAAgC,CAAC;AACtE,OAAO,EAAE,YAAY,EAAE,MAAM,wBAAwB,CAAC;AACtD,OAAO,EAAE,UAAU,EAAE,MAAM,sBAAsB,CAAC;AAClD,YAAY,EAAE,UAAU,EAAE,MAAM,uBAAuB,CAAC"}
package/lib/index.js CHANGED
@@ -6,7 +6,7 @@ export { getActiveSessionsPath } from './utilities/getActiveSessionsPath.js';
6
6
  export { getConsumedDependencies } from './utilities/getConsumedDependencies.js';
7
7
  export { getConsumedPaths } from './utilities/getConsumedPaths.js';
8
8
  // Utilities
9
- export { createPartialApiContext } from './common/createPartialApiContext.js';
9
+ export { createApiContext, createPartialApiContext } from './common/createApiContext.js';
10
10
  // API methods directly used outside this package
11
11
  export { addPackageOverride } from './apis/addPackageOverride.js';
12
12
  export { ensurePackageBundled } from './apis/ensurePackageBundled.js';
package/lib/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAYA,OAAO,EAAE,UAAU,EAAE,MAAM,2BAA2B,CAAC;AACvD,OAAO,EAAE,gBAAgB,EAAE,MAAM,sBAAsB,CAAC;AACxD,OAAO,EAAE,qBAAqB,EAAwB,MAAM,iCAAiC,CAAC;AAC9F,OAAO,EAAE,qBAAqB,EAAwB,MAAM,iCAAiC,CAAC;AAC9F,OAAO,EAAE,qBAAqB,EAAE,MAAM,sCAAsC,CAAC;AAC7E,OAAO,EAAE,uBAAuB,EAAE,MAAM,wCAAwC,CAAC;AACjF,OAAO,EAAE,gBAAgB,EAAE,MAAM,iCAAiC,CAAC;AAEnE,YAAY;AACZ,OAAO,EAAE,uBAAuB,EAA8B,MAAM,qCAAqC,CAAC;AAE1G,iDAAiD;AACjD,OAAO,EAAE,kBAAkB,EAAE,MAAM,8BAA8B,CAAC;AAClE,OAAO,EAAE,oBAAoB,EAAE,MAAM,gCAAgC,CAAC;AACtE,OAAO,EAAE,YAAY,EAAE,MAAM,wBAAwB,CAAC;AACtD,OAAO,EAAE,UAAU,EAAE,MAAM,sBAAsB,CAAC","sourcesContent":["export type { Context, PartialContext } from './types/Context.js';\nexport type { BundleInfo, BundleEntryInfo, BundleEntryConsumes } from './types/BundleInfo.js';\nexport type { Session } from '@ms-cloudpack/common-types';\nexport type { TaskStats } from './types/TaskStats.js';\nexport type { Task } from './types/Task.js';\nexport type { TaskDescription } from './types/TaskDescription.js';\nexport type { TaskEndDescription } from './types/TaskEndDescription.js';\nexport type { TaskMessage } from './types/TaskMessage.js';\nexport type { TaskOptions } from './types/TaskOptions.js';\nexport type { TaskStartDescription } from './types/TaskStartDescription.js';\nexport type { EnsurePackageBundledContext, EnsurePackageBundledResult } from './apis/ensurePackageBundled.js';\n\nexport { TaskRunner } from './utilities/TaskRunner.js';\nexport { errorEntrySource } from './data/busSources.js';\nexport { createCloudpackClient, type CloudpackClient } from './trpc/createCloudpackClient.js';\nexport { createCloudpackServer, type CloudpackServer } from './trpc/createCloudpackServer.js';\nexport { getActiveSessionsPath } from './utilities/getActiveSessionsPath.js';\nexport { getConsumedDependencies } from './utilities/getConsumedDependencies.js';\nexport { getConsumedPaths } from './utilities/getConsumedPaths.js';\n\n// Utilities\nexport { createPartialApiContext, type LazyApiContextOptions } from './common/createPartialApiContext.js';\n\n// API methods directly used outside this package\nexport { addPackageOverride } from './apis/addPackageOverride.js';\nexport { ensurePackageBundled } from './apis/ensurePackageBundled.js';\nexport { syncDownload } from './apis/syncDownload.js';\nexport { syncUpload } from './apis/syncUpload.js';\nexport type { SyncResult } from './types/SyncResult.js';\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAWA,OAAO,EAAE,UAAU,EAAE,MAAM,2BAA2B,CAAC;AACvD,OAAO,EAAE,gBAAgB,EAAE,MAAM,sBAAsB,CAAC;AACxD,OAAO,EAAE,qBAAqB,EAAwB,MAAM,iCAAiC,CAAC;AAC9F,OAAO,EAAE,qBAAqB,EAAwB,MAAM,iCAAiC,CAAC;AAC9F,OAAO,EAAE,qBAAqB,EAAE,MAAM,sCAAsC,CAAC;AAC7E,OAAO,EAAE,uBAAuB,EAAE,MAAM,wCAAwC,CAAC;AACjF,OAAO,EAAE,gBAAgB,EAAE,MAAM,iCAAiC,CAAC;AAEnE,YAAY;AACZ,OAAO,EAAE,gBAAgB,EAAE,uBAAuB,EAAgC,MAAM,8BAA8B,CAAC;AAEvH,iDAAiD;AACjD,OAAO,EAAE,kBAAkB,EAAE,MAAM,8BAA8B,CAAC;AAClE,OAAO,EAAE,oBAAoB,EAAE,MAAM,gCAAgC,CAAC;AACtE,OAAO,EAAE,YAAY,EAAE,MAAM,wBAAwB,CAAC;AACtD,OAAO,EAAE,UAAU,EAAE,MAAM,sBAAsB,CAAC","sourcesContent":["export type { Context, PartialContext } from './types/Context.js';\nexport type { BundleInfo, BundleEntryInfo, BundleEntryConsumes } from './types/BundleInfo.js';\nexport type { Session } from '@ms-cloudpack/common-types';\nexport type { TaskStats } from './types/TaskStats.js';\nexport type { Task } from './types/Task.js';\nexport type { TaskDescription } from './types/TaskDescription.js';\nexport type { TaskEndDescription } from './types/TaskEndDescription.js';\nexport type { TaskMessage } from './types/TaskMessage.js';\nexport type { TaskStartDescription } from './types/TaskStartDescription.js';\nexport type { EnsurePackageBundledContext, EnsurePackageBundledResult } from './apis/ensurePackageBundled.js';\n\nexport { TaskRunner } from './utilities/TaskRunner.js';\nexport { errorEntrySource } from './data/busSources.js';\nexport { createCloudpackClient, type CloudpackClient } from './trpc/createCloudpackClient.js';\nexport { createCloudpackServer, type CloudpackServer } from './trpc/createCloudpackServer.js';\nexport { getActiveSessionsPath } from './utilities/getActiveSessionsPath.js';\nexport { getConsumedDependencies } from './utilities/getConsumedDependencies.js';\nexport { getConsumedPaths } from './utilities/getConsumedPaths.js';\n\n// Utilities\nexport { createApiContext, createPartialApiContext, type CreateApiContextOptions } from './common/createApiContext.js';\n\n// API methods directly used outside this package\nexport { addPackageOverride } from './apis/addPackageOverride.js';\nexport { ensurePackageBundled } from './apis/ensurePackageBundled.js';\nexport { syncDownload } from './apis/syncDownload.js';\nexport { syncUpload } from './apis/syncUpload.js';\nexport type { SyncResult } from './types/SyncResult.js';\n"]}
@@ -5,19 +5,21 @@ import type { TaskReporter } from '@ms-cloudpack/task-reporter';
5
5
  import type { TelemetryClient } from '@ms-cloudpack/telemetry';
6
6
  import type { TaskRunner } from '../utilities/TaskRunner.js';
7
7
  import type { RemoteCacheClient } from '@ms-cloudpack/remote-cache';
8
- /** Context for Cloudpack API server procedures. */
8
+ /** Context for Cloudpack API server procedures and other APIs. */
9
9
  export interface Context {
10
10
  session: Session;
11
11
  /** Data bus for sending notifications to the client. */
12
12
  bus: DataBus;
13
13
  telemetryClient: TelemetryClient;
14
14
  reporter: TaskReporter;
15
- watcher: Watcher;
15
+ /** Only used by `ensurePackageBundled`. */
16
+ watcher?: Watcher;
16
17
  packages: PackageDefinitionsCache;
17
18
  taskRunner: TaskRunner;
18
19
  packageHashes: PackageHashesCache;
19
20
  remoteCacheClient?: RemoteCacheClient;
20
- dispose(): void | Promise<void>;
21
+ /** Only set if `watcher` is initialized. */
22
+ dispose?: () => void | Promise<void>;
21
23
  }
22
24
  /**
23
25
  * Helper for partial context and session objects.
@@ -1 +1 @@
1
- {"version":3,"file":"Context.d.ts","sourceRoot":"","sources":["../../src/types/Context.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,uBAAuB,EAAE,kBAAkB,EAAE,OAAO,EAAE,MAAM,4BAA4B,CAAC;AACvG,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,wBAAwB,CAAC;AACtD,OAAO,KAAK,EAAE,OAA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,6BAA6B,CAAC;AAChE,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,yBAAyB,CAAC;AAC/D,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,4BAA4B,CAAC;AAC7D,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,4BAA4B,CAAC;AAEpE,kEAAkE;AAClE,MAAM,WAAW,OAAO;IACtB,OAAO,EAAE,OAAO,CAAC;IACjB,wDAAwD;IACxD,GAAG,EAAE,OAAO,CAAC;IACb,eAAe,EAAE,eAAe,CAAC;IACjC,QAAQ,EAAE,YAAY,CAAC;IACvB,2CAA2C;IAE3C,OAAO,CAAC,EAAE,OAAO,CAAC;IAClB,QAAQ,EAAE,uBAAuB,CAAC;IAClC,UAAU,EAAE,UAAU,CAAC;IACvB,aAAa,EAAE,kBAAkB,CAAC;IAClC,iBAAiB,CAAC,EAAE,iBAAiB,CAAC;IACtC,4CAA4C;IAC5C,OAAO,CAAC,EAAE,MAAM,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;CACtC;AAED;;;;GAIG;AACH,MAAM,MAAM,cAAc,CACxB,YAAY,SAAS,MAAM,IAAI,CAAC,OAAO,EAAE,SAAS,CAAC,EACnD,YAAY,SAAS,MAAM,OAAO,IAChC,IAAI,CAAC,OAAO,EAAE,YAAY,CAAC,GAAG;IAChC,OAAO,EAAE,IAAI,CAAC,OAAO,EAAE,YAAY,CAAC,CAAC;CACtC,CAAC"}
@@ -1 +1 @@
1
- {"version":3,"file":"Context.js","sourceRoot":"","sources":["../../src/types/Context.ts"],"names":[],"mappings":"","sourcesContent":["import type { PackageDefinitionsCache, PackageHashesCache, Session } from '@ms-cloudpack/common-types';\nimport type { DataBus } from '@ms-cloudpack/data-bus';\nimport type { Watcher } from '@ms-cloudpack/file-watcher';\nimport type { TaskReporter } from '@ms-cloudpack/task-reporter';\nimport type { TelemetryClient } from '@ms-cloudpack/telemetry';\nimport type { TaskRunner } from '../utilities/TaskRunner.js';\nimport type { RemoteCacheClient } from '@ms-cloudpack/remote-cache';\n\n/** Context for Cloudpack API server procedures. */\nexport interface Context {\n session: Session;\n /** Data bus for sending notifications to the client. */\n bus: DataBus;\n telemetryClient: TelemetryClient;\n reporter: TaskReporter;\n watcher: Watcher;\n packages: PackageDefinitionsCache;\n taskRunner: TaskRunner;\n packageHashes: PackageHashesCache;\n remoteCacheClient?: RemoteCacheClient;\n // This typically returns a promise. Allow a non-promise for convenience for tests.\n dispose(): void | Promise<void>;\n}\n\n/**\n * Helper for partial context and session objects.\n * First param is context keys and second is session keys.\n * (This can make it easier to tell which properties are actually used where.)\n */\nexport type PartialContext<\n TContextKeys extends keyof Omit<Context, 'session'>,\n TSessionKeys extends keyof Session,\n> = Pick<Context, TContextKeys> & {\n session: Pick<Session, TSessionKeys>;\n};\n"]}
1
+ {"version":3,"file":"Context.js","sourceRoot":"","sources":["../../src/types/Context.ts"],"names":[],"mappings":"","sourcesContent":["import type { PackageDefinitionsCache, PackageHashesCache, Session } from '@ms-cloudpack/common-types';\nimport type { DataBus } from '@ms-cloudpack/data-bus';\nimport type { Watcher } from '@ms-cloudpack/file-watcher';\nimport type { TaskReporter } from '@ms-cloudpack/task-reporter';\nimport type { TelemetryClient } from '@ms-cloudpack/telemetry';\nimport type { TaskRunner } from '../utilities/TaskRunner.js';\nimport type { RemoteCacheClient } from '@ms-cloudpack/remote-cache';\n\n/** Context for Cloudpack API server procedures and other APIs. */\nexport interface Context {\n session: Session;\n /** Data bus for sending notifications to the client. */\n bus: DataBus;\n telemetryClient: TelemetryClient;\n reporter: TaskReporter;\n /** Only used by `ensurePackageBundled`. */\n // TODO: split to a separate type for non-tRPC APIs\n watcher?: Watcher;\n packages: PackageDefinitionsCache;\n taskRunner: TaskRunner;\n packageHashes: PackageHashesCache;\n remoteCacheClient?: RemoteCacheClient;\n /** Only set if `watcher` is initialized. */\n dispose?: () => void | Promise<void>;\n}\n\n/**\n * Helper for partial context and session objects.\n * First param is context keys and second is session keys.\n * (This can make it easier to tell which properties are actually used where.)\n */\nexport type PartialContext<\n TContextKeys extends keyof Omit<Context, 'session'>,\n TSessionKeys extends keyof Session,\n> = Pick<Context, TContextKeys> & {\n session: Pick<Session, TSessionKeys>;\n};\n"]}
@@ -1,26 +1,37 @@
1
- import type { TaskOptions } from '../types/TaskOptions.js';
2
1
  import type { Task } from '../types/Task.js';
3
- import type { TaskRunnerContext } from '../types/TaskRunnerContext.js';
2
+ import type { DataBus } from '@ms-cloudpack/data-bus';
4
3
  /**
5
- * TaskRunner class manages the state of Tasks.
6
- * This class is to be called by the api server.
4
+ * TaskRunner tracks the status of tasks, manages concurrency, allows reusing task results,
5
+ * and sends notifications about task status to the data bus (currently just used for `start`).
6
+ *
7
+ * NOTE: To enable data bus notifications, you must call `connectToBus()`.
8
+ * `createApiContext` does this with the `taskRunner` passed in.
7
9
  */
8
10
  export declare class TaskRunner {
9
- private _context;
11
+ private _bus;
10
12
  private _queue;
11
13
  private _taskStats;
12
14
  private _pendingTasks;
13
15
  private _completedTasks;
14
16
  private _requiresRerun;
15
17
  private _prevTasks;
16
- constructor(context?: TaskRunnerContext);
18
+ constructor();
17
19
  /**
18
- * The add method enqueues a Task and returns its Promise.
19
- * If a Task with the same id has already been processed,
20
- * it returns either the result or the promise.
21
- * Rerun flag forces the Task to be run again.
20
+ * Connects the TaskRunner to the data bus. Tasks will still run without this, but they won't
21
+ * send any notifications to a client (which only matters if a client is listening, e.g.
22
+ * the browser while running `start`).
22
23
  */
23
- add<TReturn>(task: Task<TReturn>, options?: TaskOptions): Promise<TReturn>;
24
+ connectToBus(bus: DataBus): void;
25
+ /**
26
+ * Enqueue a task and return its result promise.
27
+ *
28
+ * If a task with the same `id` was already added, it returns either the previous result
29
+ * (if completed) or the promise (if pending). Pass `options.rerun` to force re-running.
30
+ */
31
+ add<TReturn>(task: Task<TReturn>, options?: {
32
+ rerun?: boolean;
33
+ priority?: number;
34
+ }): Promise<TReturn>;
24
35
  /**
25
36
  * The remove method disposes a task if available
26
37
  * and then removes it from the TaskRunner.
@@ -1 +1 @@
1
- {"version":3,"file":"TaskRunner.d.ts","sourceRoot":"","sources":["../../src/utilities/TaskRunner.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,yBAAyB,CAAC;AAC3D,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,kBAAkB,CAAC;AAC7C,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,+BAA+B,CAAC;AAOvE;;;GAGG;AACH,qBAAa,UAAU;IAGrB,OAAO,CAAC,QAAQ,CAAgC;IAChD,OAAO,CAAC,MAAM,CAAS;IACvB,OAAO,CAAC,UAAU,CAAY;IAE9B,OAAO,CAAC,aAAa,CAA4B;IAEjD,OAAO,CAAC,eAAe,CAAmB;IAC1C,OAAO,CAAC,cAAc,CAAc;IAEpC,OAAO,CAAC,UAAU,CAAyB;gBAE/B,OAAO,CAAC,EAAE,iBAAiB;IAevC;;;;;OAKG;IACH,GAAG,CAAC,OAAO,EAAE,IAAI,EAAE,IAAI,CAAC,OAAO,CAAC,EAAE,OAAO,CAAC,EAAE,WAAW,GAAG,OAAO,CAAC,OAAO,CAAC;IAmE1E;;;;;;;;OAQG;IACH,MAAM,CAAC,EAAE,EAAE,MAAM,GAAG,IAAI;IAkBxB;;OAEG;IACH,KAAK,IAAI,IAAI;IAYb,2CAA2C;IAC3C,MAAM,IAAI,IAAI;IAId,sDAAsD;IACtD,MAAM,IAAI,IAAI;IAId;;OAEG;IACH,OAAO,CAAC,YAAY;IAmCpB;;OAEG;IACH,OAAO,CAAC,UAAU;CA6BnB"}
1
+ {"version":3,"file":"TaskRunner.d.ts","sourceRoot":"","sources":["../../src/utilities/TaskRunner.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,kBAAkB,CAAC;AAM7C,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,wBAAwB,CAAC;AAEtD;;;;;;GAMG;AACH,qBAAa,UAAU;IACrB,OAAO,CAAC,IAAI,CAAsB;IAClC,OAAO,CAAC,MAAM,CAAS;IACvB,OAAO,CAAC,UAAU,CAAY;IAC9B,OAAO,CAAC,aAAa,CAAgC;IACrD,OAAO,CAAC,eAAe,CAAuB;IAC9C,OAAO,CAAC,cAAc,CAAc;IAEpC,OAAO,CAAC,UAAU,CAAyB;;IAW3C;;;;OAIG;IACI,YAAY,CAAC,GAAG,EAAE,OAAO,GAAG,IAAI;IAIvC;;;;;OAKG;IACH,GAAG,CAAC,OAAO,EACT,IAAI,EAAE,IAAI,CAAC,OAAO,CAAC,EACnB,OAAO,CAAC,EAAE;QACR,KAAK,CAAC,EAAE,OAAO,CAAC;QAChB,QAAQ,CAAC,EAAE,MAAM,CAAC;KACnB,GACA,OAAO,CAAC,OAAO,CAAC;IAiEnB;;;;;;;;OAQG;IACH,MAAM,CAAC,EAAE,EAAE,MAAM,GAAG,IAAI;IAgBxB;;OAEG;IACH,KAAK,IAAI,IAAI;IASb,2CAA2C;IAC3C,MAAM,IAAI,IAAI;IAId,sDAAsD;IACtD,MAAM,IAAI,IAAI;IAId;;OAEG;IACH,OAAO,CAAC,YAAY;IAoCpB;;OAEG;IACH,OAAO,CAAC,UAAU;CA8BnB"}
@@ -2,33 +2,38 @@ import PQueue from 'p-queue';
2
2
  import { getDefaultTaskStats } from './getDefaultTaskStats.js';
3
3
  import { taskListSource, taskStatsSource } from '../index.browser.js';
4
4
  /**
5
- * TaskRunner class manages the state of Tasks.
6
- * This class is to be called by the api server.
5
+ * TaskRunner tracks the status of tasks, manages concurrency, allows reusing task results,
6
+ * and sends notifications about task status to the data bus (currently just used for `start`).
7
+ *
8
+ * NOTE: To enable data bus notifications, you must call `connectToBus()`.
9
+ * `createApiContext` does this with the `taskRunner` passed in.
7
10
  */
8
11
  export class TaskRunner {
9
- constructor(context) {
10
- this._context = context;
12
+ constructor() {
11
13
  this._queue = new PQueue({ concurrency: 10 });
12
14
  this._taskStats = getDefaultTaskStats();
13
15
  this._pendingTasks = new Map();
14
16
  this._completedTasks = new Map();
15
17
  this._requiresRerun = new Set();
16
18
  this._prevTasks = new Map();
17
- if (this._context) {
18
- const { bus, session } = this._context;
19
- bus.publish([session.id, 'status'], this._taskStats);
20
- }
21
19
  }
22
20
  /**
23
- * The add method enqueues a Task and returns its Promise.
24
- * If a Task with the same id has already been processed,
25
- * it returns either the result or the promise.
26
- * Rerun flag forces the Task to be run again.
21
+ * Connects the TaskRunner to the data bus. Tasks will still run without this, but they won't
22
+ * send any notifications to a client (which only matters if a client is listening, e.g.
23
+ * the browser while running `start`).
24
+ */
25
+ connectToBus(bus) {
26
+ this._bus = bus;
27
+ }
28
+ /**
29
+ * Enqueue a task and return its result promise.
30
+ *
31
+ * If a task with the same `id` was already added, it returns either the previous result
32
+ * (if completed) or the promise (if pending). Pass `options.rerun` to force re-running.
27
33
  */
28
34
  add(task, options) {
29
35
  const { name, id, execute } = task;
30
- const { rerun, watch, priority } = options || {};
31
- watch?.();
36
+ const { rerun, priority } = options || {};
32
37
  if (!this._prevTasks.get(id)) {
33
38
  this._prevTasks.set(id, task);
34
39
  }
@@ -98,8 +103,6 @@ export class TaskRunner {
98
103
  if (this._pendingTasks.has(id)) {
99
104
  this._pendingTasks.delete(id);
100
105
  this._taskStats.remainingTasks = this._pendingTasks.size;
101
- const { bus, session } = this._context || {};
102
- bus && session && bus.publish([session.id, 'status'], this._taskStats);
103
106
  }
104
107
  this._completedTasks.delete(id);
105
108
  }
@@ -108,11 +111,7 @@ export class TaskRunner {
108
111
  */
109
112
  clear() {
110
113
  this._taskStats = getDefaultTaskStats();
111
- if (this._context) {
112
- const { bus, session } = this._context;
113
- bus.publish([session.id, 'status'], this._taskStats);
114
- bus.publish(taskListSource, { tasks: [] });
115
- }
114
+ this._bus?.publish(taskListSource, { tasks: [] });
116
115
  for (const id of this._prevTasks.keys()) {
117
116
  this.remove(id);
118
117
  }
@@ -129,9 +128,9 @@ export class TaskRunner {
129
128
  * Internal method to report the start of a task to the bus.
130
129
  */
131
130
  _reportStart(id, description) {
132
- if (!this._context)
131
+ if (!this._bus)
133
132
  return;
134
- const { bus } = this._context;
133
+ const bus = this._bus;
135
134
  const { tasks } = bus.getData(taskListSource.path) || { tasks: [] };
136
135
  const index = tasks.findIndex((t) => t.id === id);
137
136
  const previousDescription = tasks[index];
@@ -163,9 +162,9 @@ export class TaskRunner {
163
162
  * Internal method to report the end of a task to the bus.
164
163
  */
165
164
  _reportEnd(id, description) {
166
- if (!this._context)
165
+ if (!this._bus)
167
166
  return;
168
- const { bus } = this._context;
167
+ const bus = this._bus;
169
168
  const { tasks } = bus.getData(taskListSource.path) || { tasks: [] };
170
169
  const index = tasks.findIndex((t) => t.id === id);
171
170
  const previousDescription = tasks[index];
@@ -1 +1 @@
1
- {"version":3,"file":"TaskRunner.js","sourceRoot":"","sources":["../../src/utilities/TaskRunner.ts"],"names":[],"mappings":"AAOA,OAAO,MAAM,MAAM,SAAS,CAAC;AAC7B,OAAO,EAAE,mBAAmB,EAAE,MAAM,0BAA0B,CAAC;AAC/D,OAAO,EAAE,cAAc,EAAE,eAAe,EAAwB,MAAM,qBAAqB,CAAC;AAE5F;;;GAGG;AACH,MAAM,OAAO,UAAU;IAcrB,YAAY,OAA2B;QACrC,IAAI,CAAC,QAAQ,GAAG,OAAO,CAAC;QACxB,IAAI,CAAC,MAAM,GAAG,IAAI,MAAM,CAAC,EAAE,WAAW,EAAE,EAAE,EAAE,CAAC,CAAC;QAC9C,IAAI,CAAC,UAAU,GAAG,mBAAmB,EAAE,CAAC;QACxC,IAAI,CAAC,aAAa,GAAG,IAAI,GAAG,EAAE,CAAC;QAC/B,IAAI,CAAC,eAAe,GAAG,IAAI,GAAG,EAAE,CAAC;QACjC,IAAI,CAAC,cAAc,GAAG,IAAI,GAAG,EAAE,CAAC;QAChC,IAAI,CAAC,UAAU,GAAG,IAAI,GAAG,EAAE,CAAC;QAE5B,IAAI,IAAI,CAAC,QAAQ,EAAE,CAAC;YAClB,MAAM,EAAE,GAAG,E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AAM,EAAE,MAAM,IAAI,CAAC,CAAC;YAChE,IAAI,CAAC,UAAU,CAAC,aAAa,IAAI,WAAW,EAAE,QAAQ,EAAE,MAAM,IAAI,CAAC,CAAC;YAEpE,KAAK,CAAC,KAAK,CAAC,GAAG;gBACb,GAAG,mBAAmB;gBACtB,GAAG,WAAW;gBACd,MAAM,EAAE,UAAU;gBAClB,oBAAoB,EAAE,GAAG,GAAG,mBAAmB,CAAC,SAAS;gBACzD,WAAW,EAAE,GAAG;aACjB,CAAC;YAEF,IAAI,IAAI,CAAC,UAAU,CAAC,cAAc,KAAK,CAAC,EAAE,CAAC;gBACzC,IAAI,CAAC,UAAU,CAAC,MAAM,GAAG,MAAM,CAAC;YAClC,CAAC;YAED,GAAG,CAAC,OAAO,CAAC,eAAe,EAAE,IAAI,CAAC,UAAU,CAAC,CAAC;YAC9C,GAAG,CAAC,OAAO,CAAC,cAAc,EAAE,EAAE,KAAK,EAAE,CAAC,CAAC;QACzC,CAAC;IACH,CAAC;CACF","sourcesContent":["import type { TaskStartDescription } from '../types/TaskStartDescription.js';\nimport type { TaskEndDescription } from '../types/TaskEndDescription.js';\nimport type { TaskOptions } from '../types/TaskOptions.js';\nimport type { Task } from '../types/Task.js';\nimport type { TaskRunnerContext } from '../types/TaskRunnerContext.js';\nimport type { TaskStats } from '../types/TaskStats.js';\nimport type { TaskList } from '../types/TaskList.js';\nimport PQueue from 'p-queue';\nimport { getDefaultTaskStats } from './getDefaultTaskStats.js';\nimport { taskListSource, taskStatsSource, type TaskDescription } from '../index.browser.js';\n\n/**\n * TaskRunner class manages the state of Tasks.\n * This class is to be called by the api server.\n */\nexport class TaskRunner {\n // Context is used to publish task status to the bus,\n // so it is optional, as it is not needed during init or testing.\n private _context: TaskRunnerContext | undefined;\n private _queue: PQueue;\n private _taskStats: TaskStats;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n private _pendingTasks: Map<string, Promise<any>>;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n private _completedTasks: Map<string, any>;\n private _requiresRerun: Set<string>;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n private _prevTasks: Map<string, Task<any>>;\n\n constructor(context?: TaskRunnerContext) {\n this._context = context;\n this._queue = new PQueue({ concurrency: 10 });\n this._taskStats = getDefaultTaskStats();\n this._pendingTasks = new Map();\n this._completedTasks = new Map();\n this._requiresRerun = new Set();\n this._prevTasks = new Map();\n\n if (this._context) {\n const { bus, session } = this._context;\n bus.publish([session.id, 'status'], this._taskStats);\n }\n }\n\n /**\n * The add method enqueues a Task and returns its Promise.\n * If a Task with the same id has already been processed,\n * it returns either the result or the promise.\n * Rerun flag forces the Task to be run again.\n */\n add<TReturn>(task: Task<TReturn>, options?: TaskOptions): Promise<TReturn> {\n const { name, id, execute } = task;\n const { rerun, watch, priority } = options || {};\n\n watch?.();\n\n if (!this._prevTasks.get(id)) {\n this._prevTasks.set(id, task);\n }\n\n // Check if we are already completed the task with that id.\n const action = this._completedTasks.get(id) as TReturn | undefined;\n if (action !== undefined && !rerun) {\n return Promise.resolve(action);\n }\n\n // Check if we are already running the task with that id.\n const pending = this._pendingTasks.get(id) as Promise<TReturn> | undefined;\n if (pending !== undefined) {\n if (rerun) {\n this._requiresRerun.add(id);\n }\n return pending;\n }\n\n const resultPromise: Promise<TReturn> = (async () => {\n let taskResult: TReturn | undefined;\n\n do {\n // Delete from rerun list (if present).\n this._requiresRerun.delete(id);\n\n taskResult = await this._queue.add(\n execute,\n // Removes void from return type.\n // Read more on: https://github.com/sindresorhus/p-queue/issues/175\n { throwOnTimeout: true, priority },\n );\n } while (this._requiresRerun.has(id));\n\n // Delete from pending list.\n this._pendingTasks.delete(id);\n if (task.getEndDescription) {\n this._reportEnd(id, task.getEndDescription(taskResult));\n }\n\n // Extra check to ensure that the task returned a value.\n // It should never throw, if it does we have a bug.\n if (taskResult === undefined) {\n throw new Error(`Task \"${name}:${id}\" returned undefined, without throwing an error, which was unexpected.`);\n }\n\n // Update finished Tasks.\n this._completedTasks.set(id, taskResult);\n\n return taskResult;\n })();\n\n this._pendingTasks.set(id, resultPromise);\n this._completedTasks.delete(id);\n if (task.getStartDescription) {\n this._reportStart(id, task.getStartDescription());\n }\n\n return resultPromise;\n }\n\n /**\n * The remove method disposes a task if available\n * and then removes it from the TaskRunner.\n *\n * This is useful when the state of a task needs to be cleared.\n *\n * It is intended to be used by the api server\n * to clear the TaskRunner's state before reloading the page.\n */\n remove(id: string): void {\n this._prevTasks\n .get(id)\n ?.dispose?.()\n .catch(() => {\n console.debug(`Error disposing task: ${id}`);\n });\n this._prevTasks.get(id)?.onDispose?.();\n this._prevTasks.delete(id);\n this._requiresRerun.delete(id);\n if (this._pendingTasks.has(id)) {\n this._pendingTasks.delete(id);\n this._taskStats.remainingTasks = this._pendingTasks.size;\n const { bus, session } = this._context || {};\n bus && session && bus.publish([session.id, 'status'], this._taskStats);\n }\n this._completedTasks.delete(id);\n }\n /**\n * The clear method disposes all tasks and clears the TaskRunner.\n */\n clear(): void {\n this._taskStats = getDefaultTaskStats();\n if (this._context) {\n const { bus, session } = this._context;\n bus.publish([session.id, 'status'], this._taskStats);\n bus.publish(taskListSource, { tasks: [] });\n }\n for (const id of this._prevTasks.keys()) {\n this.remove(id);\n }\n }\n\n /** Pauses the TaskRunner (for testing). */\n _pause(): void {\n this._queue.pause();\n }\n\n /** Starts or resumes the TaskRunner (for testing). */\n _start(): void {\n this._queue.start();\n }\n\n /**\n * Internal method to report the start of a task to the bus.\n */\n private _reportStart(id: string, description: TaskStartDescription): void {\n if (!this._context) return;\n const { bus } = this._context;\n const { tasks } = bus.getData<TaskList>(taskListSource.path) || { tasks: [] };\n const index = tasks.findIndex((t) => t.id === id);\n const previousDescription = tasks[index];\n const now = new Date().getTime();\n\n if (!previousDescription) {\n this._taskStats.totalTasks++;\n }\n\n if (previousDescription?.status === 'complete') {\n this._taskStats.totalErrors -= previousDescription.errors?.length || 0;\n this._taskStats.totalWarnings -= previousDescription.warnings?.length || 0;\n }\n\n this._taskStats.remainingTasks = this._pendingTasks.size;\n this._taskStats.status = 'pending';\n\n const task: TaskDescription = {\n ...description,\n status: 'pending',\n startTime: now,\n };\n if (index === -1) {\n tasks.push(task);\n } else {\n tasks[index] = task;\n }\n\n bus.publish(taskStatsSource, this._taskStats);\n bus.publish(taskListSource, { tasks });\n }\n\n /**\n * Internal method to report the end of a task to the bus.\n */\n private _reportEnd(id: string, description: TaskEndDescription): void {\n if (!this._context) return;\n const { bus } = this._context;\n const { tasks } = bus.getData<TaskList>(taskListSource.path) || { tasks: [] };\n const index = tasks.findIndex((t) => t.id === id);\n const previousDescription = tasks[index];\n const now = new Date().getTime();\n\n if (previousDescription) {\n this._taskStats.remainingTasks = this._pendingTasks.size;\n this._taskStats.totalErrors += description?.errors?.length || 0;\n this._taskStats.totalWarnings += description?.warnings?.length || 0;\n\n tasks[index] = {\n ...previousDescription,\n ...description,\n status: 'complete',\n durationMilliseconds: now - previousDescription.startTime,\n lastUpdated: now,\n };\n\n if (this._taskStats.remainingTasks === 0) {\n this._taskStats.status = 'idle';\n }\n\n bus.publish(taskStatsSource, this._taskStats);\n bus.publish(taskListSource, { tasks });\n }\n }\n}\n"]}
1
+ {"version":3,"file":"TaskRunner.js","sourceRoot":"","sources":["../../src/utilities/TaskRunner.ts"],"names":[],"mappings":"AAKA,OAAO,MAAM,MAAM,SAAS,CAAC;AAC7B,OAAO,EAAE,mBAAmB,EAAE,MAAM,0BAA0B,CAAC;AAC/D,OAAO,EAAE,cAAc,EAAE,eAAe,EAAwB,MAAM,qBAAqB,CAAC;AAG5F;;;;;;GAMG;AACH,MAAM,OAAO,UAAU;IAUrB;QACE,IAAI,CAAC,MAAM,GAAG,IAAI,MAAM,CAAC,EAAE,WAAW,EAAE,EAAE,EAAE,CAAC,CAAC;QAC9C,IAAI,CAAC,UAAU,GAAG,mBAAmB,EAAE,CAAC;QACxC,IAAI,CAAC,aAAa,GAAG,IAAI,GAAG,EAAE,CAAC;QAC/B,IAAI,CAAC,eAAe,GA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G,CAAC,OAAO,CAAC,eAAe,EAAE,IAAI,CAAC,UAAU,CAAC,CAAC;YAC9C,GAAG,CAAC,OAAO,CAAC,cAAc,EAAE,EAAE,KAAK,EAAE,CAAC,CAAC;QACzC,CAAC;IACH,CAAC;CACF","sourcesContent":["import type { TaskStartDescription } from '../types/TaskStartDescription.js';\nimport type { TaskEndDescription } from '../types/TaskEndDescription.js';\nimport type { Task } from '../types/Task.js';\nimport type { TaskStats } from '../types/TaskStats.js';\nimport type { TaskList } from '../types/TaskList.js';\nimport PQueue from 'p-queue';\nimport { getDefaultTaskStats } from './getDefaultTaskStats.js';\nimport { taskListSource, taskStatsSource, type TaskDescription } from '../index.browser.js';\nimport type { DataBus } from '@ms-cloudpack/data-bus';\n\n/**\n * TaskRunner tracks the status of tasks, manages concurrency, allows reusing task results,\n * and sends notifications about task status to the data bus (currently just used for `start`).\n *\n * NOTE: To enable data bus notifications, you must call `connectToBus()`.\n * `createApiContext` does this with the `taskRunner` passed in.\n */\nexport class TaskRunner {\n private _bus: DataBus | undefined;\n private _queue: PQueue;\n private _taskStats: TaskStats;\n private _pendingTasks: Map<string, Promise<unknown>>;\n private _completedTasks: Map<string, unknown>;\n private _requiresRerun: Set<string>;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n private _prevTasks: Map<string, Task<any>>;\n\n constructor() {\n this._queue = new PQueue({ concurrency: 10 });\n this._taskStats = getDefaultTaskStats();\n this._pendingTasks = new Map();\n this._completedTasks = new Map();\n this._requiresRerun = new Set();\n this._prevTasks = new Map();\n }\n\n /**\n * Connects the TaskRunner to the data bus. Tasks will still run without this, but they won't\n * send any notifications to a client (which only matters if a client is listening, e.g.\n * the browser while running `start`).\n */\n public connectToBus(bus: DataBus): void {\n this._bus = bus;\n }\n\n /**\n * Enqueue a task and return its result promise.\n *\n * If a task with the same `id` was already added, it returns either the previous result\n * (if completed) or the promise (if pending). Pass `options.rerun` to force re-running.\n */\n add<TReturn>(\n task: Task<TReturn>,\n options?: {\n rerun?: boolean;\n priority?: number;\n },\n ): Promise<TReturn> {\n const { name, id, execute } = task;\n const { rerun, priority } = options || {};\n\n if (!this._prevTasks.get(id)) {\n this._prevTasks.set(id, task);\n }\n\n // Check if we are already completed the task with that id.\n const action = this._completedTasks.get(id) as TReturn | undefined;\n if (action !== undefined && !rerun) {\n return Promise.resolve(action);\n }\n\n // Check if we are already running the task with that id.\n const pending = this._pendingTasks.get(id) as Promise<TReturn> | undefined;\n if (pending !== undefined) {\n if (rerun) {\n this._requiresRerun.add(id);\n }\n return pending;\n }\n\n const resultPromise: Promise<TReturn> = (async () => {\n let taskResult: TReturn | undefined;\n\n do {\n // Delete from rerun list (if present).\n this._requiresRerun.delete(id);\n\n taskResult = await this._queue.add(\n execute,\n // Removes void from return type.\n // Read more on: https://github.com/sindresorhus/p-queue/issues/175\n { throwOnTimeout: true, priority },\n );\n } while (this._requiresRerun.has(id));\n\n // Delete from pending list.\n this._pendingTasks.delete(id);\n if (task.getEndDescription) {\n this._reportEnd(id, task.getEndDescription(taskResult));\n }\n\n // Extra check to ensure that the task returned a value.\n // It should never throw, if it does we have a bug.\n if (taskResult === undefined) {\n throw new Error(`Task \"${name}:${id}\" returned undefined, without throwing an error, which was unexpected.`);\n }\n\n // Update finished Tasks.\n this._completedTasks.set(id, taskResult);\n\n return taskResult;\n })();\n\n this._pendingTasks.set(id, resultPromise);\n this._completedTasks.delete(id);\n if (task.getStartDescription) {\n this._reportStart(id, task.getStartDescription());\n }\n\n return resultPromise;\n }\n\n /**\n * The remove method disposes a task if available\n * and then removes it from the TaskRunner.\n *\n * This is useful when the state of a task needs to be cleared.\n *\n * It is intended to be used by the api server\n * to clear the TaskRunner's state before reloading the page.\n */\n remove(id: string): void {\n this._prevTasks\n .get(id)\n ?.dispose?.()\n .catch(() => {\n console.debug(`Error disposing task: ${id}`);\n });\n this._prevTasks.get(id)?.onDispose?.();\n this._prevTasks.delete(id);\n this._requiresRerun.delete(id);\n if (this._pendingTasks.has(id)) {\n this._pendingTasks.delete(id);\n this._taskStats.remainingTasks = this._pendingTasks.size;\n }\n this._completedTasks.delete(id);\n }\n /**\n * The clear method disposes all tasks and clears the TaskRunner.\n */\n clear(): void {\n this._taskStats = getDefaultTaskStats();\n this._bus?.publish(taskListSource, { tasks: [] });\n\n for (const id of this._prevTasks.keys()) {\n this.remove(id);\n }\n }\n\n /** Pauses the TaskRunner (for testing). */\n _pause(): void {\n this._queue.pause();\n }\n\n /** Starts or resumes the TaskRunner (for testing). */\n _start(): void {\n this._queue.start();\n }\n\n /**\n * Internal method to report the start of a task to the bus.\n */\n private _reportStart(id: string, description: TaskStartDescription): void {\n if (!this._bus) return;\n\n const bus = this._bus;\n const { tasks } = bus.getData<TaskList>(taskListSource.path) || { tasks: [] };\n const index = tasks.findIndex((t) => t.id === id);\n const previousDescription = tasks[index];\n const now = new Date().getTime();\n\n if (!previousDescription) {\n this._taskStats.totalTasks++;\n }\n\n if (previousDescription?.status === 'complete') {\n this._taskStats.totalErrors -= previousDescription.errors?.length || 0;\n this._taskStats.totalWarnings -= previousDescription.warnings?.length || 0;\n }\n\n this._taskStats.remainingTasks = this._pendingTasks.size;\n this._taskStats.status = 'pending';\n\n const task: TaskDescription = {\n ...description,\n status: 'pending',\n startTime: now,\n };\n if (index === -1) {\n tasks.push(task);\n } else {\n tasks[index] = task;\n }\n\n bus.publish(taskStatsSource, this._taskStats);\n bus.publish(taskListSource, { tasks });\n }\n\n /**\n * Internal method to report the end of a task to the bus.\n */\n private _reportEnd(id: string, description: TaskEndDescription): void {\n if (!this._bus) return;\n\n const bus = this._bus;\n const { tasks } = bus.getData<TaskList>(taskListSource.path) || { tasks: [] };\n const index = tasks.findIndex((t) => t.id === id);\n const previousDescription = tasks[index];\n const now = new Date().getTime();\n\n if (previousDescription) {\n this._taskStats.remainingTasks = this._pendingTasks.size;\n this._taskStats.totalErrors += description?.errors?.length || 0;\n this._taskStats.totalWarnings += description?.warnings?.length || 0;\n\n tasks[index] = {\n ...previousDescription,\n ...description,\n status: 'complete',\n durationMilliseconds: now - previousDescription.startTime,\n lastUpdated: now,\n };\n\n if (this._taskStats.remainingTasks === 0) {\n this._taskStats.status = 'idle';\n }\n\n bus.publish(taskStatsSource, this._taskStats);\n bus.publish(taskListSource, { tasks });\n }\n }\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ms-cloudpack/api-server",
3
- "version": "0.59.0",
3
+ "version": "0.60.0",
4
4
  "description": "An implementation of the API server that does interacts with a task scheduler.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -34,7 +34,7 @@
34
34
  "@ms-cloudpack/data-bus": "^0.4.3",
35
35
  "@ms-cloudpack/esm-stub-utilities": "^0.14.8",
36
36
  "@ms-cloudpack/file-watcher": "^0.2.0",
37
- "@ms-cloudpack/import-map": "^0.8.30",
37
+ "@ms-cloudpack/import-map": "^0.8.31",
38
38
  "@ms-cloudpack/json-utilities": "^0.1.10",
39
39
  "@ms-cloudpack/package-hashes": "^0.7.28",
40
40
  "@ms-cloudpack/package-utilities": "^11.3.4",
@@ -1,17 +0,0 @@
1
- import type { TaskReporter } from '@ms-cloudpack/task-reporter';
2
- import type { TelemetryClient } from '@ms-cloudpack/telemetry';
3
- import type { Context } from '../types/Context.js';
4
- import type { TaskRunner } from '../utilities/TaskRunner.js';
5
- import type { CreateSessionOptions } from './createSession.js';
6
- import type { LoginMethod } from '@ms-cloudpack/remote-cache';
7
- export interface LazyApiContextOptions extends CreateSessionOptions {
8
- reporter: TaskReporter;
9
- appPath: string;
10
- telemetryClient: TelemetryClient;
11
- taskRunner?: TaskRunner;
12
- remoteCacheClientLoginMethod?: LoginMethod;
13
- }
14
- export declare function createPartialApiContext<TKeys extends Exclude<keyof Context, 'dispose'>, TReturn extends Pick<Context, TKeys | 'dispose' | 'reporter' | 'telemetryClient'>>(options: LazyApiContextOptions & {
15
- items: (false | undefined | null | TKeys)[];
16
- }): Promise<TReturn>;
17
- //# sourceMappingURL=createPartialApiContext.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"createPartialApiContext.d.ts","sourceRoot":"","sources":["../../src/common/createPartialApiContext.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,6BAA6B,CAAC;AAChE,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,yBAAyB,CAAC;AAC/D,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,qBAAqB,CAAC;AACnD,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,4BAA4B,CAAC;AAC7D,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,oBAAoB,CAAC;AAC/D,OAAO,KAAK,EAAE,WAAW,EAAqB,MAAM,4BAA4B,CAAC;AAOjF,MAAM,WAAW,qBAAsB,SAAQ,oBAAoB;IACjE,QAAQ,EAAE,YAAY,CAAC;IACvB,OAAO,EAAE,MAAM,CAAC;IAChB,eAAe,EAAE,eAAe,CAAC;IACjC,UAAU,CAAC,EAAE,UAAU,CAAC;IACxB,4BAA4B,CAAC,EAAE,WAAW,CAAC;CAC5C;AAiJD,wBAAsB,uBAAuB,CAC3C,KAAK,SAAS,OAAO,CAAC,MAAM,OAAO,EAAE,SAAS,CAAC,EAC/C,OAAO,SAAS,IAAI,CAAC,OAAO,EAAE,KAAK,GAAG,SAAS,GAAG,UAAU,GAAG,iBAAiB,CAAC,EACjF,OAAO,EAAE,qBAAqB,GAAG;IAAE,KAAK,EAAE,CAAC,KAAK,GAAG,SAAS,GAAG,IAAI,GAAG,KAAK,CAAC,EAAE,CAAA;CAAE,GAAG,OAAO,CAAC,OAAO,CAAC,CAyBpG"}
@@ -1,163 +0,0 @@
1
- var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
2
- if (kind === "m") throw new TypeError("Private method is not writable");
3
- if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
4
- if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
5
- return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
6
- };
7
- var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
8
- if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
9
- if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
10
- return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
11
- };
12
- var _LazyApiContext_bus, _LazyApiContext_watcher, _LazyApiContext_packages, _LazyApiContext_taskRunner, _LazyApiContext_session, _LazyApiContext_packageHashes, _LazyApiContext_remoteCacheClient;
13
- import { createRemoteCacheClient } from '../utilities/createRemoteCacheClient.js';
14
- class LazyApiContext {
15
- constructor(options) {
16
- this.options = options;
17
- _LazyApiContext_bus.set(this, void 0);
18
- _LazyApiContext_watcher.set(this, void 0);
19
- _LazyApiContext_packages.set(this, void 0);
20
- _LazyApiContext_taskRunner.set(this, void 0);
21
- _LazyApiContext_session.set(this, void 0);
22
- _LazyApiContext_packageHashes.set(this, void 0);
23
- _LazyApiContext_remoteCacheClient.set(this, void 0);
24
- const { taskRunner } = options;
25
- if (taskRunner) {
26
- __classPrivateFieldSet(this, _LazyApiContext_taskRunner, Promise.resolve(taskRunner), "f");
27
- }
28
- }
29
- get telemetryClient() {
30
- return Promise.resolve(this.options.telemetryClient);
31
- }
32
- get bus() {
33
- if (!__classPrivateFieldGet(this, _LazyApiContext_bus, "f")) {
34
- const createDataBusLazy = async () => {
35
- const { createDataBus } = await import('@ms-cloudpack/data-bus');
36
- return createDataBus();
37
- };
38
- __classPrivateFieldSet(this, _LazyApiContext_bus, createDataBusLazy(), "f");
39
- }
40
- return __classPrivateFieldGet(this, _LazyApiContext_bus, "f");
41
- }
42
- get watcher() {
43
- if (!__classPrivateFieldGet(this, _LazyApiContext_watcher, "f")) {
44
- const createWatcherLazy = async () => {
45
- const { createWatcher } = await import('@ms-cloudpack/file-watcher');
46
- return createWatcher({
47
- type: this.options?.config?.features?.enableWatcherInFork ? 'fork' : 'default',
48
- });
49
- };
50
- __classPrivateFieldSet(this, _LazyApiContext_watcher, createWatcherLazy(), "f");
51
- }
52
- return __classPrivateFieldGet(this, _LazyApiContext_watcher, "f");
53
- }
54
- get reporter() {
55
- return Promise.resolve(this.options.reporter);
56
- }
57
- get packages() {
58
- if (!__classPrivateFieldGet(this, _LazyApiContext_packages, "f")) {
59
- const createPackageDefinitionsLazy = async () => {
60
- const { createPackageDefinitions } = await import('@ms-cloudpack/config');
61
- return createPackageDefinitions({ config: this.options.config });
62
- };
63
- __classPrivateFieldSet(this, _LazyApiContext_packages, createPackageDefinitionsLazy(), "f");
64
- }
65
- return __classPrivateFieldGet(this, _LazyApiContext_packages, "f");
66
- }
67
- get packageHashes() {
68
- if (!__classPrivateFieldGet(this, _LazyApiContext_packageHashes, "f")) {
69
- const createPackageHashesLazy = async () => {
70
- const { PackageHashes } = await import('@ms-cloudpack/package-hashes');
71
- return new PackageHashes({
72
- cwd: this.options.appPath,
73
- context: {
74
- config: this.options.config,
75
- packages: await this.packages,
76
- resolveMap: (await this.session).resolveMap,
77
- },
78
- });
79
- };
80
- __classPrivateFieldSet(this, _LazyApiContext_packageHashes, createPackageHashesLazy(), "f");
81
- }
82
- return __classPrivateFieldGet(this, _LazyApiContext_packageHashes, "f");
83
- }
84
- get taskRunner() {
85
- if (!__classPrivateFieldGet(this, _LazyApiContext_taskRunner, "f")) {
86
- const createTaskRunnerLazy = async () => {
87
- const { TaskRunner } = await import('../utilities/TaskRunner.js');
88
- return new TaskRunner({
89
- bus: await this.bus,
90
- reporter: await this.reporter,
91
- session: await this.session,
92
- });
93
- };
94
- __classPrivateFieldSet(this, _LazyApiContext_taskRunner, createTaskRunnerLazy(), "f");
95
- }
96
- return __classPrivateFieldGet(this, _LazyApiContext_taskRunner, "f");
97
- }
98
- get session() {
99
- if (!__classPrivateFieldGet(this, _LazyApiContext_session, "f")) {
100
- const createSessionLazy = async () => {
101
- const { createSession } = await import('./createSession.js');
102
- return createSession(this.options, {
103
- reporter: await this.reporter,
104
- packages: await this.packages,
105
- telemetryClient: await this.telemetryClient,
106
- });
107
- };
108
- __classPrivateFieldSet(this, _LazyApiContext_session, createSessionLazy(), "f");
109
- }
110
- return __classPrivateFieldGet(this, _LazyApiContext_session, "f");
111
- }
112
- get remoteCacheClient() {
113
- if (!__classPrivateFieldGet(this, _LazyApiContext_remoteCacheClient, "f")) {
114
- const createRemoteCacheClientLazy = async () => {
115
- if (!this.options.remoteCacheClientLoginMethod) {
116
- throw new Error('remoteCacheClientLoginMethod is required to create api context with remote cache');
117
- }
118
- return createRemoteCacheClient({
119
- ctx: {
120
- session: await this.session,
121
- reporter: await this.reporter,
122
- telemetryClient: await this.telemetryClient,
123
- },
124
- input: {
125
- loginMethod: this.options.remoteCacheClientLoginMethod,
126
- },
127
- });
128
- };
129
- __classPrivateFieldSet(this, _LazyApiContext_remoteCacheClient, createRemoteCacheClientLazy(), "f");
130
- }
131
- return __classPrivateFieldGet(this, _LazyApiContext_remoteCacheClient, "f");
132
- }
133
- async dispose() {
134
- if (__classPrivateFieldGet(this, _LazyApiContext_watcher, "f")) {
135
- const watcher = await __classPrivateFieldGet(this, _LazyApiContext_watcher, "f");
136
- await watcher.dispose();
137
- }
138
- }
139
- }
140
- _LazyApiContext_bus = new WeakMap(), _LazyApiContext_watcher = new WeakMap(), _LazyApiContext_packages = new WeakMap(), _LazyApiContext_taskRunner = new WeakMap(), _LazyApiContext_session = new WeakMap(), _LazyApiContext_packageHashes = new WeakMap(), _LazyApiContext_remoteCacheClient = new WeakMap();
141
- export async function createPartialApiContext(options) {
142
- const { reporter, telemetryClient, items } = options;
143
- return telemetryClient.tracer.startActiveSpan('CREATE_PARTIAL_API_CONTEXT', async (span) => {
144
- const lazyContext = new LazyApiContext(options);
145
- const result = {
146
- reporter,
147
- telemetryClient,
148
- dispose: () => {
149
- return lazyContext.dispose();
150
- },
151
- };
152
- for (const item of items) {
153
- if (item) {
154
- result[item] = (await lazyContext[item]);
155
- }
156
- }
157
- span.setAttributes({
158
- items: items.filter((item) => !!item).join(','),
159
- });
160
- return result;
161
- });
162
- }
163
- //# sourceMappingURL=createPartialApiContext.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"createPartialApiContext.js","sourceRoot":"","sources":["../../src/common/createPartialApiContext.ts"],"names":[],"mappings":";;;;;;;;;;;;AASA,OAAO,EAAE,uBAAuB,EAAE,MAAM,yCAAyC,CAAC;AAclF,MAAM,cAAc;IASlB,YAA6B,OAA8B;QAA9B,YAAO,GAAP,OAAO,CAAuB;QAR3D,sCAAmC;QACnC,0CAAuC;QACvC,2CAAwD;QACxD,6CAA6C;QAC7C,0CAAuC;QACvC,gDAAwD;QACxD,oDAAuE;QAGrE,MAAM,EAAE,UAAU,EAAE,GAAG,OAAO,CAAC;QAC/B,IAAI,UAAU,EAAE,CAAC;YACf,uBAAA,IAAI,8BAAe,OAAO,CAAC,OAAO,CAAC,UAAU,CAAC,MAAA,CAAC;QACjD,CAAC;IACH,CAAC;IAED,IAAW,eAAe;QACxB,OAAO,OAAO,CAAC,OAAO,CAAC,IAAI,CAAC,OAAO,CAAC,eAAe,CAAC,CAAC;IACvD,CAAC;IAED,IAAW,GAAG;QACZ,IAAI,CAAC,uBAAA,IAAI,2BAAK,EAAE,CAAC;YACf,MAAM,iBAAiB,GAAG,KAAK,IAAI,EAAE;gBACnC,MAAM,EAAE,aAAa,EAAE,GAAG,MAAM,MAAM,CAAC,wBAAwB,CAAC,CAAC;gBACjE,OAAO,aAAa,EAAE,CAAC;YACzB,CAAC,CAAC;YACF,uBAAA,IAAI,uBAAQ,iBAAiB,EAAE,MAAA,CAAC;QAClC,CAAC;QAED,OAAO,uBAAA,IAAI,2BAAK,CAAC;IACnB,CAAC;IAED,IAAW,OAAO;QAChB,IAAI,CAAC,uBAAA,IAAI,+BAAS,EAAE,CAAC;YACnB,MAAM,i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AC,OAAO,CAAC,CAAC;QAEhD,MAAM,MAAM,GAAG;YACb,QAAQ;YACR,eAAe;YACf,OAAO,EAAE,GAAG,EAAE;gBACZ,OAAO,WAAW,CAAC,OAAO,EAAE,CAAC;YAC/B,CAAC;SACS,CAAC;QAEb,KAAK,MAAM,IAAI,IAAI,KAAK,EAAE,CAAC;YACzB,IAAI,IAAI,EAAE,CAAC;gBACT,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,MAAM,WAAW,CAAC,IAAI,CAAC,CAAmB,CAAC;YAC7D,CAAC;QACH,CAAC;QAED,IAAI,CAAC,aAAa,CAAC;YACjB,KAAK,EAAE,KAAK,CAAC,MAAM,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC;SAChD,CAAC,CAAC;QAEH,OAAO,MAAM,CAAC;IAChB,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import type { PackageDefinitionsCache, PackageHashesCache, Session } from '@ms-cloudpack/common-types';\nimport type { DataBus } from '@ms-cloudpack/data-bus';\nimport type { Watcher } from '@ms-cloudpack/file-watcher';\nimport type { TaskReporter } from '@ms-cloudpack/task-reporter';\nimport type { TelemetryClient } from '@ms-cloudpack/telemetry';\nimport type { Context } from '../types/Context.js';\nimport type { TaskRunner } from '../utilities/TaskRunner.js';\nimport type { CreateSessionOptions } from './createSession.js';\nimport type { LoginMethod, RemoteCacheClient } from '@ms-cloudpack/remote-cache';\nimport { createRemoteCacheClient } from '../utilities/createRemoteCacheClient.js';\n\ntype PromisifyProperties<T> = {\n [K in keyof T]: T[K] extends (...args: unknown[]) => unknown ? T[K] : Promise<T[K]>;\n};\n\nexport interface LazyApiContextOptions extends CreateSessionOptions {\n reporter: TaskReporter;\n appPath: string;\n telemetryClient: TelemetryClient;\n taskRunner?: TaskRunner;\n remoteCacheClientLoginMethod?: LoginMethod;\n}\n\nclass LazyApiContext implements PromisifyProperties<Context> {\n #bus: Promise<DataBus> | undefined;\n #watcher: Promise<Watcher> | undefined;\n #packages: Promise<PackageDefinitionsCache> | undefined;\n #taskRunner: Promise<TaskRunner> | undefined;\n #session: Promise<Session> | undefined;\n #packageHashes: Promise<PackageHashesCache> | undefined;\n #remoteCacheClient: Promise<RemoteCacheClient | undefined> | undefined;\n\n constructor(private readonly options: LazyApiContextOptions) {\n const { taskRunner } = options;\n if (taskRunner) {\n this.#taskRunner = Promise.resolve(taskRunner);\n }\n }\n\n public get telemetryClient(): Promise<TelemetryClient> {\n return Promise.resolve(this.options.telemetryClient);\n }\n\n public get bus(): Promise<DataBus> {\n if (!this.#bus) {\n const createDataBusLazy = async () => {\n const { createDataBus } = await import('@ms-cloudpack/data-bus');\n return createDataBus();\n };\n this.#bus = createDataBusLazy();\n }\n\n return this.#bus;\n }\n\n public get watcher(): Promise<Watcher> {\n if (!this.#watcher) {\n const createWatcherLazy = async () => {\n const { createWatcher } = await import('@ms-cloudpack/file-watcher');\n return createWatcher({\n type: this.options?.config?.features?.enableWatcherInFork ? 'fork' : 'default',\n });\n };\n this.#watcher = createWatcherLazy();\n }\n\n return this.#watcher;\n }\n\n public get reporter(): Promise<TaskReporter> {\n return Promise.resolve(this.options.reporter);\n }\n\n public get packages(): Promise<PackageDefinitionsCache> {\n if (!this.#packages) {\n const createPackageDefinitionsLazy = async () => {\n const { createPackageDefinitions } = await import('@ms-cloudpack/config');\n return createPackageDefinitions({ config: this.options.config });\n };\n this.#packages = createPackageDefinitionsLazy();\n }\n\n return this.#packages;\n }\n\n public get packageHashes(): Promise<PackageHashesCache> {\n if (!this.#packageHashes) {\n const createPackageHashesLazy = async () => {\n const { PackageHashes } = await import('@ms-cloudpack/package-hashes');\n return new PackageHashes({\n cwd: this.options.appPath,\n context: {\n config: this.options.config,\n packages: await this.packages,\n resolveMap: (await this.session).resolveMap,\n },\n });\n };\n this.#packageHashes = createPackageHashesLazy();\n }\n\n return this.#packageHashes;\n }\n\n public get taskRunner(): Promise<TaskRunner> {\n if (!this.#taskRunner) {\n const createTaskRunnerLazy = async () => {\n const { TaskRunner } = await import('../utilities/TaskRunner.js');\n return new TaskRunner({\n bus: await this.bus,\n reporter: await this.reporter,\n session: await this.session,\n });\n };\n this.#taskRunner = createTaskRunnerLazy();\n }\n return this.#taskRunner;\n }\n\n public get session(): Promise<Session> {\n if (!this.#session) {\n const createSessionLazy = async () => {\n const { createSession } = await import('./createSession.js');\n return createSession(this.options, {\n reporter: await this.reporter,\n packages: await this.packages,\n telemetryClient: await this.telemetryClient,\n });\n };\n this.#session = createSessionLazy();\n }\n\n return this.#session;\n }\n\n public get remoteCacheClient(): Promise<RemoteCacheClient | undefined> {\n if (!this.#remoteCacheClient) {\n const createRemoteCacheClientLazy = async () => {\n if (!this.options.remoteCacheClientLoginMethod) {\n throw new Error('remoteCacheClientLoginMethod is required to create api context with remote cache');\n }\n\n return createRemoteCacheClient({\n ctx: {\n session: await this.session,\n reporter: await this.reporter,\n telemetryClient: await this.telemetryClient,\n },\n input: {\n loginMethod: this.options.remoteCacheClientLoginMethod,\n },\n });\n };\n this.#remoteCacheClient = createRemoteCacheClientLazy();\n }\n return this.#remoteCacheClient;\n }\n\n public async dispose(): Promise<void> {\n if (this.#watcher) {\n const watcher = await this.#watcher;\n await watcher.dispose();\n }\n }\n}\n\nexport async function createPartialApiContext<\n TKeys extends Exclude<keyof Context, 'dispose'>,\n TReturn extends Pick<Context, TKeys | 'dispose' | 'reporter' | 'telemetryClient'>,\n>(options: LazyApiContextOptions & { items: (false | undefined | null | TKeys)[] }): Promise<TReturn> {\n const { reporter, telemetryClient, items } = options;\n return telemetryClient.tracer.startActiveSpan('CREATE_PARTIAL_API_CONTEXT', async (span) => {\n const lazyContext = new LazyApiContext(options);\n\n const result = {\n reporter,\n telemetryClient,\n dispose: () => {\n return lazyContext.dispose();\n },\n } as TReturn;\n\n for (const item of items) {\n if (item) {\n result[item] = (await lazyContext[item]) as TReturn[TKeys];\n }\n }\n\n span.setAttributes({\n items: items.filter((item) => !!item).join(','),\n });\n\n return result;\n });\n}\n"]}
@@ -1,6 +0,0 @@
1
- export interface TaskOptions {
2
- rerun?: boolean;
3
- watch?: () => void;
4
- priority?: number;
5
- }
6
- //# sourceMappingURL=TaskOptions.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"TaskOptions.d.ts","sourceRoot":"","sources":["../../src/types/TaskOptions.ts"],"names":[],"mappings":"AAAA,MAAM,WAAW,WAAW;IAC1B,KAAK,CAAC,EAAE,OAAO,CAAC;IAChB,KAAK,CAAC,EAAE,MAAM,IAAI,CAAC;IACnB,QAAQ,CAAC,EAAE,MAAM,CAAC;CACnB"}
@@ -1,2 +0,0 @@
1
- export {};
2
- //# sourceMappingURL=TaskOptions.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"TaskOptions.js","sourceRoot":"","sources":["../../src/types/TaskOptions.ts"],"names":[],"mappings":"","sourcesContent":["export interface TaskOptions {\n rerun?: boolean;\n watch?: () => void;\n priority?: number;\n}\n"]}
@@ -1,3 +0,0 @@
1
- import type { Context } from './Context.js';
2
- export type TaskRunnerContext = Pick<Context, 'reporter' | 'bus' | 'session'>;
3
- //# sourceMappingURL=TaskRunnerContext.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"TaskRunnerContext.d.ts","sourceRoot":"","sources":["../../src/types/TaskRunnerContext.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,cAAc,CAAC;AAE5C,MAAM,MAAM,iBAAiB,GAAG,IAAI,CAAC,OAAO,EAAE,UAAU,GAAG,KAAK,GAAG,SAAS,CAAC,CAAC"}
@@ -1,2 +0,0 @@
1
- export {};
2
- //# sourceMappingURL=TaskRunnerContext.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"TaskRunnerContext.js","sourceRoot":"","sources":["../../src/types/TaskRunnerContext.ts"],"names":[],"mappings":"","sourcesContent":["import type { Context } from './Context.js';\n\nexport type TaskRunnerContext = Pick<Context, 'reporter' | 'bus' | 'session'>;\n"]}