{"version":3,"sources":["../src/index.ts"],"sourcesContent":["/**\n * Superserve Provider - Factory-based Implementation\n *\n * Wraps `@superserve/sdk` to expose the ComputeSDK provider interface.\n */\n\nimport { randomUUID } from 'node:crypto';\nimport {\n  AuthenticationError,\n  NotFoundError,\n  Sandbox as SuperserveSandbox,\n  Snapshot as SuperserveSnapshot,\n  Template as SuperserveTemplate,\n} from '@superserve/sdk';\nimport type { SnapshotInfo, TemplateCreateOptions, TemplateInfo } from '@superserve/sdk';\nimport { defineProvider, escapeShellArg, InstanceSizeError, INSTANCE_SIZE_PROFILES } from '@computesdk/provider';\n\nconst DEFAULT_TIMEOUT_MS = 300_000;\n\nimport type {\n  CommandResult,\n  CreateInstanceOptions,\n  CreateTemplateOptions,\n  FileEntry,\n  InstanceSizeClass,\n  RunCommandOptions,\n  InstanceInfo,\n} from '@computesdk/provider';\n\nexport interface SuperserveConfig {\n  /** Superserve API key. Falls back to `SUPERSERVE_API_KEY` env var. */\n  apiKey?: string;\n  /** API base URL. Falls back to `SUPERSERVE_BASE_URL` env var, then the `@superserve/sdk` default. */\n  baseUrl?: string;\n  /** Default auto-pause timeout in milliseconds. */\n  timeout?: number;\n  /** Template to boot per standard `sizeClass`; defaults to {@link SUPERSERVE_SIZE_TEMPLATES}. */\n  sizeTemplates?: Partial<Record<InstanceSizeClass, string>>;\n}\n\n/**\n * Superserve fixes vCPU, memory and disk when a template is built, so each\n * standard size boots its own template. `superserve/base` (2 vCPU / 4 GiB /\n * 8 GiB disk) is built in to every team; the others are team templates\n * built by `scripts/provider-setup.mjs superserve`. The largest listed plan\n * (Pro) caps a sandbox at 16 vCPU / 64 GiB, so `3xl` has no default.\n */\nexport const SUPERSERVE_SIZE_TEMPLATES: Readonly<Partial<Record<InstanceSizeClass, string>>> = Object.freeze({\n  xs: 'csdk-node22-1cpu-1gb',\n  sm: 'csdk-node22-1cpu-2gb',\n  md: 'superserve/base',\n  lg: 'csdk-node22-4cpu-8gb',\n  xl: 'csdk-node22-8cpu-16gb',\n  '2xl': 'csdk-node22-16cpu-32gb',\n});\n\n/** Disk the built-in templates fix; team templates take theirs from the build. */\nconst BUILT_IN_TEMPLATE_DISK_MIB: Readonly<Record<string, number>> = Object.freeze({ 'superserve/base': 8192 });\n\n/** Native selectors that pick or size the VM; `Sandbox.create` drops the sizing ones silently. */\nconst SOURCE_OPTIONS = ['templateId', 'snapshotId', 'sandboxId', 'fromTemplate', 'fromSnapshot'] as const;\nconst NATIVE_SIZE_OPTIONS = ['vcpu', 'vcpuCount', 'memoryMib', 'memoryMaxMib', 'diskMib'] as const;\n\nfunction sizeTemplateOf(config: SuperserveConfig, sizeClass: InstanceSizeClass): string | undefined {\n  const name = config.sizeTemplates?.[sizeClass] ?? SUPERSERVE_SIZE_TEMPLATES[sizeClass];\n  return typeof name === 'string' && name.trim() ? name : undefined;\n}\n\n/** A create that failed because a standard-size template was never built on this team. */\nfunction missingSizeTemplate(config: SuperserveConfig, templateId: unknown, error: unknown): string | undefined {\n  if (typeof templateId !== 'string' || !(error instanceof NotFoundError)) return undefined;\n  const sizeClass = (Object.keys(INSTANCE_SIZE_PROFILES) as InstanceSizeClass[]).find(c => sizeTemplateOf(config, c) === templateId);\n  if (!sizeClass) return undefined;\n  return `Superserve size template '${templateId}' (sizeClass ${sizeClass}) is not built on this Superserve team; run \\`node scripts/provider-setup.mjs superserve\\` (provider-setup.yml) or point \\`sizeTemplates.${sizeClass}\\` at an existing template`;\n}\n\nfunction resolveApiKey(config: SuperserveConfig): string {\n  const apiKey = config.apiKey || process.env.SUPERSERVE_API_KEY;\n  if (!apiKey) {\n    throw new Error(\n      `Missing Superserve API key. Provide 'apiKey' in config or set SUPERSERVE_API_KEY environment variable.`,\n    );\n  }\n  return apiKey;\n}\n\nfunction resolveBaseUrl(config: SuperserveConfig): string | undefined {\n  // Returns undefined when unset on purpose: the SDK then applies its own\n  // resolution (SUPERSERVE_BASE_URL env var, then its default endpoint), so\n  // we don't duplicate that default and risk it drifting.\n  return config.baseUrl || process.env.SUPERSERVE_BASE_URL || undefined;\n}\n\nfunction generateSandboxName(): string {\n  return `cs-${randomUUID().slice(0, 8)}`;\n}\n\ntype CommandRunner = (\n  sandbox: SuperserveSandbox,\n  command: string,\n  options?: RunCommandOptions,\n) => Promise<CommandResult>;\n\nconst FALLBACK_WORKDIR = '/';\n\n/** Cached `pwd` probes: relative filesystem paths resolve against the cwd a\n *  `runCommand` exec would use, so `writeFile('a.txt')` and `cat a.txt` agree. */\nconst workdirs = new WeakMap<SuperserveSandbox, Promise<string>>();\n\nfunction workdirOf(sandbox: SuperserveSandbox, runCommand: CommandRunner): Promise<string> {\n  let probe = workdirs.get(sandbox);\n  if (!probe) {\n    probe = runCommand(sandbox, 'pwd').then((result) => {\n      const dir = result.stdout.trim();\n      if (result.exitCode === 0 && dir.startsWith('/')) return dir;\n      // runCommand reports exec failures as results, not rejections, so a\n      // transient failure must not pin the workdir to the fallback forever —\n      // evict and let the next filesystem op probe again.\n      workdirs.delete(sandbox);\n      return FALLBACK_WORKDIR;\n    });\n    workdirs.set(sandbox, probe);\n    probe.catch(() => workdirs.delete(sandbox));\n  }\n  return probe;\n}\n\n/** Join `path` onto the sandbox workdir. Absolute paths pass through and skip\n *  the probe; empty and `.` segments are dropped; `..` segments are preserved\n *  for the sandbox filesystem to resolve physically — collapsing them\n *  lexically would mis-resolve when a preceding component is a symlink. */\nasync function resolveSandboxPath(\n  sandbox: SuperserveSandbox,\n  path: string,\n  runCommand: CommandRunner,\n): Promise<string> {\n  const combined = path.startsWith('/')\n    ? path\n    : `${await workdirOf(sandbox, runCommand)}/${path}`;\n  const segments: string[] = [];\n  for (const segment of combined.split('/')) {\n    if (segment === '' || segment === '.') continue;\n    segments.push(segment);\n  }\n  return `/${segments.join('/')}`;\n}\n\nfunction rethrowFriendly(error: unknown, fallbackPrefix: string): never {\n  if (error instanceof AuthenticationError) {\n    throw new Error(\n      `Superserve authentication failed. Please check your SUPERSERVE_API_KEY environment variable.`,\n    );\n  }\n  const message = error instanceof Error ? error.message : String(error);\n  const lower = message.toLowerCase();\n  if (lower.includes('unauthorized') || lower.includes('401') || lower.includes('api key')) {\n    throw new Error(\n      `Superserve authentication failed. Please check your SUPERSERVE_API_KEY environment variable.`,\n    );\n  }\n  if (lower.includes('quota') || lower.includes('limit') || lower.includes('429')) {\n    throw new Error(`Superserve quota or rate limit reached: ${message}`);\n  }\n  throw new Error(`${fallbackPrefix}: ${message}`);\n}\n\n// Also serves as `streamCommand`: the SDK streams output over its own exec API\n// when callbacks are passed, so no daemon or routable port is needed.\nconst runCommand: CommandRunner = async (sandbox, command, options) => {\n  const startTime = Date.now();\n  try {\n    let fullCommand = command;\n    if (options?.background) {\n      // Run the whole command under `sh -c` so the trailing `&` backgrounds\n      // the entire command (not just its last statement), and escape it so\n      // the user's command can't break out of the nohup wrapper.\n      fullCommand = `nohup sh -c \"${escapeShellArg(fullCommand)}\" > /dev/null 2>&1 &`;\n    }\n    const result = await sandbox.commands.run(fullCommand, {\n      cwd: options?.cwd,\n      env: options?.env,\n      timeoutMs: options?.timeout,\n      onStdout: options?.onStdout,\n      onStderr: options?.onStderr,\n    });\n    return {\n      stdout: result.stdout,\n      stderr: result.stderr,\n      exitCode: result.exitCode,\n      durationMs: Date.now() - startTime,\n    };\n  } catch (error) {\n    return {\n      stdout: '',\n      stderr: error instanceof Error ? error.message : String(error),\n      exitCode: 127,\n      durationMs: Date.now() - startTime,\n    };\n  }\n};\n\nfunction toSnapshot(info: SnapshotInfo) {\n  return {\n    id: info.id,\n    provider: 'superserve',\n    createdAt: info.createdAt,\n    metadata: {\n      name: info.name,\n      sandboxId: info.sandboxId,\n      status: info.status,\n      sizeBytes: info.sizeBytes,\n    },\n  };\n}\n\n/** Superserve sizes sandboxes at the template: vCPU, memory and disk are set\n *  here and every sandbox created from it inherits them. */\nexport type SuperserveTemplateCreateOptions = CreateTemplateOptions & Partial<Omit<TemplateCreateOptions, 'apiKey' | 'baseUrl' | 'name'>>;\n\nfunction toTemplate(info: TemplateInfo) {\n  return {\n    id: info.id,\n    name: info.name,\n    createdAt: info.createdAt,\n    metadata: { status: info.status, vcpu: info.vcpu, memoryMib: info.memoryMib, diskMib: info.diskMib, errorMessage: info.errorMessage },\n  };\n}\n\nexport const superserve = defineProvider<SuperserveSandbox, SuperserveConfig>({\n  name: 'superserve',\n  sizes: (config, profile, options) => {\n    const opts = options as Record<string, unknown> | undefined;\n    const nativeSize = NATIVE_SIZE_OPTIONS.find(key => opts?.[key] !== undefined);\n    if (nativeSize) {\n      throw new InstanceSizeError('conflict', `cannot combine sizeClass with native Superserve ${nativeSize}; Superserve sizes sandboxes by template`);\n    }\n    const source = SOURCE_OPTIONS.find(key => opts?.[key] !== undefined);\n    if (source) {\n      return { status: 'unsupported', reason: `A Superserve template or snapshot fixes CPU and memory; drop ${source} to boot the standard size template.` };\n    }\n    const templateId = sizeTemplateOf(config, profile.sizeClass);\n    if (!templateId) {\n      return {\n        status: 'unsupported',\n        reason: `Superserve lists at most 16 vCPU / 64 GiB per sandbox (Pro plan); ${profile.sizeClass} needs ${profile.vcpus} vCPU / ${profile.memoryMiB / 1024} GiB. Set sizeTemplates.${profile.sizeClass} to a custom-size template to use it.`,\n      };\n    }\n    const diskMiB = BUILT_IN_TEMPLATE_DISK_MIB[templateId];\n    return {\n      status: 'supported',\n      nativeOptions: { templateId },\n      ...(diskMiB === undefined ? {} : { resolved: { vcpus: profile.vcpus, memoryMiB: profile.memoryMiB, diskMiB } }),\n    };\n  },\n  methods: {\n    instances: {\n      create: async (config: SuperserveConfig, options?: CreateInstanceOptions) => {\n        const apiKey = resolveApiKey(config);\n        const baseUrl = resolveBaseUrl(config);\n\n        const {\n          timeout: requestedTimeoutMs,\n          envs,\n          name,\n          metadata,\n          templateId,\n          snapshotId,\n          namespace: _namespace,\n          directory: _directory,\n          ...providerOptions\n        } = options || {};\n\n        const ttMs = requestedTimeoutMs ?? config.timeout;\n        const timeoutSeconds = ttMs !== undefined ? Math.max(1, Math.ceil(ttMs / 1000)) : undefined;\n\n        try {\n          const sandbox = await SuperserveSandbox.create({\n            apiKey,\n            baseUrl,\n            name: name ?? generateSandboxName(),\n            ...(templateId ? { fromTemplate: templateId } : {}),\n            ...(snapshotId ? { fromSnapshot: snapshotId } : {}),\n            ...(timeoutSeconds !== undefined ? { timeoutSeconds } : {}),\n            ...(metadata ? { metadata: metadata as Record<string, string> } : {}),\n            ...(envs ? { envVars: envs } : {}),\n            ...providerOptions,\n          });\n          return { instance: sandbox, instanceId: sandbox.id };\n        } catch (error) {\n          const notBuilt = missingSizeTemplate(config, templateId, error);\n          if (notBuilt) throw Object.assign(new Error(notBuilt), { status: 404, cause: error });\n          rethrowFriendly(error, 'Failed to create Superserve sandbox');\n        }\n      },\n\n      getById: async (config: SuperserveConfig, sandboxId: string) => {\n        const apiKey = resolveApiKey(config);\n        const baseUrl = resolveBaseUrl(config);\n        try {\n          const sandbox = await SuperserveSandbox.connect(sandboxId, { apiKey, baseUrl });\n          return { instance: sandbox, instanceId: sandbox.id };\n        } catch {\n          return null;\n        }\n      },\n\n      list: async (config: SuperserveConfig) => {\n        const apiKey = resolveApiKey(config);\n        const baseUrl = resolveBaseUrl(config);\n        try {\n          const infos = await SuperserveSandbox.list({ apiKey, baseUrl });\n          // No per-item connect() — that would POST /activate and resume paused sandboxes.\n          return infos.map((info) => ({ instance: info as unknown as SuperserveSandbox, instanceId: info.id,\n          }));\n        } catch {\n          return [];\n        }\n      },\n\n      destroy: async (config: SuperserveConfig, sandboxId: string) => {\n        const apiKey = resolveApiKey(config);\n        const baseUrl = resolveBaseUrl(config);\n        // The SDK handles already-deleted sandboxes and retries transient failures.\n        await SuperserveSandbox.killById(sandboxId, { apiKey, baseUrl });\n      },\n\n      runCommand,\n      streamCommand: runCommand,\n\n      getInfo: async (sandbox: SuperserveSandbox): Promise<InstanceInfo> => {\n        const info = await sandbox.getInfo();\n        const status: InstanceInfo['status'] =\n          info.status === 'paused' || info.status === 'deleted' ? 'stopped' :\n          info.status === 'failed' ? 'error' :\n          'running';\n        return {\n          id: info.id,\n          provider: 'superserve',\n          status,\n          createdAt: info.createdAt,\n          timeout: info.timeoutSeconds ? info.timeoutSeconds * 1000 : DEFAULT_TIMEOUT_MS,\n          metadata: info.metadata,\n        };\n      },\n\n      getUrl: async (sandbox: SuperserveSandbox, options: { port: number; protocol?: string }): Promise<string> => {\n        // A preview URL only routes once its port is published. A new port takes\n        // the sandbox's `previewAccess` default; a published one keeps its mode.\n        await sandbox.publishPreviewPort(options.port);\n        const url = sandbox.getPreviewUrl(options.port);\n        return options.protocol ? url.replace(/^https/, options.protocol) : url;\n      },\n\n      filesystem: {\n        readFile: async (sandbox: SuperserveSandbox, path: string, runCommand: CommandRunner): Promise<string> => {\n          return sandbox.files.readText(await resolveSandboxPath(sandbox, path, runCommand));\n        },\n\n        writeFile: async (sandbox: SuperserveSandbox, path: string, content: string, runCommand: CommandRunner): Promise<void> => {\n          await sandbox.files.write(await resolveSandboxPath(sandbox, path, runCommand), content);\n        },\n\n        mkdir: async (sandbox: SuperserveSandbox, path: string, runCommand: CommandRunner): Promise<void> => {\n          const resolved = await resolveSandboxPath(sandbox, path, runCommand);\n          const result = await sandbox.commands.run(`mkdir -p \"${escapeShellArg(resolved)}\"`);\n          if (result.exitCode !== 0) {\n            throw new Error(`mkdir failed: ${result.stderr || `exit code ${result.exitCode}`}`);\n          }\n        },\n\n        readdir: async (sandbox: SuperserveSandbox, path: string, runCommand: CommandRunner): Promise<FileEntry[]> => {\n          const resolved = await resolveSandboxPath(sandbox, path, runCommand);\n          // find -printf format: <type>\\t<size>\\t<mtime-epoch>\\t<name>\n          const cmd = [\n            `cd \"${escapeShellArg(resolved)}\" || exit 2`,\n            `find . -mindepth 1 -maxdepth 1 -printf '%y\\\\t%s\\\\t%T@\\\\t%f\\\\n' 2>/dev/null`,\n          ].join(' && ');\n          const result = await sandbox.commands.run(cmd);\n          if (result.exitCode === 2) {\n            throw new Error(`readdir: directory not found: ${path}`);\n          }\n          if (result.exitCode !== 0) {\n            throw new Error(`readdir failed: ${result.stderr || `exit code ${result.exitCode}`}`);\n          }\n          const entries: FileEntry[] = [];\n          for (const line of result.stdout.split('\\n')) {\n            if (!line) continue;\n            const [type, sizeStr, mtimeStr, ...nameParts] = line.split('\\t');\n            const name = nameParts.join('\\t');\n            if (!name) continue;\n            const size = Number.parseInt(sizeStr, 10);\n            const mtime = Number.parseFloat(mtimeStr);\n            entries.push({\n              name,\n              type: type === 'd' ? 'directory' : 'file',\n              size: Number.isFinite(size) ? size : 0,\n              modified: Number.isFinite(mtime) ? new Date(mtime * 1000) : new Date(),\n            });\n          }\n          return entries;\n        },\n\n        exists: async (sandbox: SuperserveSandbox, path: string, runCommand: CommandRunner): Promise<boolean> => {\n          const resolved = await resolveSandboxPath(sandbox, path, runCommand);\n          const result = await sandbox.commands.run(`test -e \"${escapeShellArg(resolved)}\"`);\n          return result.exitCode === 0;\n        },\n\n        remove: async (sandbox: SuperserveSandbox, path: string, runCommand: CommandRunner): Promise<void> => {\n          // An empty or dot-only path would resolve to the workdir itself —\n          // refuse it rather than `rm -rf` the sandbox's whole cwd.\n          if (path.split('/').every((s) => s === '' || s === '.')) {\n            throw new Error(`remove: refusing ambiguous path: ${JSON.stringify(path)}`);\n          }\n          const resolved = await resolveSandboxPath(sandbox, path, runCommand);\n          const result = await sandbox.commands.run(`rm -rf \"${escapeShellArg(resolved)}\"`);\n          if (result.exitCode !== 0) {\n            throw new Error(`remove failed: ${result.stderr || `exit code ${result.exitCode}`}`);\n          }\n        },\n      },\n\n      getInstance: (sandbox: SuperserveSandbox): SuperserveSandbox => sandbox,\n\n      pause: async (sandbox: SuperserveSandbox): Promise<void> => {\n        try {\n          await sandbox.pause({ wait: true });\n        } catch (error) {\n          rethrowFriendly(error, 'Failed to pause Superserve sandbox');\n        }\n      },\n\n      resume: async (sandbox: SuperserveSandbox): Promise<void> => {\n        try {\n          // The access token rotates on resume; the SDK refreshes the handle in place.\n          await sandbox.resume();\n        } catch (error) {\n          rethrowFriendly(error, 'Failed to resume Superserve sandbox');\n        }\n      },\n\n      pauseCapabilities: { memory: true },\n    },\n\n    snapshot: {\n      // Snapshots hold memory and disk: restores keep the whole filesystem,\n      // tmpfs /tmp included, and running processes. The source keeps running.\n      capabilities: { scope: 'rootfs', memory: true, destroysSource: false },\n      create: async (config: SuperserveConfig, sandboxId: string, options?: { name?: string }) => {\n        const apiKey = resolveApiKey(config);\n        const baseUrl = resolveBaseUrl(config);\n        try {\n          // connect() activates the sandbox, so a paused one is resumed first.\n          const sandbox = await SuperserveSandbox.connect(sandboxId, { apiKey, baseUrl });\n          return toSnapshot(await sandbox.snapshot({ name: options?.name }));\n        } catch (error) {\n          rethrowFriendly(error, 'Failed to create Superserve snapshot');\n        }\n      },\n      list: async (config: SuperserveConfig, options?: { sandboxId?: string; limit?: number }) => {\n        // Snapshots are listed per sandbox. Callers that aggregate across\n        // providers pass no options, so an unscoped call returns nothing\n        // instead of throwing and failing their whole listing.\n        if (!options?.sandboxId) return [];\n        const apiKey = resolveApiKey(config);\n        const baseUrl = resolveBaseUrl(config);\n        const infos = await SuperserveSnapshot.list(options.sandboxId, { apiKey, baseUrl, limit: options.limit });\n        return infos.map(toSnapshot);\n      },\n      delete: async (config: SuperserveConfig, snapshotId: string) => {\n        const apiKey = resolveApiKey(config);\n        const baseUrl = resolveBaseUrl(config);\n        await SuperserveSnapshot.deleteById(snapshotId, { apiKey, baseUrl });\n      },\n    },\n\n    template: {\n      create: async (config: SuperserveConfig, options: SuperserveTemplateCreateOptions) => {\n        const apiKey = resolveApiKey(config);\n        const baseUrl = resolveBaseUrl(config);\n        const { name, from, vcpu, memoryMib, diskMib, steps, startCmd, readyCmd } = options;\n        if (!from) {\n          throw new Error('Superserve templates are built from an image: pass `from` (e.g. \"node:22\").');\n        }\n        try {\n          const template = await SuperserveTemplate.create({\n            apiKey, baseUrl, name, from, vcpu, memoryMib, diskMib, steps, startCmd, readyCmd,\n          });\n          return toTemplate(await template.waitUntilReady());\n        } catch (error) {\n          rethrowFriendly(error, 'Failed to create Superserve template');\n        }\n      },\n      list: async (config: SuperserveConfig) => {\n        const apiKey = resolveApiKey(config);\n        const baseUrl = resolveBaseUrl(config);\n        try {\n          const infos = await SuperserveTemplate.list({ apiKey, baseUrl });\n          return infos.map(toTemplate);\n        } catch {\n          return [];\n        }\n      },\n      delete: async (config: SuperserveConfig, templateId: string) => {\n        const apiKey = resolveApiKey(config);\n        const baseUrl = resolveBaseUrl(config);\n        try {\n          await SuperserveTemplate.deleteById(templateId, { apiKey, baseUrl });\n        } catch {\n          /* already deleted */\n        }\n      },\n    },\n  },\n});\n\nexport type { Sandbox as SuperserveSandbox } from '@superserve/sdk';\n"],"mappings":";AAMA,SAAS,kBAAkB;AAC3B;AAAA,EACE;AAAA,EACA;AAAA,EACA,WAAW;AAAA,EACX,YAAY;AAAA,EACZ,YAAY;AAAA,OACP;AAEP,SAAS,gBAAgB,gBAAgB,mBAAmB,8BAA8B;AAE1F,IAAM,qBAAqB;AA8BpB,IAAM,4BAAkF,OAAO,OAAO;AAAA,EAC3G,IAAI;AAAA,EACJ,IAAI;AAAA,EACJ,IAAI;AAAA,EACJ,IAAI;AAAA,EACJ,IAAI;AAAA,EACJ,OAAO;AACT,CAAC;AAGD,IAAM,6BAA+D,OAAO,OAAO,EAAE,mBAAmB,KAAK,CAAC;AAG9G,IAAM,iBAAiB,CAAC,cAAc,cAAc,aAAa,gBAAgB,cAAc;AAC/F,IAAM,sBAAsB,CAAC,QAAQ,aAAa,aAAa,gBAAgB,SAAS;AAExF,SAAS,eAAe,QAA0B,WAAkD;AAClG,QAAM,OAAO,OAAO,gBAAgB,SAAS,KAAK,0BAA0B,SAAS;AACrF,SAAO,OAAO,SAAS,YAAY,KAAK,KAAK,IAAI,OAAO;AAC1D;AAGA,SAAS,oBAAoB,QAA0B,YAAqB,OAAoC;AAC9G,MAAI,OAAO,eAAe,YAAY,EAAE,iBAAiB,eAAgB,QAAO;AAChF,QAAM,YAAa,OAAO,KAAK,sB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